Вы находитесь на странице: 1из 403

1

MSDN Library MSDN Magazine

Microsoft

ADO.NET

licrosoft

SQL Server

Microsoft*

Microsoft5
TM

. .

2003

fii. P I 1 P E 1 i 1 1

004.45
32.973.26-018.2
57

57

, I: Microsoft ADO.NET, Microsoft SQL Server,


/. ... .: -
, 2003. - 400 .: .
ISBN 5-7502-0234-8
MSDN
Magazine/ Microsoft MSDN Library.
, . , ,
, 20 .
004.45
32.973.26-018.2
.NET. ActiveSync, ActiveX, IntelliSense. JScript, Microsoft, Microsoft Press, MSDN,
Outlook. SQL Server, VBScript, Visual Basic, Visual C+-. Visual J++, Visual Studio,
Win32, Windows Windows NT ,
Microsoft / . NT Northern Telecom Limited.
.
, , URL Web-, .

ISBN 5-7502-0234-8

Microsoft Corporation CMP Media LLC, 200:i

, 2003

, 1:
Microsoft ADO.NET, Microsoft SQL Server,

. .

. ,

. .

. .

. .

127, , . , .9
.: (095) 112-0571. ./: {091)) 145-4519,e-mail: info@rusedit.ru, http://www.riistxlil.ru

14.03.03 . 5000 . 70x100/16. . . . 25


* 1(17105. , . . , Ad

Microsoft ADO.NET

. , ,
.NET


ADO.NET:

81


ADO.NET
.NET Data Access Framework

102

122

ADO.NET



ADO.NET-

133



.NET

152

Microsoft SQL Server

167



SQL

169


SQL
SQL Server 2000 VBScript-

179


SQLServer DMO
SQL Server

194

,
SQL XML
Web

213



SQL Server 2.0 .NET Compact Framework

239


SQLServer
Notification Services

259

273


.NET Reflection
SQL

275

303

317

PataRelation ADO.NET


.NET

326



Web
346

ADO XML:
DataManager

360


Spider .NET Web-
Visual Basic .NET ADO.NET

370



.NET ..

... 385

!
, ( ). .
MSDN Magazine Microsoft MSDN Library
.
, , ,
MSDN Magazine MSDN Library 2000-2003 .
, , MSDN
Magazine/ , , .
, ,
.

Microsoft ADO.NET. .NET, ADO.NET, , (expressions) ADO.NET, .

Microsoft SQL Server. 2001-2002 .


SQL-, SQL, SQL-DMO SQL Server 7.0 SQL Server 2000, SQL Server XML- , Notification Services,
SQL Server CE 2.0 ,

.

SQL .NET Reflection, ADO.NET- DataRelation, , DataManager (
, ADO), Web-
ADO.NET, + MTS (Microsoft Transaction Services),
.NET-, ADO.NET.
,
, ( )
Web- * www.rusedit.ru/
download/code_ap I .zip.
, ASP.NET
-, HTTP-,
ASP.NET, ,
Web-,
Web-.

.NET Framework ( , , ,
. .), , .NET, /
.
MSDN Magazine MSDN Library, www.rusedit.tu almanah@rusedit.ru.
.

, , ,



.NET

ADO.NET
.NET-.
,
.
.

.NET- Microsoft ADO.NET. ADO.NET


, Web- Web-. , ADO.NET
.
.
, . , : ?
(connection pooling)? ? (paging),
?

Alex Mackman, Chris Brooks, Steve Busby, and Ed Jezierski .NET Data Access Architecture
Guide//MSDN Library. Microsoft Corporation. 2001. October. - . .

Microsoft ADC.NET

,
ADO.NET Microsoft SQL Server 2000 SQL Server .NET Data Provider , ADO.NET. , , , OLE
DB .NET Data Provider OLE DB.
,
, , .
Data Access Application Block {http://msdn.microsoft.com/library/en-us/
dnbda/html/daab-rm.asp). ,
,
.NET-.


,
.NET-. , .NET-.


.NET-, ADO (ActiveX Data Objects) / OLE DB,
SQL Server. , .NET, , ADO.NET. .NET
. http://msdn.microsoft.com/net.

ADO.NET
ADO.NET .NET- . , SQL Server 2000,
, OLE DB. ADO.NET ADO.
ADO.NET , Web- ,
. ADO ADO.NET .
ADO.NET for the ADO Programmer MSDN.

-NET

1.1

ADO.NET ADO- Recordset


DataTable, DataSet, DataAdapter DataReader.
DataTable (collection)
Recordset. DataSet DataTable, ,
. DataSet XML (Extensible Markup Language).
DataSet , , .
, ,
. , DataSet XML,
. DataAdapter ADO.NET DataSet . DataAdapter

, Recordset.
. 1 DataSet.
DataSet

Table

I|

Column

Constraints
*|

Constraint

Row

Relation
. 1.

DataSet

-NET
ADO.NET (Data
Providers) .NET. -

12

Microsoft ADO.NET

(Connection, Command,
DataReader DataAdapter). ADO.NET :

SQL Server .NET Data Provider.


Microsoft SQL Server 7.0 . SQL Server
SQL Server.
SQL Server 7.0
SQL Server 2000.

OLE DB .NET Data Provider.


OLE DB. SQL Server
.NET Data Provider, OLE DB. , OLE DB ODBC (Open Database Connectivity).
ODBC ODBC .NET Data Provider,
. OLE DB,
ADO.NET, . http://msdn.microsoft.com/library/en-us/
cpguidnf/html/cpconadonetproviders.asp.
.NET
-.

ODBC .NET Data Provider.


-.
ODBC- , OLE DB .NET Data Provider OLE DB.
ODBC .NET - http://msdn,
microsoft, com/downloads/default, asp? URL=/code/sample.asp?url=/
MSDN-FILES/027/001/668/msdncompositedoc.xml.

XML SQL Server 2000.


XML for SQL Server Web update 2 ( ) , , , XML SQL Server
2000. . http://msdn.microson^com/code/default.asp?url=/code/sam
msdn-files/027/001/602/msdncompositedoc.xml.


(, , ..),
.NET, .

System.Data.SqlClient. SQL Server .NET Data Provider,

.NET

13

System.Data.OleDb. OLE DB .NET Data Provider.

System.Data.dbc. ODBC .NET Data Provider.


System.Data. , ,
DataSet H'DataTable.
Connection, Command, DataReader DataAdapter.
SqlClient <<Sql, OleDb OleDb. , Connection
SqlClient SqlConnection,
OleDb OleDbConnection. DataAdapter SqlDataAdapter OleDbDataAdapter.


, IDbConnection, IDbCommand, IDataReader I Db Data Adapter, System.Data.
Connection, Command, DataReader DataAdapter .
.NET .
http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconimplementingnetdataprovider.asp.
. 2 ADO.NET
ADO.NET , ADO
OLE DB. ,
, ADO.NET.
ADO ADO.NET .
Introducing ADO+: Data Access Services for the Microsoft .NET Framework, MSDN Magazine 2000 .

SQL
,
, SqlCommand , .
SqlCommand, SqlDataAdapter. SqlCommand.

Microsoft ADO,NET

34


.NET

AOO.NET

DataSet

QLfDB Data Pimlder


E

SQL Server .NET DataReader


TDS

Oracle,

SQL Server

Access .

6.5

. 2.

SQL Server
7.0

, SQL
.

, , , .


.
,
.

,
, SQL.

-NET


.
- ,
.

, SQL , .


ADO.NET . , :
// Command
SqlCommand cmd = new SqlCommand( "SELECT - FROM PRODUCTS", conn );
//
// ,
sqlCommand cmd = new SqlCommandO;
cmd.Connection = conn;
cmd.CommandText = "SELECT * FROM PRODUCTS";
, ,
.NET- -,

.
(
ADO.NET) .
Microsoft Visual Basic
Dim x As New.
-, . .NET .


, , Web-. , . ,
, . .

Microsoft ADO.NET

, :

Windows SQL
Server;

(impersonation) ;

,
.

,

.
, . , , .



. ,
. , ,
.
, ODBC OLE DB, , . , . OLE
DB (session pooling) (resource
pooling).
MDAC (Microsoft Data
Access Components) . http://msdn.microsoft.com/library/en-us/
dnmdac/html/pooling2.asp.
ADO. NET , -

.(

17

.
:

SQ.L Server .NET Data Provider (http://msdn.microsoit.com/library/erius/dnbda/html/#daag_sqlserverproviderpooling);

OLE DB .NET Data Provider (http://msdn.microsoft.com/library/en-us/


dnbda/html/#daag_oledbproviderpooling).


SQL Server .NET Data Provider
SQL Server .NET Data Provider, , .
, .
.
,
, ,


SQL Server .NET Data Provider
-,
. , , ( ), , , .
,
.
"Server=(local); Integrated Security=SSPI; Database=Northwind;
Max Pool Slze=75; Min Pool Slze=5"

, , , .
,
, . , .


,
.

IS

Microsoft ADO.NET

, . ,
SQL Server.
, ,
(100), .
, , .
, , . .
.
.
.
,
, . http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconconnectionpoolingforsqlservernetdataprovider.asp.

SQL Server .NET Data Provider
.


(exact match algorithm) .
-.
,
- ,
.
SqlConnection conn = new SqlConnection(
"Inteflrated Security=SSPI;Database=Northwind");
conn.0pen(); //
SqlConmection conn = new SqlConnection(
"Integrated Security=SSPI ; Database=Northwlnd");
conn.0pen(); // ( )

- .NET Framework
. (debug), (release)
. RTM- (Released To Manufacture) .NET Framework , .

.NET

19


,
. , , , , . , , .


OLE DB .NET Data Provider
OLE DB .NET Data Provider ,

OLE DB. :

, ;

, , OLE DB.
OLE DB . MSDN
OLE DB Programmer's Reference ( 19 OLE DB Services, Resource Pooling).



Windows DNA, OLE DB / ODBC +.
:


( + Catalog);

2 .

, SQL Server .NET Data Provider ,


. , ,
(manual transaction enlistment).

Microsoft ADO.NET

20

OLE DB .NET Data Provider, ,


+. (pooled object), OLE DB (,
OLE DB Services=-4).
.


, ,
Profiler, SQL Server,
Performance Monitor Microsoft Windows 2000.
Profiler .
1.

Start Programs Microsoft SQL Server Profiler Profiler.

2. File | New Trace.


3.

4.

Trace Properties Events.

5. Selected event classes , Security Audit Audit Login Audit Logout.


, .
6.

Run, . Audit
Login , Audit Logout
.

Performance Monitor .
1. Start Programs Administrative Tools | Performance Performance Monitor.
2. , , Add Counters.
3.

Performance object SQL Server: General Statistics.

4.

User Connections.

5.

Add, Close.

RTM- .NET Framework


, Performance Monitor -

.NET

21

SQL Server
.NET Data Provider.


,
. , , .
, ,
, ( ); , .

Windows
SQL Server
Windows, .

,
( Windows), SQL Server.

, .


SQL Server Windows , .

.NET Beta 2 , Windows


, SQL Server. , Windows , ,
.
Windows
.
, Windows SQL Server
RTM- .NET Framework.

22

Microsoft ADO.NET


Windows Windows.
( SQL Server) ,
, .
, , Windows,
SQL Server Windows,
.
, , .

Windows: ,
. ( , , . ,

, , , / .)

,
SQL Server, .

- , Windows SQL
Server.

,
IIS (Internet Information Services) SQL Server, ;
(
) .

TCP/IP
SQL Server 7.0
Windows . TCP/IP,
, . TCP/IP .
.


, . -

.NET

* , , , ,
. , , ,
.
: ;
.
:

(http://msdn.microsoft.com/library/
en-us/dnbda/html/#daag_usingxmlappconfigfiles),
Web.config Web- ASP.NET;

UDL- (Universal Data Link) (http://msdn.microsoft.com/Iibrary/


en-us/dnbda/html/#daag_usingudlfiles)
OLE DB .NET Data Provider;

Windows (http://rnsdn.microsoft.com/library/en-us/dnbda/
html/#daag_usingwindows registry);

(http://msdn.microsoft.com/library/en-us/dnbda/
html/#daag_usingcustomfiles);

COM+ Catalog (http://msdn.microsoft.com/library/en-us/dnbda/html/


#daag_usingcomplusconstructionstrings), ( ),

SQL Server Windows


.
, .
Web- ASP.NET Web.config.
Persist Security Info
false, , ,
, ConnectionString SqIConnection
OleDbConnection.
, ,
.
, .

24

Microsoft ADO.NET


XML-

<appSettings> . -, .
<configuration>
<appSettings>
Odd key="DBConnStr"
value="server=(local);Integrated Security=SSPI;database=northwind"/>
</appSettings>
</configuratlon>
<appSettings> <configuration>,
<system.web>.

. , .NET.

. AppSettings
ConfigurationSettings .

( ASP.NET).
Web.config,
,
(stateless component),

.

. DLL ISAPI (Internet Server


Application Programming Interface) ASP.NET .config,
NTFS,
Web-, . .

.NET

(custom), , Settings
System.Configuration.ConfigurationSettings. , ,
DBConnStr:
using System.Configuration;
private string GetDBaseConnectionStringO
{
return ConfigurationSettings.AppSettings["DBConnStr"];

.NET
Framework . http://msdn.microsoft.com/library/en-us/
cpguidnf/html/cpconconfiguringnetframeworkapplications.asp.

UDL-
OLE DB .NET Data Provider
UDL- (Universal Data Link).
OleDbConnection
ConnectionString ,
SQL Server .NET Data Provider UDL-
. , OLE
DB .NET Data Provider.

OLE DB UDL- File Name=name.udl>>.

. , UDL-
.

.
UDL- .

. UDL- . NTFS,
, .config.

SqlClient UDL-. SQL Server .NET Data Provider, SQL


Server 7.0 .

26

Microsoft ADO.NET

, /, ,
, . Web- AS.P.NET
SYSTEM, < process Model >
(Machine.config). ,
( ) <identity> Web.config.

Web-, , DDL- ,
Web.

ASP.NET,
, . http://msdn.rnicrosoft.com/
library /en-us/dnbda/html/authaspdotnet.asp.

Windows

Windows, ,
.

. (access control lists,


ACL). .

. .NET ,
.

.
,
.


.
,

.NET

27

.

.

. ASP.NET. ASP.NET ,
Web.

+ Catalog
+ Catalog

(object construction string). COM+ Construct ,
.
(serviced components). , , .

.
Component Services .

. + Catalog
( +), .

. + Catalog .NET-. , ,
, + Catalog
.

.
. ServicedComponent (
) , .

28

Microsoft ADO. NET

, .NET- (object construction), .


.NET- (http://msdn.microsoft.com/
library /en-us/dnbda/html/#daag_howtoenableobjectconstruction).

.
http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpconwritmgservicedcomponents.asp.


.NET .

. ,
Close Dispose. , , .
. , (object pooler), , .

, , , (. ). finally,
using #,
Dispose .

finally. , #, Visual
Basic .NET, (structured exception handling, SEH).
public void DoSomeWorkO
{
SqlConnection conn = new SqlConnection{connectionString);
SqlCommand cmd == new SqlCommandC'CommandProc", conn );
cmd.CommandType = CommandType.StoredProcedure;
try

conn.0pen();
cmd . ExecuteNonQue ry( ) ;

.NET

29

catch (Exception e)
//
finally
conn.CloseO;

using #. ., Visual Basic


.NET using .
public void DoSomeWorkC)
// using , conn
// Dispose, .
using (SqlConnection conn = new SqlConnection(connectionString))
SqlCommand cmd = new SqlCommandC'CommandProc", conn);
fcmd.CommandType = CommandType.StoredProcedure;
conn.0pen();
cmd.ExecuteQue ry();

, SqlDataReader
OleDbDataReader, ,
- .


ADO.NET
SEH .NET Framework. , , .

.NET .
,
, , .
,
SQL Server .NET Data Provider.

.NET-
.NET ,
, ., -

30

Microsoft ADO.NET

. ,
, .
.NET-
Exception System. .NET
, .
, SQL Server .NET Data Provider SqlException, SQL Server . OLE
DB .NET Data Provider OleDbException
, OLE DB.
. 3 ,
.NET , OleDbException ExternalException COM Interop.
ErrorCode COM HRESULT,
OLE DB.
Exception

Exception

System Except! cm
SqlException

SQL Server .NET


Data Provider

System Exception
External Except! on

OLEDB.I\
Data Prov

CT

OleDbException

lei

. . .NET

.NET-

try
catch . , , SQL Server .NET Data Provider,
SqlException, , .
try

//
\
catch (SqlException sqlex) //
I
>
catch (Exception ex) //
// ( )
'.

.NET

31

catch ,

( ).
catch.
SqlException ;

Message , ;

Number , ;

State . , , , State
, ;

Errors (collection) , SQL Server.


SqlError.

,
, SQL Server SQL Server .NET Data
Provider.
using System.Data;
using System.Data.SqlCllent;
using System.Diagnostics;
// , DAL (Data Access Layer)
public string GetProductNameC int ProductID )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
// try
try
I
conn.OpenO;
SqlCommand cmd = new SqlCommand("LookupProductName", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ProductID", ProductID );
SqlParameter paramPN =
cmd.Parameters.Add("@ProductName", SqlDbType.VarChar, 40 );
paramPN.Direction = ParameterDirection.Output;
cmd.ExecuteNonQueryO;
// finally ,
return paramPN.Value.ToStringO;

32

Microsoft ADO.NET

catch (SqlException sqlex)


{
// , ,
//
LogException(sqlex);
//
//
throw new DALException(
"Unknown ProductID: " + ProductlO.ToStringO, sqlex );
}
catch (Exception ex)
{
// . . .
throw ex;
}
finally
I
conn.Close(); //

\
// , SqlException
//
private void LogExceptionC SqlException sqlex )
{
EventLog el = new EventLogO;
el. Source = "CustomAppLog";
string strMessage;
strMessage = "Exception Number : " + sqlex. Number +
"(" + sqlex. Message + ") has occurred";
el.WriteEntry< strMessage );
foreach (SqlError sqle in sqlex. Errors)
{
strMessage = "Message: " + sqle. Message +
" Number: " + sqle. Number +
Procedure: " + sqle. Procedure +
" Server: " + sqle. Server +
" Source: " + sqle. Source +
" State: " + sqle. State +
" Severity: " + sqle. Class +
'" LineNumber: " + sqle, LineNumber;
el.Writentry( strMessage );
)
!

catch SqlException LogException. foreach Errors, . -

,NT

33

SQL Server DALException,


, GetProductName.

throw.

SqlException . http://
msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemDataSqlClientSql Except ion Members Topi c. asp.

,
.NET- ,
.
http://msdn.microsoft.coni/library /default. asp?url=/library/en-us/dnbda/html/exceptdotnet.asp.


Transact-SQL (T-SQL) RAISERROR ( ),
. ADO.NET SQL
Server .NET Data Provider
SqlError.
RAISERROR , , (severity) :
RAISERROFK 'Unknown Product ID: X s ' , 16, 1, @ProductID )

,
. , .

, sysinessag'es, sp_addmessage Enterprise Manager SQL


Server. ,
RAISERROR.
50 000;
RAISERROFU 50001, 16, 1, ProductID )

RAISERROR
SQL Server Books Online.

2-5947

Microsoft ADO.NET


(severity levels) . 0 25
, SQL Server 2000. Class SqlError, Errors SqlException. . 1
.
. 1. :



SqlException

10

11-16

17-19

20-25

,


,
,




( );


10 SQL Server
.NET Data Provider SqlException.
( +) SqlException, * .
,
AutoComplete
SqlException . *- .


10 SqlException.

.NT

35

,
.

InfoMessage SqlConnection. .
public delegate void SqlInfoMessageEventHandler( object sender,
SqllnfoMessageEventArgs e );

SqllnfoMessageEventArgs, .
Errors, SqlError
. , , .
public string GetProductName{ int ProductID )
(
SqlConnection conn = new SqlConnectionf
"serve r=(local); Integrated Security=SSPI;database=northwind");
try
i
//
conn. InfoMessage += new SqlInfoMessageEventHandler(
MessageEventHandler };
conn.0pen();
//
catch (SqlException sqlex)
{
//

finally
<
conn.CloseO;
//
void HessageEventHandler( object sender, SqllnfoMessageEventArgs e )
{
foreach( SqlError sqle in e. Errors )
i
// SqlError

36

Microsoft ADO.NET


, , , ADO.NET. , , , .
.

. (result
set), .

. .

. (item) .

. , .
,
.


, . ,
, XML- (, Web-). :
HTML-.

, , :
DataSet SqlDataReader,
Web-
(business-to consumer,
2). . 4.
SqIDataAdapter, DataSet, SqlDataReader.

SqIDataAdapter DataSet
DataTable.

,NET

37

XML
XML-
(Web- /

&

. 4.

SqlDataReader
.

XmlReader XML-
.

SqlDataReader DataSet/DataTable
. SqlDataReader , a DataSet
.



, (data-bound controls),
DataSet DataTable , SqlDataReader. , DataSet
DataTable IListSource ( IList),
SqlDataReader lEnumerable. Windows Forms ,
IList,
,
DataSet ( DataTable)
, Web-, Windows

38

Microsoft ADO.NET

Forms. , (data reader) Web-, .


, .


DataSet , XML, .
SqlDataReader
- , DataSet. ,
DataSet DataTable, DataRow DataColumn -
.

DataSet
DataSet, SqlDataAdapter, :
,
;

, XML, ;

, , , ;

,
, SqlDataAdapter;

, , IList.

SqlDataAdapter DataSet DataTable.
.
. Fill SqlDataAdapter
, .
, Fill .

- ,
Fill. /
.

-NET

39

SqlCommand , (
SQL ), .

, , Sql Data Adapter DataSet DataTable, . : SqlDataAdapter .

SqIDataReader
SqIDataReader, ExecuteReader SqlCommand, :

,
;

, ;

, DataSet;

, , lEnumerable;

;
, (binary large objects, BLOB). SqIDataReader BLOB- .
BLOB .
(BLOB).


SqIDataReader .

, .
Close SqIDataReader .

~ , ,
SqIDataReader, ExecuteReader mandBehavior.CloseConnection. , , SqIDataReader,

- (typed accessor methods) (, GetInt32 GetString), , -

Microsoft ADO.NET

40

,
.


,
, Cancel
Close . Cancel ,
.
Close , , ,

, .


ExecuteReader
SqlCommand, Close
.

, , SqlDataReader, . SqlDataReader .

XmlReader
XmlReader, ExecuteXmlReader SqlCommand, .

XML,
, DataSet, .

FOR XML SQL, XML- (. . XML ). ,


, ,
, (element or attribute-centric schema),
XML- . .


XmlReader, .

,
XmlReader . ExecuteXmlReader
SqlCommand CommandBehavior.CloseConnection, , .

.NET

41

, , XmlReader,
. XmlReader
.


, . , - ,
.


, , Sql Data Adapter DataSet
DataTable , .
DataSet/DataTable ,
.
:
;

SqlDataReader.

,
DataSet . , . ,
( 200 )
30% , SqlDataReader.



, :

Web-,
.

, , , . : .

42

Microsoft ADO.NET

SqIDataReader
SqIDataReader, :

, .
GetSchemaTable
;

. SqIDataReader ; , 200 SqIDataReader


20% ,
.

, ,
ExecuteReader SqlCommand ConimandBehavior.SingleRow. , OLE DB
.NET Data Provider, . CommandBehavior.SingleRow IRow (
), IRowset. SQL
Server .NET Data Provider .

SqIDataReader. - SqIDataReader, GetString GetDecimal. .

, , SqIDataReader , .
SqIDataReader .


. ,
(credit rating) .
, DataSet DataTable.
, , : . , Web-
, ,
. .
.

.NET

43

Execute Scalar SqlCommand, ;

SqlDataReader.

ExecuteScalar ,
, .
, .
, , ,
,
( 100 200).

, ExecuteQuery,
/ , , ,
,

, , ExecuteScalar, .
ExecuteScalar .

, , , .
,

, , SqlDataReader , . SqlDataReader *-.


-
SQL Server (firewall). , Web- (perimeter network) ( DMZ, ), Web-, , .

Microsoft ADO.NET

44

SQL Server
, . SQL Server Client Network Utility Server Network Utility, .


SQL Server TCP/IP. SQL Server
2000 .
SQL Server, , TCP/IP
, .
Client Network Utility Server Network Utility .
, TCP/IP
:

,
.

TCP/IP. , , ,
SQL Server.


SQL Server 1433.
(named instances) SQL Server 2000 .
, , SQL
Server , Server Network Utility
. , IP- , .
, ,
1024-5000.
TCP/IP, , , . ,
SQL Server, . Microsoft Product Support Services INF: TCP Ports
Needed for Communication to SQL Server Through a Firewall (http://msdn.microsoft.com/isapi/gosu ppoit.asp?Target=/support/kb/articles/Q287/9/32.ASP).

.NET

45


, SQL Server , . . .
SQL Server 2000, , ,
. SQL Server,
MDAC ( 2.6)
UDP (User Datagram Protocol) UDP- 1434.
,
, UDP.
,
.


SQL Server TCP/IP. , ,
.

TCP/IP
Client Network Utility,
SQL Server. . TCP/IP .

- (Network Library=dbmssocn). dbmssocn TCP/


1-.

SQL Server .NET Data Provider dbmssocn .

, TCP/IP . SQL Server . HOWTO: Change SQL


Server Default Network Library Without Using Client Network Utility
(Q250550) (http://msdn.microsoft.com/isapi/gosupport.asp?Target=/
support/kb/articles/Q250/5/50.ASP).

46

Microsoft A.DO.NET


SQL Server , 1433 , :

Client Network Utility;

- (Server Data Source), . :


"Data Source=ServerName, PortNumber"

ServerName IP- DNS-. IP-, DNS.


, + Microsoft
DTC (Distributed Transaction Coordinator), DTC DTC DTC (, SQL Server).
DTC . INFO:
Configuring Microsoft Distributed Transaction Coordinator (DTC) to Work
Through a Firewall (http://msdn.microsoft.com/isapi/gosupport.asp7Target=/support/kb/articles/Q250/3/67.ASP).

(BLOB)
,
, , . ,
. , ,
,
(Binary Large Objects, BLOB).
SQL Server BLOB binary,
varbinary image. BLOB- . , , .
SQL Server ntext text.

,NET

, 8
varbinary,
image. . 2
,
. 2.

binary

1 8000 .


4 .

varbinary

1 8000 .

4 .

image


0 2 .

text


0 2 .

ntext


0 2 .


Unicode

BLOB
SQL Server 7.0 BLOB, . 8 .
8 . . ,
/ text, ntext image ,
/ .
8 ,
, .
, ,
text, ntext image , . Using Text and
Image Data SQL Server Books Online.
BLOB-
, ,
(
URL-). SQL Server 7.0 BLOB- .

48

Microsoft ADO.NET

BLOB SQL Server


2000 BLOB ADO.NET BLOB .
BLOB
BLOB .

BLOB- .

BLOB .
.

BLOB XML, SQL


Server 2000. base 64
XML.

, ( Unicode),
(Full Text Search, FTS) SQL Server.
, FTS-
, image,
Microsoft Word Microsoft Excel.

BLOB
, ADO.NET
, , SQL Server
image.
public void StorePicture( string filename )
{
//
FileStream fs = new FileStream(
filename, FileMode.Open, FileAccess.Read );
byte[] imageData = new Byte[fs.Length];
fs.Read( imageOata, 0, (int)fs.Length );
fs.Closef);
SqlConnection conn = new SqlConnectionC'");
SqlCommand cmd = new SqlCommand("StorePicture", conn);
cmd.CoinmandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@filename", filename );
cmd.Parameters["filename"].Direction = ParameterDirection.Input;
cmd.Parameters.AcJd("@blobdata", SqlDbType. Image);
cmd.Parameter$["@blobdata"]. Direction = ParafneterDirection.Input;
// image
cmd.Pararoeters["@blobdata"].Value = imageData;
try

,NET

49

conn.OpenO;
cmd.ExecuteNonQueryO;
catch
throw;
finally
conn.CloseO;

BLOB
SqlDataReader ExecuteReader
, BLOB, CommandBehavior.SequentialAccess.
. BLOB, .
CommandBehavior.SequentialAccess
, BLOB-
(, GetBytes, ). .
// , ,
// SELECT IMAGE.
conn.0pen();
SqlDataReader reader = cmd.ExecuteReader(
CommandBehavior.SequentialAccess);
reader. ReadO;
// image;
// - null
long bytesize = reader.GetBytes(Q, 0, null, 0, 0);
// ,
//
byte[] imageData = new byte[bytesize];
long bytesread = 0;
tnt curpos = 0;
while (bytesread < bytesize)
f
// chunkSize - ,
bytesreab += reader.GetBytes(0, curpos, imageData, curpos, chunkSize};
curpos += chunkSize;

}
// imageData BLOB

Microsoft ADO.NET

50

CommandBehavior.SequentialAccess
. , BLOB 3,
1 2 , 3 1 2.

, ,
. .
ACID: (atomicity), (consistency), (isolation) (durability).
, , Web-
, . , :
;

.
: ,
. . .
.
http://msdn.microsoft.com/library/en-us/cpguidnf/html/cpcontransactionprocessingfundamentals.asp.
,
. .

. ,
ADO.NET Transact-SQL, , .

( +).
.NET- (declarative attributes), .
.

.NET

51

(
, SQL Server 2000), ( ,
).
.
( +)
.
, .
.
,
.


, ,
. , , . , .

, ACID.

, , .

SQL-. SQL
Server .


, , , Microsoft DTC.
( ), (,
SQL Server),
(interprocess communication, IPC) DTC,

52

Microsoft ADO.NET

, :
.
, :

;
,
MSMQ (Message Queuing) Windows 2000.

. ,

, ,
( )
. , .


,
ADO.NET Transact-SQL, . , , ADO.NET.

ADO.NET
ADO.NET , ,
, (commit) (roll back) .
; BeginTransaction . , .
,
Transaction .
,
.
ADO.NET . ADO.NET.

.NET

53

ADO.NET
Read Committed. ,
(shared locks),
.
-
(non-repeatable reads), (phantom
data). , IsolationLevel IsolationLevel.

,

. (Serialized)
. ,
, . , , .

(Kalen Delaney) Inside


SQL Server 2000 (Microsoft Press).


Transact-SQL. ,
,
Transact-SQL, BEGIN TRANSACTION, END TRANSACTION ROLLBACK TRANSACTION.


SET TRANSACTION ISOLATION LEVEL. SQL Server
Read Committed. SQL Server . SQL Server Books Online ( Accessing and
Changing Relation Data, Isolation Levels).

, ,
Transact-SQL,
. Transact-SQL.

54

Microsoft AD0.NET


,
/
.
, DTC, , .
, DTC . . ,

, , .
+- , , , . . ,
Serviced Component.
, .

Serviced Component
System. EnterpriseServices,


Transaction. , TransactionOption, , + Catalog.
,
.

( ), AutoComplete.
,
. ,
(transaction outcome). . ,

+
. Platform SDK Automatic Transactions
Through +.

.NET- . .NET.

.NET

55


+ 1.0, . . , Windows 2000,
Serialized. , . , ( )
, . ,
.
+ 1.5, Microsoft .NET, + Catalog . , , .
, , , ,
. .
.NET- Transaction
Isolation. , .
[Transaction(TransactionOption. Supported,
Isolation=TransactionIsolationL.evel.ReadCommitted)]
public class Account : ServicedCotnponent


+ .NET . Windows XP: Make
Your Components More Robust with COM+ 1.5 Innovations*-
MSDN Magazine 2001 .


(transaction abort flag), (consistent
flags) . ,
(. . 5,
).

56

Microsoft ADO.NET

. 5.

, ( Transfer) . - false true, DTC .


.NET-
.

AutoComplete, .NET
.
false
( ). , true, . ,
, , .

SetComplete SetAbort textUtil


true false.

SQL Server 10 ,
SqlExcep-

.NET

57

tion. , , , ,
[AutoComplete], .

[AutoComplete]
AutoComplete
.

SqlException .
SqlException . , ,
.

,
, .
, , .
SqlException, .
, false.
[AutoComplete]
void SomeMethodO

try
{
//
}
catch (SqlException sqlex )
<
LogException( sqlex ); //
throw;
// ,
// false
}
finally
{
//

58

Microsoft ADO.MET

[AutoComplete]
AutoComplete :

Con text Util. Set Abort catch,


. false;

Context UtiLSetComplete, , . true,


.

.
void SomeOtherMetliodO
{
try

//

ContextUtil.SetComplete(); //
I
catch (SqlException sqlex)
{
LogExceptionf sqlex );
//
ContextUtil.SetAbortO; //
// ,
//
>
finally
{
//

catch ContextUtil.SetAbort ContextUtil.SetComplete


try. ContextUtil.SetAbort
catch. , , , .
( -)
,
,
. , Transfer
, , .

.NET

59

false
, ,
. , ,
Boolean , . , .


(data paging) , . ,
,
; , / /.

.

Fill SqlDataAdapter DataSet .

ADO COM Interop


(server-side cursor).

, :

, ;

,
. , -

60

Microsoft ADO.NET

, . ,
, ,
. , , , .
.

SqIDataAdapter
, SqIDataAdapter
DataSet . Fill ( ) .
public int Fill(
DataSet dataSet,
int startRecord,
int

maxRecords,

string srcTable

);

startRecord ( ), a maxRecords
, DataSet, startRecord.
SqIDataAdapter SqlDataReader . SqIDataAdapter
DataSet, SqlDataReader . SqIDataAdapter DataSet , maxRecords , startRecord, . ,
. .
, 1000 ,
900- 950-. 899 ,
. , , ,
.

ADO
ADO
. , ADO- Recordset. CursorLocation Recordset adUseServer,
OLE DB (, ,

.NET

61

SQLOLEDB), .
, .
.

, Recordset, DataSet
. leDb Data Adapter
Fill, ADO- Recordset DataSet,
. , , Recordset,
DataSet. ,
, COM Interop DataSet .

, . ,
, .
,
- .


,
, , . , , . ( )
.



, WHERE
SELECT ,
. SET ROWCOUNT . , .
CREATE PROCEDURE GetProductsPaged
gaastProductID int,

62

Microsoft ADO.NET

int

Size
AS

SET HOWCOUNT @pageSize


SELECT
FROM Products
WHERE [ ]
AND ProductID > lastProductID
ORDER BY [, ProductID ]

GO

, ,
last Product ID
.



, , , , identity-
.

,
, ( ), .
.
Coll

12

13

\
\
\

2
2
I
1

...

X
W
X

Coll, Col2 13. , .


CREATE PROCEDURE RetrieveDataPageu
@lastKey char(40),
&pageSize

AS

int

.NET

03

SET RGWCOUNT @pageSize


SELECT
Coll, Col2. Col3. CoU, Col1+Col2+Col3 As KeyField
FROM SampleTable
WHERE [ ]
AND 11+12+13 > @lastKey
ORDER BY CoU ASC, Col2 ASC, Col3 ASC
GO


KeyField, , .

, . ,
.
,
. , , .


.NET
.NET- ,
Enterprise (COM+) Services, .

ServicedComponent
System.EnterpriseServices.
using System.EnterpriseServices;
public class DataAccessComponent : ServicedComponent

Construction Enabled
(default construction
string). + Catalog.
Component
Services Microsoft Management Console (MMC).

64

Microsoft ADO.NET

11

[ConstructionEnabled(De"fault= default DSN")]


public class DataAccessComponent : ServicedComponent

Construct. , . , + Catalog.
public override void Construct( string constructString )
{
// Construct ,
// - DSN (Data Source Name),
// .
}

(strong name),
AssemblyKeyFile Assembly Key Name. , + Services, . . http:/
/msdn.microsoft.com/library/en-us/cpguidnf/html/cpconworkingwithstrongly-namedassemblies.asp.
[assembly: AssemblyKeyFile("DataServices.snk")]

, (lazy), ApplicationName ApplicationActivation +-,


, . . http://msdn.microsoft.com/library/en-us/
cpguidnf/html/cpconregisteringservicedcomponents.asp.
// ApplicationName +-,
//
[assembly : ApplicationName("DataServices")]

// ApplicationActivation,ActivationOption ,
// :
// Library - ,
// Server - dllhost.exe
[assembly: ApplicationActivation(ActivationOption.Library)]

DataAccessComponent, + .
using Systen;
using System.EnterpriseServices;
// ApplicationName +-,
//

.NET

65

[assembly : ApplicationName("DataServices")]
// ApplicationActivation.ActivationOption .
// :
// Library - ,
// Server - dllhost.exe
[assembly: ApplicationActivation(ActivationOption. Library)]
// . snk
// sn.exe.
[assembly: AssemblyKeyFile("DataServices.snk")]
[Const ructionEnabled(Default="Default DSN")]
public class DataAccessComponent : ServicedComponent
i
private string connectionString;
public DataAccessComponent
{
//
}
public override void Construct( string constructString )
{
// Construct .
// - OSN, .
this. connectionString = constructString;

Sq I Data Adapter

, Sql Data Adapter
, DataSet DataTable.
Northwind, SQL Server.
using System. Data;
using System. Data. SqlClient;
public DataTable RetrieveRowsWithDataTableO
{

using ( SqlConnection conn = new SqlConnection(connectionString) )


<
SqlCommand cmd = new SqlCommandC'DATRetrieveProducts", conn);
cmd.CommanoType = CommandType.StoredProcedure;
SqlDataAdapter da = new SqlDataAdapter( cmd );
DataTable dt = new DataTable("Products");
da.Fill(dt);
return dt;

3 -5947

66

Microsoft ADO.NET

SqlAdapter DataSet DataTable, .


1. SqlCommand SqlConnection ( )
( ).
2. SqlDataAdapter SqlCommand.
3.

DataTable ( DataSet). DataTable.

4.

Fill SqlDataAdapter DataSet


DataTable .

SqIData Reader

, ,
using System.10;
using System.Data;
using System.Data.SqlClient;
public SqlDataReader HetrieveRowsWithDataReader()
1
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommandC'DATRetrieveProducts", conn );
cmd,CommandType = CommandType.StoredProcedure;
try
{
conn.OpenO;
// . CommandBehavior.CloseConnection
// ,
// .
return{ cmd.ExecuteReader( CommandBehavior.CloseConnection ) );
}
catch
<
conn.Closef);
throw;
)
// ,
private void DisplayProductsO
{

SqlDataReader reader = RetrieveRowsWithDataReaderO;


while (reader.Reacf(

.NET

67

Console. WriteLine("{0} {1} {2}",


reader.GetInt32(0).ToString(),
reader. GetString(l) );
}
reader. Close(); // ,
// CommandBenavior
SqlDataReader,
.
1. SqlCommand
SqlConnection.
2. .
3.

SqlDataReader, ExecuteReader
SqlCommand.

4.

Read SqlDataReader - (, Getlnt32 GetString).

5.

, Close.

XmlReader

SqlCommand XmlReader, XML- . ( )
XML. SQL Server 2000
SELECT FOR XML.
.
public void RetrieveAndDisplayRowsWithXmlReaderO
{

SqlConnection conn = new SqlConnection(connectionString);


SqlCommand cmd = new SqlCommand("DATRetrieveProductsXML", conn );
cmd.CommandType = CommandType.StoredProcedure;
try
I
conn.0pen();
XmlTextReader xreader = (XmlTextReader)cmd. ExecuteXmlReaderf);
while ( xreader. Read() )
{
if ( xreader. Name == "PRODUCTS" )
I
string strOutput = xreader. GetAttributeC'ProductlD");

68

Microsoft ADO.NET

strOutput += " ";


strOutput += xreader.GetAttribute("ProductName");
Console. WriteLineC strOutput );

xreader.CloseC);

}
catch
{
throw;
}
finally
{
conn.Close();
}
:

.
CREATE PROCEDURE DATRetrieveProductsXML

AS

SELECT * FROM PRODUCTS


FOR XML AUTO
GO

XML XmlReader, .
1.

SqlComraand , XML (,
FOR XML SELECT). SqlCommand
.

2.

ExecuteXmlReadcr SqlCommand
XmlTextReader .
XmlReader, ,
XML- .

3. Read XmlTextReader.



, . , Products Nortlrwind.

.NET

69

void GetProductDetails( int ProductID,


out string ProductName, out decimal UnitPrice )
i
SqlConnection conn = new SqlConnection(
"server=( local) integrated Security=SSPI;database=Northwind");
//
SqlCommand cmd = new SqlCommandC "DATGetProductDetailsSPOutput", conn );
cmd.CommandType = CommandType.StoredProcedure;
// :
// @ProductID int INPUT
// @ProductName nvarchar(40) OUTPUT
// @UnitPrice money OUTPUT
//
SqlParameter paramProdlD =
cmd. Parameters. Add( "ProductID", ProductID );
paramProdlD. Direction = ParameterDirection. Input;
SqlParameter paramProdName =
cmd . Parameters. Add( "^ProductName", SqlDbType . VarCtiar, 40 ) ;
paramProdName. Direction = ParameterDirection. Output;
SqlParameter paramUnitPrice =
cmd. Parameters. Add( "@UnitPrice", SqlDbType. Money );
paramUnitPrice. Direct ion = ParameterDirection. Output;
try
<
conn.OpenQ;

// ExecuteNonQuery.
// ,
// ( , ).
cmd . ExecuteNonQuery( ) ;
//
ProductName = paramProdName. Value. ToString();
UnitPrice = (decimal)paramUnitPrice. Value;
}
catch
(
throw;
}
finally
{
conn.CloseO;

, .
1.

SqlCommand SqlConnection.

70

2.

Microsoft ADO.NET

, Add
Parameters SqlCommand. ,
.

,
.

3.

4.

ExecuteNon Query SqlCoramand. (, , ).

5.

Value Sql Parameter.

6.

.
CREATE PROCEDURE DATGetProductDetailsSPOutput
eProductID int,
@ProductName nvarchar(40) OUTPUT,
@UnitPrice money OUTPUT
AS

SELECT eProductName = ProductName,


9UnltPrice = UnitPrtce
FROM Products
WHERE ProductID = ProductID
GO

SqIDataReader
SqIDataReader ,

. .
void GetProductDetailsUslngReader( int ProductID,
out string ProductName, out decimal UnitPrice )
{
SqlConnection conn = new SqlConnection(
"server=(local>;Integrated Security=SSPI;database=Northwind");
//
SqlCommand cmd = new SqlCommand{ "DATGetProductDetailsReader", conn );
cmd.CommandType = CommandType.StoredProcedure;
//
// ProductID int INPUT
SqlParameter paraiflProdlD = cmd.Parameters.Add( "@ProductID", ProductID );
paramProdlD.Direction = ParameterDirection.Input;

.NET

71

try

conn.OpenO;
SqlDataReader reader = cmd.ExecuteReaderf);
reader. ReadO; //
//
ProductName = reader. GetString(O);
UnitPrice = reader. GetDecimal(l);
reader. Closef);

}
catch
{
throw;

}
finally
{
conn.CloseO;

SqlDataReader
.
1.

SqlCommand.

2.

3.

ExecuteReader SqlCommand,
SqlDataReader.

4. - SqlDataReader ( GetString GetDecimal).


,
CREATE PROCEDURE DATGetProductDetailsReader
&ProductID int
AS

SELECT ProductName, UnitPrice FROM Products


WHERE ProductlD = @ProductID
GO

ExecuteScalar
ExecuteScalar ,
. / ,
ExecuteScalar .
, .

72

Microsoft ADG.NET

void GetProductNameExecuteScalar{ int ProductID, out string ProductName )


{

SqlConnection conn = new SqlConnection(


"server=(local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommand("LookupProductNameScalar", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ProductID", ProductID );
try
{
conn.0pen();
ProductName = (string)cind. ExecuteScalar();
}
catch
{
throw;
}
finally
{
conn.Close();
}
;
ExecuteScalar,
.
1. SqlCommand .
2.

3.

ExecuteScalar. ,
,
.

4. .
.
CREATE PROCEDURE
ProductID int
AS

LookupProductNameScalar

SELECT TOP 1 ProductName


FROM Products
WHERE ProductID = tProductID
GO

.NET

73





. .
void GetProductNaraeUsingSPOutpuU int ProductID, out string ProductName )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommandC'LookupProductNameSPOutput", conn );
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter paramProdID = cmd.Parameters.Add("ProductID", ProductID );
ParamProdlD.Direction = ParameterDirection.Input;
SqlParameter paramPN =
cind.Parameters.Add("@>ProductName", SqlObType.VarChar, 40 );
paramPN.Direction = ParameterDirectlon.Output;
try
I
conn.OpenO;
cmd.ExecuteNonQue ry();
ProductName = paramPN. Value. ToStringO;
}
catch
{
throw;
}
finally
{
conn.Close();
}
I

.
1. SqlCommand .
2.

, SqlParameter Parameters SqlCommand.

3. .
4.

ExecuteNonQuery SqlCommand.

5.

6.

Value SqlParameter.

74

Microsoft ADO.NET


.
CREATE PROCEDURE LookupProductNameSPOutput
SProductlD int,
@ProductName nvarchar(40) OUTPUT
AS

SELECT @ProductName = ProductName


FROM Products
WHERE ProductID = @ProductID

GO

, , . , ,
SqlParameter ParameterDirection. Return Value.
bool CheckProduct( int ProductID )
(
SqlConnectIon conn = new SqlConnection{
"server={local);Integrated Security=SSPI;database=northwind");
SqlCommand cmd = new SqlCommandC'CheckProductSP", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ProductID", ProductID );
SqlParameter paramRet =
cmd.Parameters.Add("@ProductExists", SqlDbType.Int );
paramRet.Direction = ParameterDirection.ReturnValue;
try

conn.0pen();
cmd.ExecuteNonQuery();

\
catch
{
throw;

}
finally
conn.CloseO;
}
return (int)paramRet.Value == 1;
J

,
.
1.

SqlCommand .

,NET

75

2. ,
, .
3.

. SqlParameter Parameters SQLCommand ParameterDirection.RetumValue.

4. .
5.

ExecuteNonQuery SqlCommand.

6. .
7. Value SqlParameter.

.
CREATE PROCEDURE CheckProductSP
isProductlD int
AS

IF EXISTSC SELECT ProductID


FROM Products

WHERE ProductID = @ProductID )


return 1
ELSE
return 0
GO

SqIDataReader
SqIDataReader ExecuteReader .
, ,
Read SqIDataReader,
- .
SqIDataReader ,
bool CheckProductWithReaderC int ProductID )
{
SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=northwind");
SqlCominand cmd = new SqlCommand("CheckProductExistsWithCount", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("ProductID", ProductID };
cmd. Parameters["ProductID"]. Direction = ParameterDirection.Input;
try
(
conn.OpenO;
SqIDataReader reader = cmd.ExecuteReader(
CommandBehavior.Singleflesult );

Microsoft ADO.NET

76

reader.Read();
bool bRecordExists = reader.Getlnt32{0) > 0;
reader.Closet);
return bRecordExists;
catch
throw;
finally
conn.Close();


.
CREATE PROCEDURE CheckProductExistsWitnCount
@ProductID int
AS
SELECT COUNT(*} FROM Products
WHERE ProductID = eProductID
GO

ADO.NET
, SQL Server
.NET Data Provider, . , .
public void TransferMoney( string toAccount,
string fromAccount, decimal amount )
{
using ( SqlConnection conn = new SqlConnection(
"server=(local);Integrated Security=SSPI;database=SimpleBank" ) )
{
SqlCommand cmdCredit = new SqlCommand("Credit", conn );
cmdCredit.CommandType = CommandType.StoredProcedure;
cmdCredit.Parameters.Add( new SqlParameter("@AccountNo", toAccount) );
cmdCredit.Parameters.Add( new SqlParameter("Amount", amount ));
SqlCommand cmdDebit = new SqlCommand("Debit", conn );
cmdOebit.CommandType = CommandType.StoredProcedure;
cmdDebit.Parameters.Add{ new SqlParameter("@AccountNo", fromAccount) );
cindDebit.Parameters.Add( new SqlParameter("@Amount", amount ));
conn.0pen();
//

.NET

77

using ( SqlTransaction trans = conn.BeginTransaction() )


{
//
omdCredit. Transaction = trans;
cmdDebit. Transaction = trans;
try
{
cmdCredit . ExecuteNonQueryt ) ;
cmdDebit . ExecuteNonQueryt ) ;
// ( )
trans. CommitO;
}
catch( Exception ex )
{
//
trans. RollbackQ;
// ...
throw ex;

Transact-SQL
, Transact-SQL.
CREATE PROCEDURE MoneyTransfer

@FromAccount char(20),
taToAccount char(20),
^Amount money
AS

BEGIN TRANSACTION
-
UPDATE Accounts

SET Balance = Balance - ^Amount


WHERE AccountNurober = FromAccount
IF RowCount = 0
BEGIN
RAISERRORC 'Invalid From Account Number', 11, 1)
GOTO ABORT
END
DECLARE ^Balance money
SELECT ^Balance = Balance FROM ACCOUNTS
WHERE AccountNumber = @FromAccount
IF ^BALANCE < 0
BEGIN
RAISERRORC Insufficient funds', 11, 1)
GOTO ABORT

78

Microsoft ADO.MET

END
-
UPDATE Accounts

SET Balance = Balance + Amount


WHERE AccountNumber = @ToAccount

IF @@RowCount = 0
BEGIN

RAISERROHCInvalid To Account Number', 11, 1)


GOTO ABORT
END
COMMIT TRANSACTION
RETURN 0
ABORT:
ROLLBACK TRANSACTION
GO

BEGIN TRANSACTION, COMMIT TRANSACTION


ROLLBACK TRANSACTION.

.NET-
.NET, .
Transaction, ,
.
. Transfer RequiresNew, Debit Credit Required,
.
using System;
using System.EnterpriseServices;
[Transaction(TransactionOption.RequiresNew}]
public class Transfer : ServicedComponent
<
[AutoComplete]
public void Transfer^ string toAccount,
string fromAccount, decimal amount }
{
try
//
Debit debit = new Debit();
debit.DebitAccount( fromAccount, amount );
//

.NET

Credit credit = new CreditO;


credit. CreditAccount( toAccount, amount );
}
catch( SqlException sqlex )
{
// .
// .
throw new TransferException( "Transfer Failure", sqlex );

[Transact ion(TransactionOption. Required)]


public class Credit : ServicedComponent
{
[AutoComplete]
public void CreditAccount( string account, decimal amount )
{
SqlConnection conn = new SqlConnection(
"Serve r=( local); Integrated Security=SSPI";database="SimpleBank");
SqlComtnand cmd = new SqlCommand("Credit", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd. Parameters. Add{ new SqlParameter("@AccountNo", account) );
cmd. Parameters. Add( new SqlParameter("@Amount", amount ));
try
(
conn.0pen();
cmd . ExecuteNonQuery( ) ;
}
catch (SqlException sqlex)
{
//
throw; //
I
[ ransaction(TransactionOption. Required)]
public class Debit : ServicedComponent
{
public void DebitAccount( string account, decimal amount )
{
SqlConnectton conn = new SqlConnection(
"Server=(local); Integrated Security=SSPI"; database="SimpleBank");
SqlCommand cmd = new SqlCommandC'Debit", conn );
cmd.CommandType = CommandType.StoredProcedure;
cmd. Parameters, Add( new SqlParameter("@AccountNo", account) );
cmd,Parameters.Add( new SqlParameter("$Amount", amount ));
try
{
conn.0pen();

79

80

Microsoft ADO.NET

cmd. ExecuteNonQueryO;
catch (SqlException sqlex)
//
throw; //

, :
Bill Vaughn, Mike Pizzo, Doug Rothaus, Kevin White, Blaine Dokter, David
Schleifer, Graeme Malcolm (Content Master), Bernard Chen (Sapient), Matt
Drucker (Turner Broadcasting) Steve Kirk.
? ? ?
( ) devfdbck@microsoft.com.
.NET ? Microsoft.
http://www.microsoft.com/business/services/mtc.asp.

ADO.NET:


ADO.NET - ,
. , ,
.NET-: # Visual Basic .NET.

Microsoft .NET
,
. , Visual Basic 6.0 ,
.NET-. , ADO.NET ADO 2
ADO .
.
ADO.NET #, Visual Basic .NET .NET-co . ADO 1.x Visual Basic 6.0. ,
- Visual Basic 6.0.
.NET,
ADO.NET MSDN Magazine/ . 2002. 1 (). . .

Microsoft ADO.NET

82

.NET. , ADO.NET, -,
ASP.NET.
, , :
Web-, ,
asp:DataGrid, ;

CodeBehind-,
Web-;

,
, .

, .NET- . .NET , , . , , Visual Basic, #.


, , ,
. ,
# , Visual Basic .NET.

Web-
Web-, (UI) . WebForm.aspx
DataGrid,
ADO.NET- DataSet (. 1). DataGrid
HTML-. ( DataGrid
Cutting Edge , MSDN Magazine? 2001 .) Web DataGrid: grdSql ( SQL- ) grdProc (
).
: Web- . 1 , HTML . . .NET Framework , , .
, HTML
Web-, , UI, . ASP,
,
.

ADQ.NET:

. 1. Web- Visual Basic


a

<@ Page Language "vtr Codebehind="WebForra.aspx.vb"


a
Innerlts "HyV80ataLayer.WebForerx>
<html>

<ne:ad></head>
<body>
<span>Example of Executing a SQL Statement and Filling a Grid</span>
<asp:Data6rid
ld*"grdSql" '
njnat=" Server"
autogeneratecolumn:s="tnje"
headerstyle-backcolor="8333399"
h e ade rst yle-font~ names="tah oma"
headerstyle-fontsize="8pt"
he ade rstyle-forecolo r~"ff f f66"
itewtyl,e-baekcQlor="White"
i t emstyle- f nt -name s* " t atiorcia"
itemstyle-font-size="8pt"
alternatingitemstyle~backcolor="LightGoldenrQdYellow"
cellpadding="3"
/>
<br><br>
<span>xampla of Executing a Stored Procedure and Filling a Grid</span>
<asp:DataGrid
ld="grciPrac"
unat="Server"
autogeneratecolurons="true"
headerstyle-backcolor=s"333399"
heade rsty1e-fon t-names="t a homa"
head0rstyle-font-size="8pt"
tiea6erstyle-forecolor="ffffff66"
itemstyle-backcolo r*"White"
i t emst yle-font-names"tah oraa"
itemstyle-font-size="8pt~
alternatingiteiBstyle-backcolor="Light6oldenrodYellow"
cellpadding="3"
/>
</body>
</html>

Web- , , ( CodeBehind-). (
CodeBehind . http://msdn.microsoft.com/msdnmag/issues/
01/08/cuttmg/cutting0108.asp.) @Page CodcBe-.
hind (, 1). Web- .
@Page Inherits, , Web-.

Ctf-
Visual Basic . , Language #, Visual Basic. CodeBehind WebForm.aspx.cs, a Inherits My SDataLayer. WebForm. ,
.
. 2.
Imports
Imports
Imports
Imports

Web- a Visuaf Basic


System
System. Data
System. Wet. 01
System. Web. UI.WebGontrols

Public Class WebForm


Inherits System. Web. UI. Page
'//

'//- DataGrid , SQL-


Protected grdSql As DataGrid
'//- DataQrid ,
Protected grdProc As DataGrid

'ft
' / / ____ __ __ __.,

Public WebForntO
Private Sub Page_Load(8yVal sender As System. Object,
ByVal e As System. EventArgs) Handles MyBase.Load
' ,
Dim oDs As DataSet = Nothing
Difli oSql As SqIService = Nothing
. Dim sSql As String = ""
Dim sProcName As String = ""
V/- SqIService
oSql = New MyVBDataLayer. SqlService("localhost", "northwind1
"sa", "")
'//- SQL-
sSql * "SELECT CategorylD, CategoryName, Description F80H "
"Categories ORDER 8Y CategoryName"
'//- SQL- SQLService
'// DataSet

. . .

&DO.NET:

. 2. Web- Visual Basic ()


oDs ~ QSql.Run5ql{sSql, "Category")
'//- DataGrid DataSet
{jrdSql.DataSoorce = New DataVlew(oBs.Tables("Category")>
grdSql.DataBiRdO
'//- DataSet
oDs = Nothing
*,//-
sProcName = "SalesByCategory"
eSqlrAddParaffleterC"CategoryName",ssenumSqlDataTypes.
ssSOT_String, 15, "Produce")
QE^l.AddParameter("QrdYear",sseruitfiSqlDataTyp&s. _
ssSDT_Strifi&, 4, "1998")
'//- SQLService
V/ OataSet
oDs * oSql.RunProc<sProcName, "Sales")
'//- DataGrid OataSet
grdProc.DataSouree = Mew DataView{oDs,TabIes("Sales"))
grdProc.DataBindO
'If- DataSet
oDs = Nothing
'//- SQIService
oSql = Mottling
End Sub

End Class

Web-
Visual Basic WebForm.aspx System.Data Imports
(. 2).
DataSet Data View DataSet , a DataView DataSet
DataGrid,
WebForm System.Web.UI.Page. .
DataGrid , -

86

Microsoft ADO.NET

UI, .
DataGrid . Protected, , . WebForm, , .
CodeBehind, Page_Load (. 2). DataSet
(result set), . ,
My Base. Load. , Page_Load
Load .
(MyVBDataLayer.Sq]Service) oSQL. SqlService,
,
, .
SqlClient.Connection, SqlService.
SQL- RunSql,
SQL- DataSet, oDs. DataSource DataGrid (grdSql) Data View ( Category DataSet).
DataGrid, , DataBind. DataGrid WebForm.aspx.
() . , ,
.
SqlClient, . ,
, SQL-
, . ,
SqlService.
System.Data: DataSet Data View, , SqlClient.
: XML (DataGrid).
System.Data CodeBehind,

ADO.NET:

DataGrid SQL-,
.
Add Parameter (. 2). ,
, AddParameter.
, SqlService.
RunProc, DataSet.
#.
using. . WebForm. # ,
(. 3).
. 3.

Web- #

//
using System;
using System. Data;
using System. Web. Ul;
using System . Web. UI . WebContt ol&;
namespace MyCSDataLayer
i /____ _____ _
// ; WebForm.aSpx.C3
// ; Lancelot Web Solutions, LLC
// : 07/04/2001
/ / ______________ _ ____
// : ASP.NET-
// WebForts.aspx. DataGrid
// MyCSDataLayer.
// DataGrld ,
// SQL-. - ,
// .
//_..-.-._.
______
public class WebForm : System. Web. UI. Page
/_......____ ____ _-

//__._-. _____ ____

//
.. . .

Microsoft ADO.NET

. 3. Web-d>opMw;a #
/{
_
//- DataGrld SQL-
protected DataSrid grdSql;
//- DataGrid
protected DataGrid grdProc;
it

//_________
//
//_

___-..-.___

protected WebFoneO
i

Page,Init += new System.EventHandler(Paffe_lnit);

//
//__...., _______ ..
private void Page_Load(object sender, System, EventArgs e)
II DataSet ,
// DataGrid'
SqlService oSql = null; // SqlService
string sSql = "";
// SQL- PataSet
string sProcName - ""; // DataSet
DataSet oDs = null;

//- SqlService
oSql = new SqlService<"localhost", "northwinct", "sa", "");
//- SQL-
sSql = "SELECT CategorylD, CategoryName, Description "
sSql += " FROM Categories ORDER BY CategoryName";
//- SQL- SQLService
// DataSet
oDs = oSql.8unSql(sSql, "Category"};
//- DataGrid DataSet
grdSql.DataSource * new SataView(oOs.Tables["Category"]};
grdSql.DataBindC);
//- DataSet
oDs=null;
//-
sProcName = "SalesByCategory";
oSql.AddParaiieter<"@CategoryNaffle",
. . .

ADO.NET:

. 3- Web- # ()
MyCSOataUyer.ssenumSqlDataTypes.ssSDT.String, 15, /'Produce");
oSql.AddPara[neter("@QrdYear",
MyGSDataLayer.ssenumSqlDataTypes.ssSDT_String, 4, "1998");
//- SQLService
// DataSet
oDs * QSql.flunProe(sProcNaffle, "Sales");
//- OataGrid DataSet
grdProc.DataSouree = new DataView(oDs.Tables["Sales"});
grdProc.DataBindO:
//- DataSet
oDs=nyll;
//- SQiServlce
oSql=null;

, : , null ( Nothing)

(. 3). , #
, Visual
Basic.

SqIService
SqIService ,
, .
:
Imports
Imports
Imports
Imports
Imports

System
System.Data
System.Data.SqlClient
System.Data.SqlTypes
System.Collections

, (
CodeBehind). ,
AddParameter. ADO.NET-
SqlDataTypes.

90

Microsoft ADO.NET

Public Enum ssenumSqLDataTypes


ssSDT_Bit
ssSDT_DateTime
ssSDT_Decimal
ssSDT_Integer
ssSDT_Honey
ssSDT_String
End Enum

SqlService (. 4).
, .
ArrayList , AddParameter
.
,
SqlService. , / .
. 4.

SqlService

Public Class SqlService


//_

_-_____ _.__ _

'//
'//
Private m_sUsername As String * " '//
Private m_sP3Ssword As String //
Private ra_sServer As String = ""
'// SQL Server
Private ift_sDatabase As String = "" '//
Private m^sConnectionStfing As String - "" "//
'//-
Private ffl_oParmList As ArrayList ~ New ArrayListO

SqlService . ,
. . SqlService
, . : ,
, () (. 5).
SqlService . ,

.

ADO.NET:

91

. 5. SqIService
"U ( )
'// ;

7/

Sub NewO
End Sub

'// ( - )
'// ;

7/

Sub Hew(ByV8l sConnectionString As String)


ffl_sCoRnectionString - sConneetionString
nd Sub

V/ ( - )
V/ ;
'//

Sub New(8yVal aServer As String, ByVal sOatabase AS Stritvg, _


ByVal sysername As String, _
ByVal sPassword As String)
Server = sServer
Database = sDatabase
Userrame = sttsemaee
Password * sPassword
End Sub

RunSql (. 6) , SQL- ( DataTable), DataSet.


RunSql SQL-
(. 7). SQL-, , , . RunSql
,
. , SQL-,
RunSql.
, DataSet (. 6),
ADO.NET-. SqlConnection Connect. (SqlConnection ADODB.Connection ADO 2.x.) SqlConnection ,
, SqlComniand.
( ADODB.Command ADO

Microsoft ADO.NET

92

2.x.) SqlCommand, SQL-, SelectCommand SqlDataAdapter. SqlDataAdapcer SqlCommand


. (InsertCommand, UpdateCominand DeleteComniand), .
Fill SqlDataAdapter, DataSet , .
. 6.

RunSql, Dataset

V/
V/ :
'// : DataSet
'// : SQL-
Public Overloads Function RunSqKByVal sSql As String, _.
ByVal sTableName As String) As DataSet
Dim oCrad As SqlCommand = New SqlCoismandO
Dim oCn As SqlConnection = Nothing '// SqlCormection
Dim oOa As SqlDataAdapter = New SqlDataAdapterO
Dim oOs As DataSet = New DataSetO
'//-
oCn = ConnectO
With oCffid
'//- CommamjText, Connection
'//- SqlCommand
.Connection - oCn
. ConiBiandText = sSql
.ComrnandType = CommandType.Text
End With
With oDa

'//- SqJGomruand SqlDataAdapter


.SeleotCommand = oCmd
'//- SQL- DataSet
.Fill(oDs, sTableName)
End With
*//-
Disconnect(oCn) .
'//- DataSet
Return oDs
End Function

ADO,NET:

. 7, RunSql ,
V/
"// :

'// :
V/ : SQL-
Public Overloads Sub RunSqKByVal sSql As String)
Dim oCind As SqlCoMand = New SqlCommandO
Dim oCn As SqlCorvnection = Nothing '// SqlConnection
'//-
oCn * Connect{)
With oGuid
'//- SOt-one
,CommandText = sSql
.Connection = oCn
.CommandType = ComrnandType.Text
. ExecuteNonQue ry()
End With
'//-
Disconnect(oCn)
End Sub
SqlDataAdapter ( ADO.NET Beta 1 SqlDataCommand) ADO 1.x. On
(SELECT, INSERT, UPDATE
DELETE), DataSet. SqlDataAdapter (SqlCommand
SqlConnection) (DataSet).
DataSet Recordset ADO 2.x, , .
DataSet
DataTable. , DataSet DataTable ( , ). , DataSet , , Recordset ADO 2.x. ,
DataSet Recordset , . DataSet Extended-, ; DataRelation
DataTable; XML DataSet XML.

94

Microsoft ADO.NET

DataSet , RunSql, . 7. SQL- SqlConnection,


SqlCommand IT ExecuteNonQuery. SQL-, ADO.NET,
. (
Connection.Execute ADO 2.x adExecuteNoRecords.)
,
ExecuteNon Query.
RunProc.
DataSet (. 8), (. 9). RunProc , RunSql
, Array List- m_oParmList. , oEnumerator lEnumerator. , Sql Parameters.
. 3. RunProc, Dataset

'//
V/ :
V/ : DataSet
V/ :
Public Overloads Function RunProc(ByVal sProcName As String,
ByVal sTableName As String) As DataSet
Din oCrad As SqlCoiBiand = New SqlCommandO
Dim oCn As SqlGonnectiorj = Nothing
Dim oOA As SqlDataAdapter = New SqlDataAdapter()
Dim oDs As DataSet = New DataSetO
: Dim oSqlParameter As SqlParaiaeter = Nothing
Dim oP As Parameter = Nothing
'//-
Dim oEnumerator As lEnumerator = m_oPamList.i3etEnuieeratorC)
'//-
oCn = ConnectO
With oCmd
'//- CommandText, ActiveConneetlon CommandType
'//- SqlConmtand
.Connection = oCn
.CommandText = sProeName
.CommandType = GommandType.StoredProcedure
End With

. . .

ADO.NET:

. 8. RunProc, Dataset

'//~ Parameters ArrayLtst


Do While (oEnumeratQr.MoveNextO)
oP = Hotting
"//- Parameter
oP = Q&Himerator. Current
*//- SqlPa remoter
oSqlParameter = ConvertPararaeterToSqlParametef(oP)^
'//- SqlParameter SqlConmiano;
oCmd. Parameters. Add(oSqlParaieter)
Loop
With OOA
'//- SqlCoirmiand ^IDataAdapter
.SelectCoflimand = oCmti
'//- ! BataSet
,Fiil(oDs,
nd

'//-
DiscoMect{oCR>
V/- DataSet
Return oDs
'End fraction

. 9. RunProc ,
V/
V/ :
V/ :
'// ;
Public Overloads Sub RunProc(ByVal sProcMame As String)
Dim
Dim
Din
Diffl

oCmti As SqlCommand = New SqlCommand()


As SqlCoimeetion = Nothing
oSqlParameter As SqlParameter = Nothing
oP As Paraneter = Nothing

'//-

Di* Enumerator As leniwierator <= Bi_oPariel.ist.eetEnuBerator{)

// -
oCn = Connect
With
'//- CoaniandText, ActiveCotinection : CommandType
. . .

Microsoft ADO.NET

. 9. RunProc ^ ()
'//- 1 SqlGommand
,Connection = oCn
.CommandText = sProcName
. ConwandType = ComBiandType.StoredPrQcedure
. End ltttii
'//- Parameters a ArrayLlst
Do While (oEnumerator.MoveNextO)
oP = Nothing '//- Parameter
of = oEnumerator.Current
V/- SqlParameter
oSqlParameter ~ ConvertParameterToSqlPafameter(oP)
'//- SqlParameter SqlCoramand
oCffld.Parameters.Add(oSqlParameter)
Loop
'//-
oCmd.ExecuteNonQueryQ
'//-
Disconnect(oCn)
End Sub

, MoveNext lEnumerator
false, . . ArrayList .
.
, ADO.NET, . .
SqlParameter. SqlParameter
SqlParameters SqlCommand .
, SQL- DataSet
, Select Command Fill SqlDataAdapter
, RimSql.
RunProc (. 9) , DataSet. Overloads,
Visual Basic, .
RunProc (. 8).
AddParameter (. 10) , SqlService . , , .
Parameter, Array-

ADO.NETt

97

List , RunProc,
: ( ssenuinSqlDataTypes)
SqlDBType.
. 10. AddParameter

V/
V/ .:
'// :
V/ :
Public Sub AddParameterCByVal sParameterNante As String,
, ByVal ISqlType As ssemiBiSqlDataTypes _
ByVal iSize As Integer, ByVal sValue As String)
OiiB eQatalype As SqlDbType
Dim As Parameter = Nothing
Select Case ISqlType
Case ssenuffl$qlDataTypes.ssSDT_String
eDataType = SqlQbType.VarChar
Case ssenuSqlOataTypes,ssSOT__Integer
eDataType = SqlDDType.Int
Case ssenumSqlDataTypes.ssSDT_OateTime
eDataType = SqlDbType.BateTine
Case ssenwiSqlDataTypes.ssSDTjJit
eOataType = SqlDbType.Bit
Case ssenuinSqlBataTypes. ssSDT_Decifial
eDataType = SqlDbType.Decimal
ssenuraSqlOataTypes.ssSDT_Honey
eDataType = SqlDbType.Money
ind Select
~ New Parameter(sParameterNaffls, eDataType, iSize, sValue)
_ rmUst. Add< oFa ram)

End Sub

SqIService #
SqIService #
. ( Visual Basic #) MSDN Magazine (http://msdn.microsoft.com/msdnmag/
issues/01/ll/code/DataOlll.exe). RunSql, #,
SQL- DataSet (. 11). :

4-5947

Microsoft ADO.NET

. , ( RunSql), ( Visual Basic Overloads) . # .


. 11. RunSqJ #, Dataset
//-
//- :
//- : DataSet
//- : SQL-
public DataSet RunSql(string sSql, string sTableName)
SqlCommand oCmd = new SqlCommandO;
SqlConnection oCn = null;
SqlDataAdapter oda = new SqlDataAdapterO;
DataSet oDs = new DataSetf);
//-
oCn = CorvnectO;
//- CommandText, Connection CommandType
//- SqlComnand
.Connection = oCn;
oCiBd.CofflinandText ~ sSql;
I.CoifflBandType = CommandType.Text;

//- SqlCommand SqlDataAdapter


oDa.SelectConimand = oCmd;
//- SQL- DataSet
oDa.FilKoDs, sTableName};
'//-
DiscorineGt(oCn);
//- OataSet
return oDs;

RunSql, DataSet, , . void:


public void RunSql(string sSql)

ADO.NET:

RunProc #
DataSet (. 12). Visual Basic .
. 12.

RunProc #, Dataset

//-
//- :
//- : DataSet
//- :
public DataSet RunProc{string sProcName, string )
{
:
SqlCommand oCmd = new SqlCoramandO i
SqlConnection oCn = null;
SqlPararoeter oSqlParameter = null;
SqlDataAdapter oDa - new SqlDataAdapter ;
DataSet oDs - new DataSetO;
Parameter oP = null;
//-
lEnumerator oEnutnerator * m_oPariBList.uetEnuroerator();
//-
= Connect();
//- CofftmandText, ActiveGonnectlon CommandType
//- Sql Command
oCnd.CoinmandText = sProcName;
. Connection = oCn;
, CommandType = CommandType. StoredProcedure;.
//- Parameters a ArrayList
while ( oEnuraerator.MoveNextO )
{
oP = null;
//- Paraaeter
oP = (ParaiReter)oEmjmeratQr. Current;
//- SqlParameter
oSqlParanteter = ConvertParameterToSqlParameter(oP);
//- SqlParaieeter SqlCommand
oCmd,Parameters.Add(oSqlParaaeter};

//- SqlCoiranarnJ SqlBataAdapter


oDa.SelectComfliand - oCid;
'//- DataSet
oDa.Fill(oOs, sTableName);
. . .

100

Microsoft ADO.NET

. 12. RunProc C$, Dataset (}


//-
DlsconnGct(oCn);
//- DataSet
retarn oDs;

RunProc, DataSet, , , ,
void:
public void RunProc(string sProcName)


, WebForm.aspx
(. 13). ( Visual Basic
#.) DataGrid,
HTML.

F-gyortes

Vcots

He p

3, ccTFeeSj tea;, bea =, aid aies


3
4

Cnndirfienrs

'Sweet and s^v-jry , r*iESt;fs, swssttr, srii se^scnings

Confections

Desserts, candies, and wet b'eads

Dairy Products Cheeses

Grehs^Cereals Breads, crackers, posts, snd cc'tal

MeaLJPuJtri/

;S

Seafood

Prepared riieuU
Dried fruit and bean (urd
'' and Hih

Exanple of fisecutmg a Stored Procedure and Pi]Jing a Grid


Longlf* Tofu
Dried uppies

-lie
1J090

Sob's Organic Dried s; 12336

. 13. WebForm.aspx

ADO.NET;

3.01

, , , ADO.NET, . ADO.NET- -,
ADO.NET.
, ,
System.Data.OleDb. SqIClient. SQL Server
OleDb.
, SQL Server,
SqlService, System.Data.OleDb (, SqIClient). , SqIClient, SQL Server.

ADO.NET, SqlDataAdpater, DataSet
(presentation layer) -
(business layer), (relations) , DataSet DataTable.
(Johnny Papa) - MJM Investigations
(, ),
ADO, XML SQL Server. , VSLive.
datapoints@lancelotweb.com.



.NET Data Access
Framework*

.NET Framework System.Data.dll ,


,
(custom data providers). ,
, , .
ADO.NET- Connection, Command, DataReader DataAdapter
ADO.NET , OLE DB. , ,
.

Windows- API , - (providerconsumer). ODBC (Open Database Connectivity) API,


. ODBC SQL CLI (Call-Level Interface), ANSI SQL. ODBC-
, ,
TDS (tabular data stream), SQL Server, , API, *

MSDN Magazine. 2001. 12 (). . .

.NET Data Access Framework

, OCI (Oracle Call Interface).


OLE DB - , ODBC .
OLE DB
, (flat)

OLE DB.
Microsoft .NET System.Data.d 11, , OLE DB ODBC.
Systeni.Data ,
System.Data.Common
, , .
, System.Data.dll (System.Data.OleDb System.Data.SqlClient),
, .
API- . , , ( ) .
,
, , . , System.Data (disconnected object
model), DataSet,
ODBC Recordset (OLE DB).
.NET SDK Beta 2 , , , .
. , , , , , System.Data,
System.Data.Common.
.NET, .
, , . ,
, -

104

Microsoft ADO.NET

. , .NET Beta 2.

?
OLE DB ODBC
. , GUI-.
,
API. -
ADO Recordset RDS (Remote Data Services), , ADO- Recordset.
, ,
. , . , ODBC-
SQL OLE DB Simple Provider.
Windows, Visual
Basic, , (data-bound controls).
,

, OLE DB , , ActiveX Control Writer's Specification for OLE DB.
ODBC OLE DB , Microsoft . ,
Microsoft Access ODBC-
Access- ,
Access. SQL Server DB/2 ( Windows NT)
OLE DB . , SQL Server 7.0, OLE DB
, DTS (Data Transformation Services). Crystal Reports ODBC- ADO- Recordset ,
. ADO
ODBC OLAP- XML-.
, OLE DB ODBC .

.NET Data Access Framework

105


Visual C++ 6.0 Microsoft ATL (ActiveX
Template Library), OLE DB.
ATL- OLE DB (wizard), ATL ,
WIN32_FIND_DATA ( ) (cotypes) OLE
DB. , : DirProv OLE
DB . .NET ,
dirprov (managed dirprov).
ADO.NET , OLE
DB. ADO.NET ; ,
. : Connection, Command, DataReader DataAdapter.
.
Connection ,
. ,
. DataAdapter, ,
Open Close Connection DataTable, DataSet.
Command Command . , , . , SQL INSERT, UPDATE DELETE. , , . SQL SELECT.
DataReader DataReader ,
Command.
(forward-only). , .NET-.
DataAdapter DataAdapter DataSet , Command, , .
. 1;
. , , Com-

106

Microsoft ADO.NET

mand Connection. Create Command,


Connection Command. , ,
. ,
. (. 1),
.
.
IDbConneclion

CHH
Connection

IDbCommand

Created mm and
ctor(Command)

IDbDalaAdapter

ExecuteReader

IDbOataReader
IDbDataRecord

. 1.

Connection
Connection IDbConnection. IDbConnection (. 2) ,
Open Close. .NET
(deterministic
destruction), Close, , OLE
DB. ChangeDatabase , .
BeginTransaction . BeginTransaction IDbTransaction,
Commit Rollback. BeginTransaction,
(transaction isolation level).
, BeginTransaction .
, IDbCreateCommand Command IDbCommand,
IDbConnection. . ConnectionString, ConnectionTimeout Database , . , State,
. ConnectionState (. 1). Open Closed -

.NET Data Access Framework 107

. , , a Fetching ,
. Broken ,
, , , .
. 2. iDbConnectipn
public interface IDbConnection
{
IQbTransaction BeginTrartsaction(IsolationLevel iso)
IDbTransaction 8egin.Transaetion()
bool ChaflgeDatabase(striRg newdb)
; void CloseO
IPbCoiamand CreateComroandO
void Qpert()
//
string ConnectionString
int ConnectlonTimeout
string Database
Connect!onState State

//
//
//
//

get, set
get, set
get, set
set

. 1. ConnectionState

Broken

. . ,
, .

Closed

Connecting

Executing

Fetching

Open

Connection
IDbConnection, , .
,
. , .
Open Close (

108

Microsoft ADO.NET

ConnectionState), , , , .
Connection
. :
String ( ).
, . Connection ConnectionState.Closed;
_ConnectionState .
. , , . (NotSupported)
(Notlmplernented), . MDirConnection
, MSDN Magazine
http://msdn.microsoft.com/msdnmag/code01.asp .

Connection
OLE DB , . .NET- .
, ( ), . OLE DB,
, , .
/. - (marker interfaces).
, (reflection), , .
, , .
Connection
, SqlClient.
Data Source, User ID Password (-

.NET Data Access Framework

109

OLE DB), SqlClient , SQL Server (, Network Library


TDS).

, , Web-.
OleDb, SqlClient , .

Command
Command IDbCommand (. 3),
IDbCommand
. , ,
, IDbCommand.ExecuteNonQuery,
, .
- DataReader.
IDbCommand.ExecuteReader IDataReader
DataReader. ExecuteScalar ,
, . ,
.
IDbCommand.ExecuteReader , CommandBehavior. , . CommandBehavior . 2.
. 2.

CommandBehavior

CloseConnection


Connection ,
DataReader

Keylnfo

SchernaOnly

SequentialAccess

SingleResult

SinglcRow

, ;

110

Microsoft ADO.NET

. 3. IDbCommand
public interface IDbCommand
public
public
public
public
public
public

void CancelO
I&ataParameter CreatePararaeterO
int ExeeuteNonQueryO
IDataReader ExecuteReaeferQ
IDataReader ExecutefieaderfCommandBehavior b)
object ExecuteScalar()

public string CoairoandText


public int CofflfflandTimeotit
public ComaancfType CoioiandType
public XDbCdnnection Connection
public IDataParameterColleetion Parameters
public IDbTransaction Transaction
public UpdateftowSource UpdatedRowSouree

//
//
//
//
//
//
//

get,
get,
get,
get,
get
get,
get,

set
set
set
set
set
set

CommandText ( )
CommandType. . , , CommandText Connection . CommandType, ,
CommandType.CommandText. (
OLE DB). ( Cancel)
( CommandTimeout).
. Command Connection ( IDbConnection), .
Transaction ( IDbTransaction). Transaction Connection.
. .NET-, (collection). Parameters
Command, Create Parameter. , UpdatedRowSouree , DataRow , DataAdapter.

,NET Data Access Framework

Command
. CommandText.
, , . ExecuteNonQuery ExecuteReader DataReader, GetDirectory (
), DataReader, .
. 4. ExecuteReader
public IDataReader ExecuteReader(CominandBehaviQr t>)
{
Debug.WriteLine("MBirCoimancl.ExecuteReader(b)", "MdirCommand"};
//
if ^Connection == sull II .Connection.State !=
ConnectionState.Open)
throw new InvalidOperationExceptionC"
Connection must be valid and open"};
if ((b & CoKiBand8etiavior.KeyInfo) > 0)
Debug.WriteLine("Behavior includes Keylnfo"};
if ((b & CoieiandieftavlQr.SchemaQnly) > 0}
Debug.WriteLinet"Behavior in-cludes Schema&nly");
// CloseConrtection " "
if <( & CoiemaniiBehavior.CloseConnection) > 0)
{
De&ug.WriteUneC'Behavior Inelttctes CloseCotiRection");
HDirDataReader reader = new HDirDataReader(_CominandText,
Connection);
reade r. GetOi recto ry (CoiwnandText);
return reader;
I

else
{

HDirCataReader reader = new MDirDataReader(_ComfflandText);


, reade r. Get Di recto ry(_ConnnandText);
return reader;

ExecuteReader, Command Behavior. -

j.12

Microsoft ADO.NET

CommandBehavior ,
. Keylnfo SchemaOnly, (
GetSchemaTable DataReader). CloseConnection.
DataReader, Connection, . Close DataReader,
Connection. ExecuteReader . 4.

Command
SqlCIient OleDb IDbCommand.
, , CommandBehavior SingleRow. Prepare,
.
, SqlCIient Command. SQL Server 2000
XML-, SqlCIient ExecuteXmlReader, XmlReader IDataReader.

DataReader
DataReader . IDataReader IDataRecord. DataReader
.
IDataReader IDataRecord . 5.
IDataReader
Read, false, .
.
NextResult.
,
, . GetSchemaTable IDataReader DataTable . , GetSchemaTable, , ,

.NET Data Access Framework

. 5. IDataReader IDataRecord

public interface tuataReader


\
IDataReader
public BataTable GetScheiftaTable< }
public void Close()

public bool Nextflesult(>

public bool ReadO


// IDatafieader
public int Depth
public bool IsGlosed
public int Records Affected
public interface IDataRecord
{
// IDataRecord
public bool Set&Qoleafl{iRt i)
public byte QetSyteCint i)
public int Get8ytes(int i, int fieldoffset, byteH buffer,
int length, int bufferoffset)
putilic char SetChar(int i)
public int GetCharsfirvt i, int fielaoffset, chart] buffer,
Int length, int bufferoffset)
public IDataReader GetCata(int i)
public string 6etOataTypeNarne(int i)
public DateTime 6etDateTiroe(int i)
public decimal QetDecimaKint i)
public double QetDauble(int i)
public Type GetFleldType(int i)
public float SetFloatCint i)
public Quid 6etGuid(int i)
public short Setlntl6(int i)
public int Getlnt32(int i)
public long 6etlnte4{int i)
public string 6etNafne(int i)
public int GetOrdinal(string name)
public string QetString(int i)
public object GetValue(int i)
public int GetValuesCobjectC] values)

public bool IsDBHulldnt i)

// IDataRecord
public int FleldCount
public object this[string nafae];
public object this[int 1]

113

12,4

Microsoft ADO.NET

IDataRecord , . - (getters), , GetValue GetValues, object.


IDataRecord .NET-; ,
.NET-. , IDataRecord (iterators) ,
Item.
.

DataReader
DataReader GetDirectory, System.IO.DirectoryInfo. GetFileSysternlnfos. ,
Name, Size, Type ( ) CreationDate. Name
String, Size Int64, a CreateDate DateTime. , : ( ),
( ), ( ) (
object). ,
, . . ADO
Variant.
, GetSchemaTable. DataReader Read . 6.
- . (, Getlnt32 String)
InvalidCastException, SqlClient OleDb. , .
Item (indexers) #.
.
, , DataReader, lEnumerable. lEnumerable DbEnumerator System.Data.Common. SqlClient OleDb .
Get Enumerator lEnumerable, DbEnu-

.NET Data Access Framework

merator, ,
DataReader:
lEnumerator System.Collections.Innumerable.GetEnumerator()

{
return ((lEnumerator) new DbEnumerator(this));

. 6. MDirDataReader
// IDataReader.ReadC)
public bool ReadO

i
Debug. WrlteLinerK&lrDataReader. Read", "HdirBataReader");
if (_le i null)

{
bool notEQF = ie.MoveNextO;

if (notEOF == true)
{

CurrentRow++;
if (_fsi[_CurrentRo] is Filelnfo)
{
FUelnfo f = (Filelnfo)_fsiE_GurrentRow3;
_cols[Q] a f.Narae;

_cols[l] f.tangttv.ToStringC); ; - - . -
_cols[2] * "File";
13] = f.CreatiDnTiffle.ToStrlngO;
else
Oireetoryinfo d * (DirectoryInfo)_fsit_GurrentBow];
_cols[0] * d.Hame;
_cols{1] = "0";
_cols[23 * "Directory";
_eols[3] * d. Great ionTiae.ToStringO;

return notEOF;

}
, return false;
}
// MOir DataReader
// HDirCoronand, Execute HOirCoiffiand.ExecuteReader

/*
,
* CoBinandfleliavior.GloseConnection. Null
* ( ),
*/

. . .

116

Microsoft AD0.NET

, 6. MDirDataReader ()
private
internal

IDbConnectiOR Connection = null;


Directorylnfo _dir;

internal meSystemlnfop _fsi;


internal int _GurrentRow;
internal lEnumerator _ie;
internal StringCJ names * {"Name", "Size", "Type", "CreationDate" };
internal Type[] types = (typeofCString), typeof(long),
typeof(St ring}, typeof(Dateline)I;
internal object[] _cols = new object[43;
//
internal Int32{] sizes { 1024, 8, 9, 8 >;
internal void GetDirectory(String command)
_dir = new Plrectorylnfo(coffimand);
_fsi = _dir.GetFileSystemInfos();
flecordsAffected = fsi.Length;
_GurrentRow = -t;
_ie = _fsi.GetEnumerator();
isClosed = false;

DataReader
OleDb SqlClient no- . SqlClient SqlTypes, System. Data.SqlTypes , SQL Server.
- (, Getlnt32), SQL Server .NET-, SqlClient
- (, GetSqlInt32),
SQL Server System.Data.SqlTypes . .NET SDK ,
, .
OleDb OLE DB DBTYPE
, , ,
DBTYPE- OLE DB.
IDataReader, IDataRecord.GetData. OLE DB (chapter concept),
chapter, (rowsets). IDataRecord.Get Data DataReader, , .
MDirProv ,

.NET Data Access Framework

DataAdapter
DataAdapter ,
. DataAdapter,
, DbDataAdapter,
DataAdapter. IDataAdapter ( Fill
Update, DataSet) IDbDataAdapter.
Command (SelectCommand, UpdateCommand, InsertCommand DeleteCommand), DataSet. ,
DataAdapter ,
( Insert, Delete
Update, ).
. 7.
IDbDataAdapter

IDbDataAdapter

IDataAdapter

. 7.


I
DataAdapter

DataAdapter
DataAdapter DirProv , .
SelectCommand,
, (
).
, DbDataAdapter,
MDirDataAdapter (Fill, FillSchema .). MDirDataAdapter
, ,
DataSet Fill SelectCommand. -

Microsoft ADO.NET

, , Fill DbDataAdapter
Command.ExecuteReader(commandBehavior),
SequentialAccess, FillSchema
Keylnfo SchemaOnly.

DataAdapter
SqlClient OleDb Updating/UpdatedEventArgs . OleDb
Fill, DataSet DataTable ADO- Recordset.


,
. , DirProv

, , ADO.NET. MSDN
Magazine.
, , OLE DB,
. ,
: , , , CommandBuilder, ,
, . , SqlClient OleDb
.
,
. OleDb, SqlClient
Transaction, IDbTransaction.
(collections) , . .NET-
, IDataReader. SqlParameter OleDb Parameter IDataParameter, IDataParameterColIection,
(lEnumerable, ICollection IList).
CommandBuilder ,
InsertCommand, UpdateCommand DeleteCommand DataAdapter -

.NET Data Access Framework

, . SqlClient, OleDb Command Builder,


.
, API
( ).
SqlClient, OleDb Errors,
, . . .
, ,
GleDbException/SqlException. , / Sql/OleDblnfoMessageEventArgs/Delegate. .
.NET,
, API. Permissions PermissionsAttribute. DBDataPermission DBDataPermissionAtribute, , , System.Data.Common.


MdirProv, .NET.
. ?
? ,
, ,
GUI- Crystal Reports.
, .NET.
.NET- ,
( - ) , . . SqlClient, TDS (TDS parser), OleDb,
API, . , , , -

20

Microsoft ADO,NET

.

(multiple rectangular resultsets). , . , ( )
.
XmlReader XPathNavigator

, (, ) (),
. , (subsetting), . . ,
XPathNavigator. , XPath- XSLT-, . (Aaron Skonnard)
XPathNavigator ( , .NET- .), . http://staff.develop.com/
aarons.
(legacy) OLE DB ODBC- ,
- ,
SQL Server, SQL Server DTS,
MSDTC- . . API
.
OLE DB,
.NET OleDb.
DataSet XmlDocument
API, .
, API .
, ,
, .
.NET- DataSet , , , ADO-
Recordset. DataSet Web-,
. DataSet . ADO-
Recordset, (advanced data
tablegram, ADTG), DataSet XML,
.NET Framework. XML
.NET. , DataSet.

.NET Data Access Framework

121


XmlReader XPathNavigator, XML infoset,
DataSet. XML infoset (opaque)
XML- . infoset XML-, XML
,
XML infoset. , XML infoset , ( ).
,
XML, DataSet. ADO Recordset, ConnectionCommand- DataReader.
Visual Studio
, . .NET- , ,
, lEnumerable ICollection. Visual
Studio .
.
.NET. , Crystal Reports .NET,
Visual Studio .NET, DataSet ODBC- ADO- Recordset.


Connection, Transaction Parameters , DataSet.
-,
, .
{Bob Beauchemin) DevelopMentor,
20 .
DevelopMentor .NET. Essential ADO.NET AddisonWestey/DevelopMentor. bobb@develop.com.

ADO.NET

ADO.NET
Compute, . DataColumn,
, DataSet
DataColumn, DataTable.
, .

ADO.NET . ,
DataSet. ADO.NET- DataTable
, , , .
ADO.NET
(column-based expressions) Compute,
.
DataColumn, (totals),
DataSet
DataColumn, DataTable. ,
.
SQL-, , ,
, SUM AVG, ANSI

MSDN Magazine/ . 2003. 1 (). . .

ADO.NET

123

SQL. SQL ,
.
ADO.NET ,
- .
, ,
DataSet ,
DataRelation
DataTable.
ADO.NET Compute
.
, , Compute
ADO.NET . ,
, DataTable,
DataTable DataSet,
DataRelation. ,
ADO.NET SQL . , DataRelation. ( DataRelation . 2002 . http://rasdn.microsoft.com/
msdnmag/issues/02/ll/datapoints/default.aspx.) ,
DataColumn, , DataSet SQL. , , DataTable DataTable,
DataSet Compute.

SQL-
SQL- , ,
. SQL- , SQL Server 2000, , ,
.
, , . - , .
.
, , , ,
10, $7.00, - $100.00. ,

124

Microsoft ADO,NET

. , , , ( ).
SQL-. , SQL- , (. 1). ,
.
. 1. SQL
USE rjorthwind
GO
SEUCI QrderlO,
:
ProductID,
UnitPrice,
Quantity,
(UnitPrice * Quantity) AS ExtendedPrice,
Discount,
((UnitPrioe * Quantity) * (1 - Discount)) AS
Extended?riceWithDiscauflt
0
[Order Details]
QROER BY
OrderlD,
Product!

SQL- SQL-. ,
( ), :
USE pubs
GO
SELECT au_fname AS FirstName,

au_lname AS LastName,
au_lname + ', ' + au_fname AS FullNamel,
(UPPER(au_fnanie) + ' ' + UPPER(au_lname)) AS FullName2
FROM
authors
ORDER BY
au^lname,
au_fname
SQL- , . ,
, . DataSet SQL- . 1 , , -

125

ADD,NET

, . , 10, $7.00 5,
ExtendedPrice $70.00 (10
* $7.00), . . . ,
, SQL-
ADO.NET- DataSet.

DataColumn
ADO.NET- DataColumn, . SQL-
DataColumn, . SQL- DataColumn ,
, , , DataColumn ,
DataColumn SQL- (, . 1) .
. 2 , DataTable DataSet SQL-,
DataColumn, ,
DataTable DataSet.
(default view) DataTable DataGrid grdOrderDetail.
. 2.

DataSet

private void LoadGrderDetailDataQ


//-

ifSqlConnection oCn * new SqlConnection("Data.. Souree=papa;


'-" . " +
"Initial Catalog=rn3rthwind;User ID=sa;" +
: "Password-secretpassword; ");
//- *! SELECT
string sSQL * "SELECT od.OrderlD, od.ProductIO, p.ProductName,
od.UnitPrioe, od.Quantity, od.Discount " +
" FROM [order details] od JOIN Products p ON " +
"od.ProductlO = p.ProductID " + " ORDEfi BY od.Orderlo, " +
"p.ProductNaae ";
SqlCommand oSelCrud = new SqlGoraBand<sSQL,
.oSelCmd-GominartdTvpe = ComniandType.Text;

. . .

Microsoft ADG.NET

126

. 2. DataSet ()
//- SqlCommand DataAdapter DataSet

//

SqlDataAdapter oDA = new SqlDataAdapter(oSelCffld);


DataSet oDs * new DataSetO;
aDA,Fll(oDs, "Orderoetail");

//- ()

//
oOs.Tables["OrderPetail").ColuiBns.AtM("ExtendedPrice",
typeof(tieeimel), "UnitPrice * Quantity"};

//- ."- DataGrid


//
grdGrderQetail.DataSouree = oDs,Tablest"OrderDetail"J.DefaultView;

QrdOrderDetail.DataBindO;
oDs.DisposeO;

DataSet,
. DataTable DataSet
Extended Price decimal. . DataColumn DataTable, . DataRow. ,
10 $7.00,
$70,00.
DataTable,
. , , ,
, .
ExtendedPrice ;
oDs.Tablesf"rderDetail"].Columns.Add("ExtendedPrice",
typeof(decimal), "(UnitPrice * Quantity) * (1 - Discount)");
DataColumn UnitPrice, Discount Quantity. SQL- DataColumn ExtendedPrice .
, : , ,
.

ADO.NET

127

: . ,
, , .
oDs.Tables["rderDetail"].Columns.Add("GetsDiscount",
typeof(bool), "Discount > 0");
, ; , AND, OR
NOT , LIKE
IN.
, ,
DataTable . , ProductName ductlD:
oDs.Tablest"rderDetail"].Columns.AddC'stringfield",
typeof(string), "ProductID + '-' + ProductName");
.r

, . , Len,
lif, IsNull, Convert, Trim Substring.
. Len :
oDs.Tables["OrderDetail"].Columns.AddC'LengthOfProductName",
typeof(int), "Len(ProductName)");
lif, Ilf Visual Basic .NET,
If. , true false.
true, lif , . If...Then...Else, Ilf;
oDs.Tables["OrderDetail"].Columns.Add{"Inventory",
typeof(string),
"Iif(Quantity < 10,'A few left', 'Plenty is stock')");
IsNull
System.DbNull. false,
, (. . System.DbNull) . , ,
NULL-
(placeholder value), , , :

Microsoft ADO.NET

128

oDs.Tables["OrderDetail"].Columns,Add("DiscountString",
typeof(string), "IsNull(Discount, '[null value]')");
Trim .
Convert , , , . Substring, T-SQL,
() . Substring
, (. ). , .
oDs.Tables["OrderDetail"].Columns.Add("ShortProduct",
typeof(string), "Substring(ProductName, 1, 10)");



. , ,
?
.
, DataSet, Order
Order Details Northwind SQL Server. , , . . 3 DataSet,
DataTable ,
DataTable . DataTable DataRelation (Orders2 Order Details).
DataRelation ,
ADO.NET, . MSDN
Magazine 2002 .
. 3,
private void LoadDataO

/ /

- - . ' -

//-

//

SqlGonnaotioR oCn new SqlConnection("Data Source^papa;


"Initial Gatalog*northwlnd;User ID^sa;" *
"PassworcNsecretpassword;");

. . .

ADQ.NET

129

. 3.

//- SELECT
//
string sSQL = "SELECT GrderlD, CustomerlD, QrdsrDate, ShipCity,
ShipCountry " + " FROM
Orders " +
" ORDER BY CustomerlD, OrderDate DESC "; .
SqlCofflroand oSelCmd = new SqlContmand{sSQL, oCn);
. oSelCmd.CommaridType = ComfnandType.Text;

//- SqlCommand e DataAdapter DataSet


//
SqlDataAdapter oOA new SqlOataAdapter(oSelCmd);
DataSet oBs = new DataSet();
oDA.FilKoDs, "Order");
//- SELECT
//
string sSQL "SELECT od.OrderlD, od.ProductID, p.Producttiame,

od.UftitPrice, od. Quantity, od. Discount " +


" FROH [order details] od INNER JOIN Products p 0
od.ProductID - p.ProductlS " +
" ORDER BY od.OrderlD, p.ProductName ";
SqlCommand oSelCffid = new SqlComniand(sSQL, oCn);
oSelCmd.CoiTiBiandType = CommandType.Text;

I/
//- SqlCommand OataAdapter DataSet
//
SqlOataAdapter oDA = new SqlDataAdapter(oSelCmd);
oDA.FillCoDs, "OrderDetail");
//- DataTable
//

'_

oDs. Relations. Add("Order20rderDetail",


oDs . Tables[ "Order" ] . Columns
{"OrderlO"), oDs.Tables["OrderOetail"].ColuiinsC"OrderIO''I);

//- OrderDetail

oDs.Tables["OrderDetail"].Columns.Add("OrderDate",
typeof(string), "Parent.OrderDate");
oDs.Tables["OrderDetail"].Columns,AddC'ExtendedPrlce",
typeof(decifflal), "(UnltPrice * Quantity) * (1 - Discount)");
oDs.Tablesf'OrderDetail"]. Columns. AddC'GetsDiscount",
. . .
5-5947

30

Microsoft ADO,NET

, . ()
typeaf(bool), "Discount > ");
oDs,Taules["OrderDetail"].Columns.Add("stringtest",
typeof{string), "ProductID + '-" * ProductName");
oDs.Tablest"OrderDetail"]. Columns. Addt"Len9thOfPrm3ctHrfe"f
typeof(int), "Len(ProductNaine)");.
oDs.Tables["OrderOetail"].Columns.AddC"Inventory",
typeof(strinff), "lifCQuantity < 10, 'Only a few left',
'Plenty 1 stock')");
oOs, bles[ "Order-Detail"], Columns. Add("DiscountString",
typeof(string), "IsNull(Discount, '[null value]')");
oDs.Tat>les[''QrderDetair']. Columns. Add("ShortProduct",
typeof (string), "Substring(Pro6uctName, 1, 10)+ '...'")

//- Order
o0s.Tables["Order"l.Columns.Add("OrderTotal", tyjssof (decimal)*
"Suin<CHild(Order20rderDetail).ExtendedPrice)");
oDs.Taules["Orcfer"].Columns.Add("AvgOuantity", typeof(decimal),
"Avg(Child(Order2QrderQetail).Quantity)");

, . 3 , DataTable Order.
DataColumn OrderTotal . ,
DataColumn ExtendedPrice DataTable OrderDetail. , , ,
DataRelation, .
''*
ADO.NET , Sum, Avg, Max,
Min, StDev, Var Count. . , Avg .
Parent Child,
, DataRelation:
oDs.Tables["Order"].Columns.AddC'AvgQuantity", typeof(decimal),
Avg(Child(Order20rderDetail). Quantity)");

Child DataRelation, . , DataRelation,


DataTable . DataTable

ADO.NET

DataTable, ,
DataRelation, DacaRelation:
oDs.Tables["Order"].Columns.Add("AvgQuantity", typeof{decimal),
Avg(Child.Quantity)");


Compute
Parent , Child, , ,
DataTable, .
ADO.NET- ,
GROUP BY SQL.

, . , DataTable DataTable,
DataGrid ( ). Parent, DataTable DataTable DataGrid DataTable. ,
DataTable OrderDetail . 3, DataColumn Parent:
oDs.Tables["OrderDetail"].Columns.Add("QrderDate", typeof(string),
"Parent.OrderDate");

(roll up and down) . Parent Child, DataGrid. , SQL-.


,
, DataTable. DataSet, Parent
.
, , Compute DataTable, DataTable . ,
$1000. . Compute ,
OrderTotal, :

132

Microsoft ADO.NET

//- , $1000

int iCnt = (int)oDs.Tables["Order 1 '].Compute("Count(OrderTotal)",


"OrderTotal >= 1000");
IblTest.Text = iCnt.ToStrirtgO + " orders are at least $1000";
Compute , ,
, ,
. , OrderTotal $1000.00 . Compute, ,
DataTable. ,
, ,
, , ,
.
, DataColumn
. ,
, . ,

XML-. ,
, , .
SQL ADO.NET. , ,
, .
(Johnny Papa) - MJM Investigations
(, ),
ADO, XML SQL Server. , VSLive.
datapoints@lancelotweb.com.


ADO.NET-

, ADO.NET.
- DataSet DataTable,
ISerializable.
, ADO.NET,
XML-.
.NET- , ,
ADO.NET .

ADO.NET ADO XML. XML ADO


-. , ADO XML
. XML ADO.NET, ,
,
ADO.NET-. ,
, . , . . ADO.NET-.
, XmlDaiaDocument,
MSDN.
ADO.NET- . -,
* MSDK Magazine/ . 2002. 6 (). . .

34

Microsoft ADO.NET

Microsoft .NET Framework,


(formatters), SOAP
(SOAP formatter) (binary formatter). -,
ADO.NET-, XML- .
, -
ADO.KET- DataSet DataTable,
ISerializable.
.NET Framework. DataSet ( WriteXral), . XML. , ADO.NET DataTable, Data View DataRow .
, ADO.NET-, XML-. .NET-
, ( ) (Jeffrey Richter)
.NET*. , , . , ADO.NET- .

DataTable
System.Data DataSet XML, (class-defined XML format). ADO.NET XML. WriteXml
DataSet
(relations) .
DataTable XML .
, XML DataTable, - DataSet,
.
DataSet XML
DataTable XML, . , -

. MSDN Magazine/ . 2002. 2, 1(7), 3(9). - . .

ADO.NET-

135

DataSet, ,
XML. . 1 ,
DataTable , ,
DataSet. Write DataTable
, WriteXml DataSet. DataTable . 1 DataSet, DataTable.
, ( ) . , XML-. , DataSet XML-:
DataSet ds = new DataSet("DataTable");
if (dt.DataSet == null)
ds.Tables.Add(dt);
else
ds.Tables.Add(dt.CopyO);
. 1.

MsdnMagActoNetSerializer

public class MsdRMagAdoNetSerializer


I
public static void WriteDataTable( DataTable eft, XmlWriter writer)
i
WriteDataTable(dt, writer, XmlWriteMode. IgnoreScnema);
1
public static void WriteDataTableCDataTable dt, Stream stm)
(
WriteDataTable( dt , stm, XmlWriteMode . IgnorsSchema) ;
public static void WriteDataTableCDataTable dt, Stream stm,

XmlWritettode mode)

DataSet trap = CreateTeiapDataSet(dt);


tmp.WriteXmlCstis, mode);

public static void WriteOataTable( DataTable dt, string output-File)


{
WriteDataTabIe{dt, output File, XmlWriteHode.IgrtoreScnema);
public static void WriteDataTable(OataTable dt, string outputFils,
XmlWriteMode mode)

. . .

Microsoft ADC .NET

136

. 1. MsdnMagAdoNet&erializer ()
DataSet trap - CreateTempDataSet(dt);
tmp.WriteXflil(QutputFile, mode);
public static void WriteDataTable{DataTable dt, string outputFile,
XmlWriteHode mode)
{
DataSet tmp - CreateTempDataSet(dt);
tmp.WriteXmKoutputFile, mode);
private static DataSet GreateTempDataSet(DataTable dt)
// DataSet
DataSet ds = new DataSet{"DataTable");
// , DataTable
// - DataSet
if(dt.DataSet == null)
ds.Tables.Add(dt);
else
ds.Tables.Add(dt.Copy());
return ds:

, DataTable
DataSet; . DataTable , DataSet null.
DataSet. , . DataTable.
ISerializable (. ISerializable).
MsdnMagAdoNetSerializer, Write DataTable, . (http://msdn.microsoft.com/msdnmag/code02.aspx ). :
StringWriter writer = new StringWriterO;
MsdnMagAdoNetSerial:izer.WriteDataTable( table, writer);
//
OutputText.Text = writer.ToString();
writer.Close();

ADO.NET-

3,37

WriteDataTable
. StringWriter
(text writer), ToString .
DataTable. , , (, , ).

DataView
DataView DataTable.
- (document/view model). DataTable ,
DataView . . , , . , .
DataView
DataTable. ,
, .
.
Data View- RowFilter Row State Filter, , . Sort
, . DataView . 2. - , DataView
DataTable , . . - ,
, .
DataTable DataView DataTable
DataView:
public DataView(DataTable table);

, , Table DataView:
DataView dv = new DataViewO;
dv.Table = dataSet.Tables["Employees"];

Microsoft ADO-NET


Dataflow
Dataflow
. 2.

Dataflow

DataView

:
DataView DataTable- DefaultView. DataView,
:
DataView dv = dt.DefaultView;

, . DataView ,
(collections), (enumerators). , GetEnumerator
, foreach. , :
DataView myView = new DataView(table);
foreach(DataRowView rowview in myView}
{
// (dereference) Dataflow
Dataflow row = rowview.Row;
-

, ,
(. 2). , , DataRowView . DataRowView
DataRow, . DataRowView ,
. DataRow DataRowView Row .
, , , DataView . , DataView -

ADO.NET-

139

. , , , .
, , ,
- , Data View
Data Row View, DataRow.

DataView
MsdnMagAdoNetSerializer, . 1,
DataView, , DataTable ,
(. 3).
. 3.

DataTable

public class MsdnHagAdoNetSerlalizer

public static void WriteDataViewC DataView dv, string outputFile,


XmlWriteMode mode)

{
OataTable dt = CreateTefflpTable(dv);
WriteDataTable(dt, outputFile, aode);

private static DataTable CreateTefpTable(DataView dv)


{
// DataTable,
//
DataTable dt * dv. Table, CloneO;
// DataTable
foreach<DataRowView rowvlew in dv)
dt . Import Row( rowview. Row) ;
return dt;

DataTable , , DataView.
, . , XML
WriteDataTable.

j_4Q

Microsoft ADO,NET

DataTable- ImportRow . 3, DataRow , .


DataRow, ADO.NET-, -. ImportRow .
. NewRow, , ImportRow .

DataRow
ADO.NET- XML. DataSet, , DataRow,
DataTable,
DataSet.

ADO.NET-
, ADO.NET: XML- , , .NET Framework
. ADO.NET XML, API-, , DataSet.
, ADO.NET-,
.NET Framework .
WriteXml
.NET Framework , . , , .

, ,
. [serializable] . , , API (reflection),
.NET Framework.
ISerializable;
, . , , . ,

ADO.NET-

141

[serializable] ISerializable, . , ADO.NET


, DataSet
DataTable. , DataColumn DataRow
. , , ;
.
.NET- .

ADO.NET-
.NET Framework
System.Runtime.Serialization.Formatters: SOAP.
BinaryFormatter SoapFormatter.
, SOAP.
, DataTable :
BinaryFormatter bin = new BinaryFormatterO;
StreamWriter dat = new StreamWriter(outputFile);
bin.Serialize(dat.Basestream, dataTable);
dat.CloseO;

Serialize . Deserialize : , :
DataTable table = new DataTableO;
BinaryFormatter bin = new BinaryFormatterO;
StreamReader reader = new StreamReader(sourceFile);
table = (DataTable) bin.Deserialize(reader.BaseStream);
reader.CloseC);

. -
. DataTable
DataSet ,
, , ,
XML-. , XML- .
, . ,
ADO.NET- , . ADO.NET-

142

Microsoft ADO.NET

, .
?
ADO.NET-,
( DataTable DataSet),
ISerializable, , . GetObjectData, .
DataTable DataSet ,
XML-. , DifrGram, . . XML. . ,
XML, . ,
,
, .NET Framework, ADO.NET ( , ).
.NET;
void GetObjectData(SerializationInfo Info,
StreamingContext context)
{

info.AddValue("XrnlScfiema", this.GetXmlSchemaO);
this.WriteXmKstrWriter, XmlWriteMode.DiffGram);
info.AddValueC'XmlDiffGram", strWriter.ToStringO);

, Serializationlnfo AddValue. , DataSet


, .
DataTable ,
DataSet, , XML, , Serializationlnfo,
SOAP-
.


ADO.NET-
DataTable ( DataSet) , .

ADO. NET-

143

. , DataTable DataSet,
. .NET-pecypc, , (surrogate types). ,

, . ,
, .

. , ,
DataTable ( ).
ADO.NET-
, , , , .
, DataTable ( DataSet),
(ghost serializer class) , ISerializable.
DataTable .
. DataTable (),
. DataTable
,
DataTable. .


DataTable,
. :
[Serlalizable]
public class GhostDataTableSerializer
{

protected ArrayList colNames;


protected ArrayList colTypes;
protected ArrayList dataRows;
public GhostDataTableSerializerO { . . . }
public void Load(DataTable dt) {...}

Microsoft ADO.NET

144

public DataTable SaveC) { . . . }


!

. 4. Ghost DataTable Serializer ArrayList, ,


. , ArrayList .
DataTable
:
void BinarySerialize(DataTable dt, string outputFile)
{
BinaryFormatter bin = new BinaryFonnatter();
StreamWriter dat = new StreamWriter(outputFile);
//
//
GhostDataTable ghost = new GhostDataTablef);
ghost.Load(dt);
//
bin.Serialize(dat.BaseStream, ghost);
dat.CloseC);

. 4.

GhostDataTabteSettalizer

using System;
using Systeffl.Collections;
using System.Data;
// ,
[SerlalizableJ
public class GhostDataTatileSerializer
i
public GlrostBataTableSe rialize r()
{
colNames = new ArrayListO;
colTypes = new Arraytistf);
dataRows = new ArrayListO;

//
protected ArrayList eolNantes;
protected ArrayList colTypes;
protected ArrayList dataRows;
. . .

AOO.NET-

. 4. GhostDataTableSeriatizer

//
public void Uad(DataTable dt)
{
// ( )
foreachCDataColumn col in dt. Columns)
colTypes. Add(col , DataType. FullHanie);

//
foreachtOataflow row in dt.Ftows)
dataflows. Add(row.ItemAr ray);

// DataTable,
public fiatsTable SaveC)
i
DataTatle dt = new OataTableO;
//
foKirvt 1=0; i<colNames..Count; 1--)
{
OataColumn col = new DataColufflrr(colHaiBesti3.ToString(),
Tyoe.6etType(colTypes[l].ToString() ));
dt,Columns.,Add<col);

//
for(int 1=0; KdataRows, Count;
DataRow row = dt.NewRowO:
row. IteraArray = (ob}ect[]) dataRowstl];

dt, Rows. Add{ row);


dt , AcceptChangesC } ;
return dt;

145

146

Microsoft ADO.NET

JSerializable
, DataTable ISerializable.
. ? ISemlizable, .
DataTable
,
, .
, ISerializable
ADO.NET.
BinDataTable ( ) , ,
ESerializatele]
class BinDataTable : DataTable, ISerializable {

protected 8inQataTable(SerializaticmInfQ si, StreaningContext ctx}


void System, Runtime, Serialization. ISerializable.
QetObjectDataCSerializatlonlnfo si, StreafltingContext ctx)

GetObjectData , DataTable, ;
. : BinDataTable. , , MSDN Magazine .
.
, : DataTable GhostDataTableSerializer.
Load.
(colNames colTypes) , DataRow ,
.

ADO.NET-

147

public void Load(DataTable dt)


{
foreach(DataColunm col in dt.Columns) {
colNames.Add(col.ColumnName);
colTypes.Add(col.Datatype,FullName);

foreach(DataRow row in dt.Rows)


dataRows.Add{row.ItemArray);

ItemArray DataRow .
,
, . (get
accessor) ,
. (set accessor)
, BeginEdit/EndEdit ,
.
, AcceptChanges (. 4)
Unchanged, . - ,
Added. , , , , .
. 5 -. ,
DataTable, , 80% ,
, . , , DataTable, :
SELECT * FROM [Order Details]
ilsiiio a Ghost berlaiazef ties*.

. 5.

148

Microsoft ADO.NEt

2000 . DataTable,
. 83% .
, .
, ,
. , BLOB, . Northwind
SQL Server, BLOB- :
SELECT photo FROM employees
25%, , . , , . BLOB-
, .


, DataTable. ,
-:
DataTable BinaryDeserialize(string sourceFile)
{
BinaryFormatter bin = new BinaryFormatterO;
StreamReader reader = new StreamReader(sourceFile);
GhostDataTableSerializer ghost;
ghost = (GhostDataTableSerializer) of.Deserialize(reader.BaseStream);
sr.Closef);
return ghost.Savef);
}

Save ,
, DataTable (. 6).

?
DataTable ,
. - , , ADO.NET-. , , , DataTable DataTableSurrogate:

ADQ.NET-

. 6.

149

public DataTable Save()


{

DataTable dt - new DataTableO;

//
for(int 1=0; KcolNames. Count;
BataColuim col = new OataColumn(colNames[i].ToStrlng(),
Type.GetType(eolTypes[i].ToString()));
dt.Coiueins.Add(col);
//
forfint i=0; Kdataflows.Count; i--)
{
OataRow row = dt.NewRowO;
row.IteieArray = (objectU) dataRows[i];
dt.Rows.Add(row);

dt.AceeptChanges();
return dt;

*
SurrogateSelector ss = new SurrogateSelector();
DataTableSurrogate dts = new DataTableSurrogate();
ss.AddSurrogate(typeof(DataTable),
new StreamingContext(StreamingContextStates.All), dts);
formatter.SurrogateSelector = ss;
formatter.Serialize(dat,BaseStream, dt);

(surrogate selector)
. . ISerialization Surrogate, : GetObjectData Set Object Data.
Serializationlnfo, . 7. . 8 , , .
, .
, , ADO.NET-, .
, ,
DataSet DataTable ,
. .NET

150

Microsoft ADO.NET

.
GetUninitializedObject FormatterServices, . , , ,
.
. 7.

public class DataTableSurrogate : ISerializationSurrogate


{
public void GetQftjectData(object obj,
Serializatlonlnfo iRfo, StreamingContext context)
{
DataTable dt = (DataTable) obj;
AddSerializationInfo(<ft, info);
public object SetObjectData(object obj, Serializationlnfo info,
StreamingContext context, JSurrogateSelector selector)
DataTable dt * (DataTable) obj;
ReadSerializationInfo(dt, info);
return null;

Pc. 8.

protected void Flll(BataTable dt. Serializationlnfo info)


{
ArrayList colNames - new ArrayLlstO;
Array-list colTypes = new ArrayListO;
ArrayList dataflows = new ArraylistC);
// ( )
//
foreacnCDataColumfl col in dt.Columns)
colNames.Add<col.ColumnName);
colTypes.Add(col.DataType.FullName);
//
f0reacft(DataRow row in dt.Ros)
dataflows. ( row. IteaArray);

. . .

.-

151

. 8. ()
// ,
//
info,AddValae{"ColNaies", colNames);
info.AddValue("ColTypes", colTypes};
info.AddValue<"DataRows", dataflows);

, DataTable . null.
, . GetUninitiaHzedObject
. , . , , DataTable,
, ,
( .NET-). DataTable, , , .

, ADO.NET- .
. , ,
, , , ,
. , SetObjectData . ,
Get Uninitialized,
SetObjectData
. .
.NET 2002 . (http://
msdn.microsoft.com/msdnmag/issues/02/09/net/default.aspx).
(Dino Esposito) .
Building Web Solutions with ASP.NET and ADO.NET Applied XML
Programming for .NET ( Microsoft Press
2002 .). dinoe@wintellect.com.

.NET

,
Microsoft .NET.

,
.
,
, .
.
, (transaction
boundaries), . , , .
ACID: Atomicity (). Consistency (), Isolation () Durability (). . Processing Transactions (http://rasdn.microsoft.com/

Priya Dhawan Transaction Control. Building Distributed Applications with .NET//MSDN


Library. 2001. November. . .

.NET

J.53

library/en-us/cpguide/html/cpconprocessingtransactions.asp) Microsoft
.NET Framework SDK Microsoft Platform SDK.
,
Microsoft .NET.


,
, , Microsoft SQL
Server, MSMQ . ,
ACID, , . SQL Server
(transaction manager), (commit) (rollback) .
,
, ,
SQL Server,
Message Queue Server . , , , . Microsoft DTC (Distributed Transaction Coordinator).
DTC (two-phase commit protocol),
, . DTC , .
(Resource Managers). [ .
Distributed Transactions (http://msdn.microsoft.com/library/en-us/cpguide/htnil/cpcondistributedtransactions.asp) .NET Framework Developer's
Guide.] MSMQ, Microsoft SQL Server, Oracle, Sybase ,


(stored procedure), BEGIN TRANSACTION COMMIT/ROLLBACK TRANSACTION, ,
(single
round-trip). , ,
. . ,

Microsoft ADO.NET

154

BEGIN TRANSACTION
. :
COMMIT TRANSACTION, ( - ) ROLLBACK TRANSACTION.
CREATE PROCEDURE Prod

AS

--
BEGIN TRANSACTION
--

If @@Error
-
ROLLBACK TRANSACTION

-
COMMIT TRANSACTION

XML- (order). Orders OrderDetails


XML
sp_xrnlpreparedocument. , ,
().
, XACT_ABORT ON, , SQL Server ,
- .
CREATE PROCEDURE InsertOrder
@0rder NVARCHAR(4000) = NULL
, eOrderld int Output
AS
SET NOCOUNT ON
DECLARE @hDoc INT
DECLARE @PKId INT
-- , SQL Server
-- , Transact-SQL
(run-time error)
SET XACT_ABORT ON
-
BEGIN TRANSACTION
- XML-

.NET

155

-- , XMLDocument
EXEC sp_xml_preparedocument @hDoc OUTPUT. @0rder
-- XMLDocument- Orders
-- Orders
INSERT Orders(CustomerId,
OrderDate,
ShipToName,
ShipToAddressId,
OrderStatus)
SELECT Customerld, CONVERT(DateTime,OrderDate), ShipToName,
ShipToAddressId, OrderStatus
FROM OPENXHL(@hDoc, '/NewDataSet/Orders')
WITH ( Customerld int 'Customerld1,
OrderDate nvarchar(23) 'OrderDate',
ShipToName nvarchar(40) 'ShipToName',
ShipToAddressId int 'ShipToAddressId',
OrderStatus int 'OrderStatus')
-- Orderld , Orders
(order details)
SELECT SPKId = IDENTITY
- XHLDocument- Details
-- QrderDetails
INSERT OrderDetails (Orderld,
Itemld,
UnitPrice,
Quantity)
SELECT PKId as Orderld, Itenld, UnitPrice, Quantity
FROM OPENXML(@hDoc, '/NewDataSet/Details')
WITH (Itemld int 'Itemld',
UnitPrice money 'UnitPrice',
Quantity int 'Quantity')
-
Select @0rderld = QPKId
-
COMMIT TRANSACTION
EXEC sp_xml_removedocument @hDoc
RETURN 0
GO
,
Transact SQL, , , .NET.


, (manual transactions),
. , . .
.

156

Microsoft ADO.NET

,

. ,

. , ACID .

ADO.NET,
Microsoft
ADO.NET, , , , , , .
ADO.NET- SQL (ADO.NET
SQL managed provider).

SQLTransaction, SQLConnection, ,
, . SQLTransaction . Commit.
Rollback SQLTransaction.
SQL- Transaction
Command .
Visual Basic .NET
Dim conn as SQLConnection
Dim cmd as SQLComrcand
Dim txn As SQLTransaction
conn = New SQLConnectionC'ConnString")
cmd = New SQLCommand

conn.OpenO

txn - conn.BeginTransaction()
Transaction ,
' SQL-
cmd.Transaction - Txn

.NET

Visual C# .NET
SQLConnection Conn = New SQLConnectlon(TTConnString");
SQLCommand Cmd = Kew SQLCommand;
//
Conn.OpenO;
//
3QLTransaction Txn ~ Conn.Begin!ransaction();
// Transaction ,
// SQL-
Crnd.Transaction - Txn;
, ,
SQL-. (order header) Orders Orderld . OrderId , OrderDetails. ,
; .
Visual Basic .NET
Dim conn As SqlConnection
Dim cmd As SqlComntand
Dim tran As SqlTransaction
1

conn = New SqlConnection("ConnString")
'
conn.OpenO
' Command
cmd = New SqlCommandO
1

tran = conn.BeginTransaction
' Transaction ,
1
SQL-
cmd.Transaction = tran
Try
' . Command.
With cmd
.CommandType = CommandType.StoredProcedure
,CommandText = "InsertOrderHeader"
.Connection = conn
'
.Parameters.Add("@Customerid", SqlDbType.Int)
.Parameters("@Customerid").Direction = ParameterDirection.Input
1


.Parameters("CustomerId").Value = 1

Microsoft ADO.NEt

158

'
. ExecuteNonQueryO
' Qrderld
Qrderld = .Pararneters("@0rderld").Value
'
.Parameters.clearf)
End With
' . Command.
With cmd
.CommandType = CommandType.StoredProcedure
,CommandText = "InsertOrderDetail"
.Connection = conn
'
.Parameters.Add("0rderld", SqlDbType.Int)
. Parameters("@|OrderId"}.SourceColumn = "Orderld"
.Parameters("@0rderld").Direction = ParameterDirection,Input
'
.Parameters*"@0rderld").Value = Orderld
.Parameters("@ltemld").Value = 100
'
, ExecuteNonQueryO
'
End With
'
tran.Commit()
Catch
1

tran.Rollback()
Finally
1
. .
conn.Close()
End Try
, .
, ,
. try /catch/finally, :
try SQL-.
catch,
, , .
ADO.NET
,
. , ADO.NET,

.NET

15

,
,
.
ADO.NET
.

MSMQ,
.NET Framework MSMQ:
( ) (
).
.
DTC (Distributed Transaction Coordinator).
MSMQ, ,
MessageQueueTransaction MSMQ.
. - (Duncan Mackenzie) Reliable Messaging with MSMQ and .NET (http://msdn.microsoft.com/library/
en-us/dnbda,/html/bdadotnetasync2.asp).


.NET Framework
MTS/COM+. + DTC
. .NET , ,
SQL Server, MSMQ (Microsoft Message Queue),

Oracle.
(declarative transactions), COM+ , . ,
,
DTC ; , .
ASP.NET, Web- .NET-
,
(declarative transaction attribute).
ASP.NET
<@ Page Transaction="Required">

Microsoft ADO.NET

160

Web- ASP.NET

<%@ WebService Language="VB" Class="Class1" X>


<W assembly name="System.EnterpriseServices" %>
Public Class Classl
Inherits WebService
<WebMethod(TransactionOption := TransactionOption.RequiresNew)>
Public Function Methodic)
.NET- System.EnterpriseServices.ServicedComponent, +. , +, DTC,
. ,
,
.
Visual Basic .NET
<Transaction(TransactionOption.Required)> Public Class Classl
Inherits ServicedComponent

Visual C# .NET
[Transactlon(TransactionOption. Required)]
public class Classl : ServicedComponent {

Disabled. ,
+. DTC
.

NotSupported.
.

Supported. ,
. , .

Required. , .
,
.

, -

,NET

161

* RequiresNew. ,
.
.NET-,
+. , , +-.
Visual Basic .NET
Imports
Imports
Imports
Imports

System
System.Runtime.CompilerServices
System.EnterpriseServices
System.Reflection

.
COM--- ,
' +
<Assembly: ApplicationName("Classl"}>
' (strong name) (assembly)
<Assembly: AssemblyKeyFileAttribute("class1,snk")>
<Assembly: ApplicationActivation(ActivationOption.Server)>
1

<Transaction(TransactionOption.Required}> Public Class Classl


Inherits ServicedComponent
Public Sub Example1()
End Sub
End Class

Visual C# .NET
using
using
using
using

System;
System,Runtime.CompilerServices;
System.EnterpriseServices;
System.Reflection;

// ,
// +- ,
// +
[Assembly; ApplicationName("Classl")]
//
[Assembly: AssemblyKeyFileAttribute("class!.snk")]
[Assembly: ApplicationActivation(ActivationOption.Server)]
[Transaction(TransactionOption,Required)]
public class Classl : ServicedComponent {
[AutoComplete]
public void Example1()
i

Microsoft ADO.NET

162

<Assembly; ApplicationName(Classl)> +-, , a <Assembly: ApplicationActivation(ActivationOption.Server)> , . Application Activation(ActivationOption.Server), GAC


(global assembly cache) gacutil
(GacUtil.exe).
,
+-
Regsvcs.exe. , , . ,
Application Activation( Activation Option. Server), . +, , +. +-,
, Component Services.
, (serviced components) Writing Serviced Components (http://msdn.microsoft.com/library/en-us/cpguide/html/cpconwritmgservicedcomponents.asp) .NET Framework Developer's Guide.
, +, SQL-.
Orderld . Orderld

OrderDetails. ,
; .
Visual Basic .NET
<Transaction(TransactionOption.Required)> Public Class Classl
Inherits ServicedComponent
Public Sub Exampl1()

Try
'

.NET

163

conn = New SqlConnectionC'ConnString")


'
conn.OpenO
' Command
cmd = New SqlCommandO
' ,
1
Command.
With cmdl
.CommandType = CommandType.StoredProcedure
.CommandText = "InsertQrderHeader"
.Connection = conn
'
.Parameters.Add("@CustomerId", SqlDbType.Int)
, ExecuteNonQuervO

.Parameters.clear()
End With
' ,
1
Command,
With cmd
.CommandType = CommandType.StoredProcedure
.CommandText = "InsertOrderDetail"
.Connection = conn

.Parameters.Add("Orderld", SqlDbType.Int)

. ExecuteNonQueryO

End With
'
Contextlltil. SetComplete()
Catch
'
ContextUtil.SetAbortO
Finally
'
End Try
End Sub
System. Enterprise Services. Context Util,
+-. SetComplete SetAbort,
. , ContextUtil.SetComplete try, . -

164

Microsoft ADO.NET

catch,
Context Util.SeiAbort.
, - (attribute class) System. EnterpriseServices.AutoComplete ,
, . ,
. ,
; ContextUtil.SetAbort .
, <AutoComplete> :
Visual Basic .NET
<Transaction(TransactionOption.Required)> Public Class Class"!
Inherits ServicedComponent
<AutoComplete()> Public Sub Example1{)

End Sub
End Class

Visual C# .NET
[Transact ion(TransactionOpt ion. Required)]
public class Class"! : ServicedComponent {
[AutoComplete]
public void Example1()

'<

<AutoComplete> ,
. , ,
ContextUtil.SetAbort catch. ,
. , , . , ContextUtil.SetAbort
.
, , MSMQ,
,
DTC +. DTC , , , -

.NET

. MSMQ
SQL Server . - Reliable Messaging with
MSMQ and .NET (http://msdn.microsoft.com/library/en-us/dnbda/html/
bdadotnetasync2.asp).


. ,
. , , . ,
, Transact SQL. , .NET.
,
ADO.NET, .
, .
.
, ,
, SQL Server, MSMQ
. . . -
, +, .


SQL*

, , SQL Server.
SQL- IDENTITY, LEFT JOIN CROSS JOIN.
, HAVING WHERE GROUP BY
DISTINCT .

, , . !
, - SQL- , :
, . ,
? , ,
? ,
. (, .
LEFT JOIN.) , ,
. , - - . ( , .)
. ? . , ,
MSDN Magazine/ . 2002. 1 (). . .

170

Microsoft SQL Server

SQL Server. LEFT JOIN


CROSS JOIN, IDENTITY. , . , . , - , .

IDENTITY INSERT
, , , : IDENTITY SQL- INSERT?
, ,
, . SQL Server,
IDENTITY, SQL- , ;
SELECT @@IDENTITY

SQL-, :
INSERT
, . INSERT , :
INSERT INTO Products (ProductName) VALUES ('Chalk')
SELECT ^IDENTITY

Northwind, IDENTITY Chalk ().


, Visual Basic, ADO,
:
Set ofis = oCn.ExecuterSET NOCOUNT ON;INSERT INTO Products (ProductName)
VALUES ('Chalk');SELECT IDENTITY")
IProductID = oRs(O)

SQL Server ,
INSERT IDENTITY,
, SET NOCOUNT ON , Recordset
IDENTITY.
Recordset ( INSERT ),
Recordset, IDENTITY.
, INSERT Recordset. , SQL Server

SQL

171

, - ,
Recordset. Recordset.
Recordset ADO-
Next Recordset, ( ) , Recordset.
, SQL-.
SET NOCOUNT ON INSERT, FOR INSERT
SELECT IDENTITY, .
INSERT, ,
IDENTITY.
CREATE TRIGGER trProducts_Insert ON Products FOR INSERT AS
SELECT @@IDENTITY
GO

, INSERT
Products, IDENTITY
.
IDENTITY .


,
GROUP BY . ,
, , . SQL-, . , Products, ,
:
CREATE TABLE Tempi (OrderlD INT NOT NULL, OrderDate DATETIME NOT NULL)
INSERT INTO Tempi (OrderlD, OrderDate}
SELECT
TOP 5 o.OrderlD, o.OrderOate
FROM Orders ORDER BY o.OrderDate DESC
SELECT
p.ProductName, SUM(od.Quantity) AS ProductQuantity
FROM
Tempi t
INNER JOIN [Order Details] od ON t.OrderlD = od.OrderlD
INNER JOIN Products p ON od.ProductID = p.ProductID
GROUP BY p.ProductName
ORDER BY p.ProductName
DflOP TABLE #Temp1

172

Microsoft SQL Server

, , . , .
-, ,

(inline view) , FROM.
, -:
SELECT p.ProductName,
SUH(od.Quantity) AS ProductQuantity
FROM
(
SELECT TOP 5 o.OrderlD, o.OrderDate
FROM
Orders
ORDER BY o.OrderDate DESC

) t
INNER JOIN [Order Details] od ON t.OrderlD = od.OrderlD
INNER JOIN Products p ON od.ProductID = p.ProductID
GROUP BY p.ProductName
ORDER BY p.ProductName

, . ,
.
, .

LEFT JOIN NULL


, , LEFT JOIN NULL
. . SQL-, , , , . , . TABLE,
,
. , SQL ,
LEFT JOIN.
, . , ,
LEFT JOIN , ,
.
. LEFT JOIN , NULL ( ). - LEFT JOIN ,
. LEFT JOIN , INNER JOIN, , , LEFT JOIN, (. 1).

SQL

173

JOIN
. 1.

LEFT JOIN
TABLE ( LEFT JOIN), TABLE
. , LEFT JOIN. ,
.
, .
( ) SQL
Server , .
,
, . , .
, LEFT JOIN, . , - , - . ,
,
NULL. ,
, LEFT JOIN.
No Category
(foreign key relationship), NULL.
INNER JOIN.

174

Microsoft SQL Server

, LEFT JOIN.
, . :
,
, .


, : (Cartesian product)
. - (CROSS JOIN)
,
. CROSS JOIN .
SQL. ,
,
, - .
SQL- . 2. : (INNER JOIN) Customers Orders
,
, .
, . ,
,
, . SQL-
. 2 , ,
Orders (,
, ).
. 3 , ,
. TABLE
(@tblMonths). , - ,
(@tblCustomers). , (resultset),
, .
(12 ), , . ( 81 ). 12 ,
INNER JOIN LEFT JOIN , .

SQL

175

. 2.

set nocount on
DECLARE dtStartDate DATETIME,
9dtERU&ate DATETINE,
SUtDats
SET SdtEndDate = '5/5/1997'
SET dtEntfBate * BATEABBCQD, -1. CAST(CASTMONTH(tftEndDate) + 1)
AS VABCHAR(2)} + '/01/' + CAST(YEAR(@dtEndDate) AS VARCHftR<4
23; 59:59' AS DATETIME
SET $dtStartDate * DATEAEJD(HM, -1 * 12, edtEndDate)
SELECT CAST(YEAR(O.OrderOate) AS VAflCAR<4 + *-' +
CASE
WHEN MOmiCo.QrderDate) < W
THEN 000 + CAST(KQ8TH{o.Qr<lerDate) AS VARCHAR(2
ELSE GAST(HmiTH(o.QrderDate) AS VARCHAR(2)>
ES& AS sMonth,
c.CustomerlD,
.,
c.ContactHame,
SyM<od.Quantity * od,UnltPrioe) AS mSales
FROM Gustwiiers e
INNER JOIN Orders ON c-Customerlt = o.CustomerlO
INNER JOIN tOrder Details] od ON o.OrderlD - Qd.OrderlD
WHERE
o.OrderDate BETWEEN @dtStartDate AND SdtEndDate
GROUP BY
CASTCYEAR(o.OrderBate) AS VARCHAR(4)) * '-"*
CASE
HGNTH(o.CrderPate) < 19
THQi 000 + GAST(HQNTH(Q,OrderOate} AS VAfiGHAR(2)}
Ei^ CAST(MQNTH<o.OrderDate) AS VARCHAft(2

END,
c.CustoraerlO,
c.CoapanyNarae,
G,CorttactNaffle
OfiDEft BY

"=.;'

c.CompanyNaroe,
sKonth

.
, , . , @tblFinal 972
. @tblFinal

176

Microsoft SQL Server

.
. 3.
DECLARE etblMonths TABLE (sHonth VARCHAR(7
DECLARE etblGustomers TABLE
CustomerlD CHAR(10),
CompanyName VARCHAR(50),
ContactNaroe VARCNAR(SO))
DECLARE tblFinal TABLE {
sMonth VARCHARC7),
CustomerlD CHAR(1Q),
CompanyName VARCHAR(50),

ContactKame VARCHAR(SO),
mSales KQNEY)
DECLARE @dtStartDate .
@dtEndDate DATETIME,
dtDate DATETIME,
91 INTEQER
SET dtEndDate = '5/5/1997'
SET SdtEfidDate = DATEADD<DO, -1, CAST(CAST(CMOTH(@dtEndDate) + T) AS
VARCHARC2 + 701/' + CAST(YEAR(@dtEndBate) AS VARCHARC4 + '
23:59:59' AS DATETIME))
SET dtStartDate = OATEADD(MH, -1 * 12, tdtEndDate)

SET W
WHILE < 12)
BEGIN
SET @dtDate = DATEADDCm, -1 * !, (MtEndDate)
INSERT INTO @tbIMortths SELECT CAST(YEAR(dtDate) AS VAfiCHAR(4 + 0
CASE
WHEN MONTH(edtOate) < 10
THEN '0' + CAST(HONTH(@dtDate) AS VARCWAR(2))
ELSE CAST(MONTH(&dtOate) AS VARCHAR{2)>
END AS sMonth
SET &i = 91 + 1
EHD

, - , ''
INSERT INTO tblCustomers
SELECT
DISTINCT
. Customer-ID,
c.CompanyNaroe,
c.ContactName
FROM Customers
INNER JOIN Orders ON c.CustomerlD * o.CustofflerlD
. WHERE
o.OfderDate BETWEEN eeftStartDate.AND fcJtEndDate

. . .

SQL

177

, 3, ()

IHSE8T INTO
SELECT
m.sHonth,
c.CustofflerIC,
c.CompanyName,
c.ContactNaffle,
0
FHOM @tblHonthS n CROSS JOIN tblCustGlsers
UPDATE tblFinal SET
mSales - mydata.fflSales
tblFinal f INKER JOIN
SELECT
c.CustoraerlD,
CAST(YEAR(o.QrderDate> AS VAfiCHAR(4))
CASE WKEN MQNTH(o.QrderDate) < 10
THEN '0' + CAST(MONTHo.QrderDate) AS VARCHARC2))
ELSE CASTCHONTHCo.QrtlerDate) AS VARCHAR(2)}
END AS SHonth,

SUH( od. Quantity * od.UnitPrice) AS raSales


FROM Customers
JOIN Orders ON c.CustoroerlD = o.CustomerlO .
INKER JOIN tQrder Details} od ON o.OrderlD = od.OrderlD
WHERE
o.OrderDate BETWEEN 9dtStartDate AND dtEndSata
GROUP BY
c.CustojaerlD,
CAST(YAR<O.OrderDate) AS VAfiCHAR(4)) + '-; +
CASE WHEN HOHTHCo.OrderDate) < 10
THEN '0' + CAST{MQNTH<O.GrtferOate) AS VARCHAR(2))
ELSE CAST(HONTH(o.OrderOate) AS VARCHAR<2
END

) mydata on f.CustomerlD * mydata.CustomerlD AND f.sMonth =


mydata.sltonth
SELECT
f.sMonth,
f.CustomerlD,
f.Com&anyName,
f.ContactName,
f .mSales
.FROM etblFinal f
ORDER BY

f.sHonth

CROSS JOIN , . , ,
CROSS JOIN, WHERE, DISTINCT GROUP BY, ,

178

Microsoft SQL Server

(INNER
JOIN). , , .
.


, SQL. ,
, ,
. HAVING
, WHERE.
WHERE , ,
, HAVING. - HAVING ,
WHERE.
, , DISTINCT GROUP BY , (distinct list of data
rows). DISTINCT .
GROUP BY SUM, COUNT, . . , DISTINCT , , . DISTINCT
.
, - . ,
. : , . SQL Server, , SQL Server.
(Johnny Papa) - MJM Investigations
(, ).
Professional ADO 2.5 RDS Programming with ASP 3.0 (Wrox, 2000).
.
datapoints@lancelotweb.com.

SQL



SQL Server 2000
VBScript-*

(application service providers, ASP)


,
, -
. SQL Server
, , ,
, (scripts). ,
DTS (Data Transformation Services) SQL
Server SQL Server
2000 .

(push), Web- (Web casting), . , Web-


. ,
(push application)
.
, - , ,
.

MSDN Magazine/ . 2002. 2 (). . .

18G

Microsoft SQL Server

. , ,
, . ,
, , ,
-, ,
. ,
.
, ,
DTS (Data Transformation Services), SQL Server 2000.
. ,
, (workflowdriven). , DTS .
DTS- (DTS package) , , , .
(steps)
(tasks), . , , . , ,
. DTS Designer,
.
VBScript JScript , , DTS-. , :

ADO-, ,
(recordsets) ;

, -;

, , DTS ActiveX-;

DTS.

SQL Server 2000 ...

-
, VBScript- , DTS,
, VBScript- , (scheduled task). DTS,
, VBScript
SQL Server 2000.

{
SQL Server)

DTS-
s SQLServer 2000

VBScript-


DTS-

VBScript
.

( )

OTS- ,

. 1. DTS-

. 1 ,
- DTS. VBScript- B'DTS-

. .
Pubs, SQL Server 2000, .

182

Microsoft SQL Server

. . 2,
Pubs authors, au_email
varChar 20 *. ,
GUI-
, .
( 3;OesJtjn authfirt, in 'put)*' on

aujd
aujname
aujnams
phone
address
city
state

-_

contract
aujsmaill

*'.$.
id (varchar)
varchar
yardw
char
varchar
varchar
chat
char

11
40
20
"12
40
3J
2
"" 5

bit

!l

that

' 75

V
V
V
V
V

. 2.

DTS- SQL Server 2000.


. 3;, DTS Designer , Enterprise Manager SQL Server,
Data Transformation Services
New Package. GUI- DTS Designer
, DTS-, .
(. 4) VBScript-
ActiveX Script Task Task -

, char 75 .
. .

SQL Server 2000 ...

183

. ActiveX Script Task; undefined


- .
IM I rronsole Root\Microsolt- SQL ServersXStH Server tiup\DWlU JAMS (Windows
, J-.*SJ :

V i

! - >^'

.1

-r

:>

....

. --

,_, 11>:,;

^CwscJaPcw
1
| nscwsefr S'5L 3v*n
l|J SQL Server
. |jk DWUIAMS (Windows NT)

Loiil Packs
Meta D-ifs
Mil* Data

'. r'j Security


li-- Ml* Did SrviMi

pp lh DWIlL!AM'DWMJdM5_SER'/R Windows HT IbSQlDEVDEFERRALlWifKjowsNT)

. .
. ActiveX Script Task Properties

Package Objec
'B Tasks Cons

Visual Eass

veX bcri

Author AiokMehtaandDi
ale:
1/2002
aiy Sales Repent using CDOI
'ou should have 5QL Seivw i
Change ihe *Q losing thiee cc
SeeyowDBAcyNetwokAd
MallTransfeiPitiocol |
(5_-"!
d(ire and Text foi Ihel
Const SENDER_EMAiL - ^
ADO Connection Strino to the
itDB^CONNECTSTRINCl

. 4. ActiveX-

184

Microsoft SQL Server

VBScript ,
. -, (.
). , ActiveX Script Task
VBScript. Language (. 4).
,
main, .
, , SQL Server, (
).
, . 5.
BookSales.

. 5.

- ,
Parse,
. ActiveX Script Task.
Go* DTS
Designer.
Execute step. ,
BookSales Enterprise Manager (. 6).
(. 7).
Execute. . .

SQL Server 2000 ...

tn SQL Server " Manager - {

'- 'ill Pal*TrinsfonriatLai Semites


m*>i D-Ki Sen/net
Mat, fsis

. 6.

BookSales

-,/. -.d

. 7.

186

Microsoft SQL Server

BookSales , Schedule Package (. 6)


.
BookSales 11:00 ,
01.01.2002, , , . : SQL Server Agent DTS . BookSales Enterprise Manager
Management SQL Server Agent j Jobs.

VBScript
SourceCode.txt.
, , main, ,
, , .
, :
Const SHTP_SERVER *= "excfiange.afs-link.com"
Const SENOER_E-MAIL =
Book Sales Reporting Service"" <amehta@afs- " &
"link.com>"
Const DB_CONNECT_STRING =
"Provider=SQLOLEDB.1;Data Source=(local); " & _
"Initial Catalog=Pubs;user id = ' s a ' ; p a s s w o r d = ' '

, Const SMTP_SERVER = "exchange.afs-link.com", DNS- SMTP- ( ). ;


.
Const SENDER_E-MAIL = ""Book Sales Reporting Service" <amehta@afslink.com>" . sys1@_.. (Book Sales Reporting) (
, . .
, .
(connection string)
, ,
. ADO :

SQL Server 2000 ...

187

Const DB_CONNECT_STRING = "Provider=SQLOLEDB.1;Data " & _


"Source=(local); Initial Catalog=Pubs;user id = " & " ' s a ' ; p a s s w o r d * ' ' "

, ADO,
.
Provider=SQLOLEDB.l; .
ODBC-,
. SQL Server. , ODBC-
http://msdn.microsoft.com/library/en-us/odbc/htm/dasdkodbcoverview.asp.
Data Source .
local, SQL Server .
IP- , .
Initial Catalog ; Pubs, SQL Server. , user id , a password .
ActiveX- main,
. main .
Process_Daily_Sales,
, ActiveX-, DTSTaskExecResult^Success. Package Object Browser
(. 8).
DTS-. . , main
DTSTaskExecResult_Success, VBScript- .


Process_Daily_Sales .
,
.
HTML- .
( ADO
):

Microsoft SQL Server

4.1
]S .*rs Con^anl

V^.iB^.Adiv^-.rn

Da^a Punp Corijlani


S TSTiansformStaLOK
DTSTiansrojmSialJnlo

DTSTransiufmSlaLSkpFelch
DTSTfans-tormStaLSkiplnsert
IB DTSTransformSlaLDeslDalaNoSet
D"STramformStat..Eiror
S! DTSTfanstofmStat_EriotSkpFlcw
DISTransiomiS(aL^ceptionRow
33 DTSTtansiQriTi)fll_AbcrtPump
SI DTSTrar-islorniStaLNoMoreRom
^ala Driver. Query Constant
!

rfTCTrs^,?fjMl^Ck->

DTSriwisloimSfaUJpditeQuery
-jSl DTSTransrermStaLDfcleteQuefy
- JSJ DTSTFertsforrffiaUJserQuwji
]
(-..- Active* Script Cnrtstant
51 DTSTa;kFse-?Result_SuccsES
!
-[ DTSTaskEKseRefull Failure
\3 Steps Coreienl
--X DTSSiepEKecS(at_Compteted
jf DTSSteptHecSsatjnashve
!
OTSSiepExecSiatJnProgrew
JT . . *e,ik.^..c5rai_ /a. ng
jf OTSStepSctiplResuH^ExeculeTask
:
A l~
.-ih !V*
'
V
LitoM

. 8.

'Chaige ihe lol^^ing three !


l
SeeyoutDBAcjfNetv*iokAdnJ
i'iunpte Mail Transfer Protocol
[Const 5MTP_SERVER = '-:- :jtmail Address and ( for theT
Consl SENDER_EMAIL = J
'ADO Conn&etkin Stnna to thel
Coml D8_mNNECT_STRINl

' r-'-j-'llj .^r,r

AulHiot: Atok Meht3 and Dad


Oale
1 /2002
IJaijji Sales Report using CDG.J|
You should have SQL Serves |is

51! J

Name: Main
Aur.hoi: Atak Mehta and Oal1
'Dale'
1 /2002
Purpose. Calbihe PioceM_Di-

MictbnK)ain{l
Call P[ocess_Daily_Sa|

End Function
'
^
'Name:
Fundicin Serid^iii.J"
'Authoi: A!ck Mehta and ,'Daie
1/1.^2002
'Puipoje IJsssCDD to spni
Return
Noihing

Dim rstAuthors
Dim rstSales
Dim Todays_Date

Pubs , 14.09.1994.
Pubs.
14.09.1994
:
"Todays_Date =
& DateQ &
Todays_Date = "'9/14/1994'"

SQL Server 2000 ...

189

, , , :
strAu_Sales = "Select Distinct Authors.* from " &
"Authors,Sales, TitleAuthor
Where " &.
"TitleAuthor.au_id = Authors,au_id and " &
"TitleAuthor.Title_id = Sales.Title.id and " &
"Sales.ord_date = " & Todays_Date

ADO,
SQL:
Set rstAuthors = ExecuteSQL(strAu^Sales)

, rstAuthors
, , :
If Not (rstAuthors.Eof and rstAuthors.Bof ) Then
While Not rstAuthors.Eof
: , ,
, , . Stores, Sales, TitleAuthors Titles. ,
* :
strAu_Sales = "SELECT distinct stores.stor_name as [Store Name], " &
"sales.ord^num as [Order Number], sales.qty as [Quantity], " &
"sales.payterms as [Pay Terms], Titles.Title FROH Stores, Sales, " & _
"TitleAuthor, Titles " & "Where TitleAuthor.au_id = '" & _
rstAuthors("au_id") & "' and Sales.ord_date = " & Todays_Date " &
"and Sales.Title^id = Titles.Title_id and sales.stor_id = " & _
"stores.stor^id "

ADO,
Execute SQL:
Set rstSales=ExecuteSQL(strAu_Sales)

.
HTML- <br>, HTML:
strTable = rstAuthors("au_fname") & " " 4
rstAuthors{"au_lname") & "<br>" & rstAuthorsC'Address")
& "<br>" & rstAuthors("city") & ", " &
rstAuthors("state") & " " & rstAuthors("Zip")

, SourceCode.txt.
. .

190

Microsoft SQL Server

. HTML-, . Format Recordset


rstSales HTML-:
strTable = strTable & FormatRecorcfset(rstSales)
, , HTML:
Call send_e-mail("Book Sales Report For: " & Todays_Date,
rstAuthors("au_email"), strTable)
:
rstAuthors.movenext
Mend
ExecuteSQL .
,
SQL ( ). ADO-:
Set myConn = CreateObject("ADODB,Connection")
ADO:
set myRecordset = CreateObject("ADODB.Recordset")
,
DB_CONNECT_STRING:
myConn.Open = DB_CONNECT_STRING

, :
myRecordset.Open mySQLCmdText, myConn
, , :
Set ExecuteSQL = myHecordset
ADO,
.
FormatRecordset
ADO HTML- ( ).
, . .

SQL Server 2000 ...

191

; , . HTML-.
HTML- .
:
strTable = <table border=1 width=500>
,
<tr>:
rstTable.MoveFirst
strTable = strTable & "<tr>"

<td>, :
For Index = 0 rstTable.Fields.Count - 1
strTable = strTable & "<td bgcolor=blue nowrap>" &
"<font color='white'>"
strTable = strTable & rstTable.Fields.Item(Index).Name
strTable = strTable & "</font></td>"
Next
<tr>
:
strTable = strTable & "</tr>"
, HTML- ,
, . HTML- <tr> <td>:
While (Not rstTable.EOF)
strTable = strTable & "<tr>"
For Index = 0 To rstTable.Fields.Count - 1
strTable = strTable & "<td>"
strTable = strTable &
rstTableCrstTable.Fields.Item(Index).Name).Value
strTable = strTable & "<br>"
strTable = strTable & "</td>"
Next
strTable = strTable & "</tr>"
rstTable.MoveNext
Wend
. :

192

Microsoft SQL Server

strTable = strTable & "</table>"


FonnatRecordset = strTable


Send_Email. ,
SMTP_SERVER SENDER_EMAIL, Microsoft Collaboration Data Objects (CDO 2.0) CDOSYS.DLL. CDO
Windows 2000, SMTP NNTP Windows 2000 Server.
API Web, Windows 2000 Server.
Send _Email : subject, rcpt msgHTML.
, , HTML.
Send_Email : cdoSendUsingPickup (, : SMTP) cdoSendUsingPort (, ).
SMTP,
cdoSendUsingPickup. (
Outlook Express) cdoSendUsingPort (default account). cdoSendUsingPickup.
Send_Email - Message Configuration:
set iMsg = CreateObjectC'CDO.Message")
set iConf = CreateObjectC'CDO.Configuration")

Configuration .
:
Set Fids = iConf.Fields
, CDO, http://schemas.microsoft.com/
cdo/configuration/. (SendUsing,
SMTP_SERVER TimeOut) Configuration:
With Fids
.Item("http://schemas.microsoft.com/cdo/configtjration/sendusLng") =

SQL Server 2000 ...

193

cdoSendUsingPickup
. Item( "http://schenias.microsoft.coin/cdo/configuration/snitpserve ") =
SHTP.SERVER
,Item("http://schemas.microsoft.com/cdo/configuration/ " & _
"smtpconnectiontimeout") = 10
.Update
End With

, , ,
:
With iMsg
Set .Configuration = iConf
.To = rcpt
.From = SENDER_EMAIL

.Subject = subject
.HTMLBody = msgHTML

.Send
End With

, SQL Server 2000, VBScript, ADO, CDO DTS-.


, . ,
, . ,
VBScript- DTS-. , , : , .
: http://download.microsoft.com/download/msdnmagazine/code/Aug02/WXP/EN-US/
VBScriptAndSQLServer2000.exe.
(Alok Mehta) - American Financial Systems Inc. (AFS) (, ).
amehta@afs-link.com.
(Daniel Williams) -
Deferral.com ( AFS), ,
Deferral.com.
dwilliams@afs-link.com.

7-5947



SQL Server*

SQL Server
,
- DM0 {Distributed Management
Objects). SQL-DMO SQL Server 7.0 SQL Server 2000,
SQL-DMO.
Databases JobServer .
, Registry,
Configuration Database
,
, , (scripts) T-SQL
.

Microsoft SQL Server


( , . .),
T-SQL,
. DMO (Distributed Management Objects) . , , .
SQL-DMO 150 , SQL Server 7.0 SQL Server 2000.

MSDN Magazine. 2001. 5 (). . .

SQL Server

(dual interfaces), , Visual Basic, C++, VBScript, JScript, Windows Script Host (WSH)
ASP-. , ,
, ,
T-SQL,
.
Visual Basic, , , .

SQL-DMO
, DMO SQLDMO.DLL. SQLDMO.RLL . SQL Server 7.0 RLL-
\Mssql7\Binn\Resources'vrxYA- ( , ),
(, 1033 U.S. English), SQL Server 2000
C:\Program Files\Microsoft SQL Server\80\Tools\
Binn\Resources\;u:xr. SQL Server, DMO
. , SQLDMO.SQL ( T-SQL) , DMO.
\Mssql7\lnstall ( SQL Server
7.0) Microsoft SQL Server\MSSQL$w.w,a cepeepa\lnsta\\ ( SQL
Server 2000), , . DMO ,
. REDIST.TXT
- SQL Server SQL-DMO.
SQLDMO.DLL SQLSVC.DLL ( ), ODBC32.DLL, ODBC- SQL Server. ODBC-
3.70 ( SQL Server 7.0).
, SQL-DMO
ODBC.
SQLDMO.DLL ,
Client Network Utility, .

SQL-DMO
DMO, ;

196

Microsoft SQL Server

SQL Server Enterprise Manager. DMO-


Application; ServerGroup,
SQLServer. . 1.
SQLServer : Databases ( , , , . .), JobServer ( , ) Replication (
, . .).
Database
JobServer.

BackupDeuices

Languages

RemoteServers

Re in ale Logins

Server Roles

. 1.

Application

SQL Server

197

SQL-DMO
SQL-DMO : (, Database, Table Column), (, Databases, Tables Columns) . -
,
. , . , (combobox) :
Dim sqlApp As New SQLDMO.Application
Dim NL As SQLDMO.NameList
Set NL = sqlApp.ListAvailableSQLServers
For index = 1 To NL.Count
cboServers.Addltem NL.Item(index)
Next

SQL Server 7.0 ,


Windows NT, Named Pipes . (
NetBIOS,
. :
SQL Server Windows 9.r ,
Named Pipes.) SQL Server 2000
NetBIOS
UDP, ,
TCP/IP. , , .
, SQLServer .


SQL Server
SQLServer,
LoginTimeout Connect:
Dim SQLServer As New SQLDMO.SQLServer
SQLServer.LoginTimeout = 10
If UseNTAuthentication Then
1
Windows NT
SQLServer.LoginSecure = True
SQLServer.Connect strServer
Else

98

Microsoft SQL Server

1
SQL Server
SQLServer.Connect strServer, strlogin, strPassword
End If

, Windows NT SQL Server.


strServer , a strLogin
strPassword SQL Server. , ,
.
ADO- Connection SQLServer
, ,
, , . SQL Server ( SQLServer.Disconnect),
SQL-DMO ( SQL
Server 2000
). , DMO , :
set oDatabase = Nothing

,
SQL-DMO ( ,
, , , ).
, SQLServer
Microsoft SQL Server ,
(. 2). Visual
Basic (stoplite), , ,
http://msdn.microsott.com/msdnmag/code01.asp . SQLServer. Status.
SQLServer MSSQLServer. SQLServerAgent,
, JobServer:
SQLSe rver.JobSe rve .Start
SQLSe rver.JobSe rve r.Stop

SQL Server
Registry:

SQL Server

SQLServer.Registry.AutostartServer = True
SQLServer.Registry.AutostartDTC = True

. 2. ,
Public Sub SQLServiceManager{NewState as Int)
Dim oSQLServer As SQLDMO.SQLServer
Set oSQLServer = New SQLServer
oSQLServer.Name = "(local)"
On Error GoTo errHandler

Select Case Index


Case 1 '
If oSQLServer.Status = SQLDHQSvc_Stopped Then
oSQLServer. Start False
Else
HsgBox "Cannot start server, server is either"
1 "running or paused' vbOKOnly,
"SQL Server Service Manager"
End If
Case 2 ' /-
If oSQLServer.Status = SQLDMQSvc.Paused Then
oSQLServer.Continue
Elself oSQLServer.Status = SQLDMOSvc_Bunnjng Then
oSQLServer,Pause
Else
HsgBox "Cannot pause a server which is running",
& vbOKOnly, "SQL Server Service Manager"
End If
Case 3 '
If oSQLServer.Status = SQLDMOSvc_Running Then
oSQLServer.Stop
' oSQLServer.Shutdown TSQL- "shutdown"
' (SCM)
Else
HsgBox "Cannot stop a server which is not running",
vbOKOnly, "SQt Server Service Manager"
End If
End Select
Exit Sub

errHandler:
HsgBox Err.Number & " " & Err.Description & " <" & _
Err.Source & " " & Err.LastDUError & ")", _
vbQKOnly, "SQL Server Service Manager"
nd Sub

199

200

Microsoft SQL Server

, SQLAgent Windows 98, Windows 98 SE


Windows Me, Windows NT
(Service Control Manager,
SCM). (SQL Server 2000 Windows 95.) Windows 9x ,

Registry Configuration
Registry , , ,
master . , SQL
Server.
Configuration ConfigValue.
40 ,
sp_configure. , - . ,
:
Dim cv As SOLDMO.ConfigValue
With SQLServer.Configuration
.ShowAdvancedOptions = True

For Each cv In .ConfigValues


Print cv.Name, cv.RunningValue, cv.CurrentValue
Next
End With

,
ReconfigureCurrentValues ReconfigureWithOverride:
'
With SQLServer.Configuration
.ConfigValuesC'allow updates").CurrentValue = 1
.ReconfigureWithOverride
End With

QueryResults
. SQLServer
10 ,
, , Windows NT
,
. Enunuxr QueryResults.

201

SQL Server

Query Results ,
,
GetColumnString, GetColumnLong Get Column Double. ,
ColumnType
GetColummxt.
QueryResults, GetRangeString.
, Query Analyzer
(, sp_\vho sp_locks ).

Split Visual Basic VBScript.
. 3 ,
QueryResults ADO- Recordset.
Recordset , , ,
, Recordset
DataGrid (. 4).
- 3.

QueryResults Recordset

Function QueryResultToRecordset(qres As SQLDHQ.QueryResylts) _


A3 ADQDS.Recordset
. Dim qresString As String
DliB rs As New AOODB. Recordset
Dim rowsO, As String, cols() As String
Dim rowlndex As Long, callndex As Long
*
' , ;
' /,
" CRLF
qresString = qres.GetRangeString(t , , , (2), Chr<1))
' .
row&Q = SplitCqresString, Dhr<2)}
cols() * Split(rQws(0), Ghr(1
1

Recordset
For collnitex = 0 To UBoijnd(cols)
rs.Fields.Append RTrim$(cols(colIndex)), adVarCtiar,
cfres.ColurflnMaxLength(colIndex + 1)
Next

. . .

Microsoft SQL Server

. . QuervResults ADO-... ()
Recordset
rs.Open
, rows(1), -,

For rowlntiex = 2 UBound(rows)
'
colsC) = Split(rows(rowlndex), Chr(1))
'
rs.AddNew
For collndex = 0 To UBound{cols)
rs.Fields(collndex) - RTrim$(cols(colIndex))
Next
rs.Update
Next
" Recordset
Set QueryResultToflecordset = rs
End Function

. 4.

QueryResults

SQLServer ,
QueryResults. SQL-DMO 80
Enumjcxu:,
, , (replication subscriptions),
. ,
, . ,
, .

Database
, ,
DMO-SQL. , -

SQL Server

, , ,
, ,
(. 5).

DataBaseRoles

FullTeitCattlogs

StoredProcedures
SystemDatalypes

UserDefinedDataTypes

FileGroups

. 5. Database

,
. , . 6 (
) Pubs, SQL Server.
SystemObject, True ( ) False (
),
, :
1


' Pubs T-SQL
Dim sp As SQLDMO.StoredProcedure
For Each sp In db.StoredProcedures

204

Microsoft SQL Server

If Not sp.SystemObject Then


Print "- PROCEDURE " & sp.Name
Print sp.Text
End If
Next

. 6. Pubs

' , SQLServer
Dim db As SQLDMO.Database
Dins tbl As SQLDMO. Table
Dim col As SQLOMQ.Column
Set db - SQLServer.Databases("pubs")
For Each tbl In db.Tables
PriRt "TA8L " 4 tbl.Nase
For Each col In tbl.Columns
Print "
" 8 col.Name
fiext
Next

-SQL
SQL-DMO, Database, Table, Index, Key, Job,
Alert, Trigger, User, Rule, Check , Script, -SQL,
. , . , ,
CREATE DATABASE
sp_option,
' -SQL Pubs
Dim pubsDB As SQLDMO.Database

Set pubsDB = SQLServer.Databases("pubs")


Print pubsDB.Script
,
Script Database,
, . Script
- , . , ,
,
(constraints), (. 7).
SQL-DMO (batch)
SQL- .
Visual Basic -

SQL Server

205

Execute Immediate 1;, . T-SQL , . ,



(, 8).
, 7. T-SQL
' T-SQL
' Pubs
Dim tbl As SQLDHQ.Table
Dim allParams As Long, ! As String
'
allParams = SOLDMQScript_Default Or SQLDMGScript.lndexes
Or SQLOHOScript_DRI_AllConstraints Or _
SGLDMOSerlptJYiQgers Or SQLDMOScript_DflI_ForeignKeys
For Each tbl In pubsDB.Tables
sql * sql & tbl.Script(allParaiBS)
Next

. 8., ,

' ,
' NewName Script,
1
,
Din oSQLServer As SOLDHO.SQLServer
Set oSOLServer * Hew SQLDMO.SQLServer.
oSQLServer.LoginSecure * True
,oSQLServer.Connect "(local)"
Dim oTabla As SQLDMO.Table
Set oTable = oSQLServer.Databases("pubs"}.Table8C"sales")
Dim sqlText As String
Dim ScriptOptionsI As SQLDMO.SQLDMQ_SCRIPT_TYPE
Dim ScriptDptions2 As SQLDMQ.SQLBM(LSCRIPT2J"YP
ScriptOptionsI = SQLDMOScript.Default * SQLDHOScriptJJwnerQualify
ScriptOptions2 = SULOMOScript2_Default
sqlText = oTa61e.Script(ScriptQptiotis1, , "New Sales", ScriptOptions2)
Pubs,
" (resolve) sales ,

aw. . .

206

Microsoft SQL Server

. 8. ... ()
' - sqlText "use pubs"
oSQLServer.Databases("pubs").Exeeutelmmediate sqlText
'
" ,
' - oSQLServer,Exeeutelmmediate sqlText
oSQLServer.Disconnect
Set oSQLServer = Nothing


(jobs) , SQL-DMO.
, , SQL Server
,
. JobServer DMO (. 9) ,
CI
,
.

JobServer,
; Job JobStep
JobSchedule. SQL Server Enterprise Manager, .
, ,
, .
Job. Name Description, Jobs JobServer:
Job
Dim SQLJob As New SQLDMO.Job
SQLJob.Name = "Northwind Backup"
SQLJob.Description = "Check and Backup Northwind"
1
Jobs
SQLServer.JobServer.Jobs.Add SQLJob

(job step) Enterprise Manager


JobStep SQL-DMO. -

* SQL Server

: T-SQL, Windows Script


. Subsystem ,

AlerlCategories

JabCategories

JabSchedules

JobSteps
QperatorCategories

Operators
TargetSermGroups
MemberServers
TargetServers

. 9.

JobServer

, , ,
DBCC CHECKDB Northwind:
Dim aJobStep As SQLDMO.JobStep
Set aJobStep = New SQLDHO.JobStep
aJobStep.Name = "Step 1: Check Northwind"
aJobStep.StepId = 1
aJobStep.Subsystem = "TSQL"
aJobStep.DatabaseName = "Northwind"
aJobStep.Command = "DBCC CHECKDB ('Northwind', REPAIR.FAST)"
aJobStep.OutputFileName = "c:\temp\job1.log"

208

Microsoft SQL Server

OutputFileName , .
:
( Enterprise Manager ). , SQL-DMO , Enterprise Manager. ,
,
.
,
, OnSuccessAction
II Failure Action - : SQLDMOJobStepAction_QuitWithSuccess, SQLDMOJobStepAction_QuitWithFailure, SQLDMOJobStepAction_GotoNextStep SQLDMOJobStepAction_GotoStep.
, DBCC CHECKDB ,
() , :
aJobStep.OnSuccessAction = SQLDMOJobStepAction_GotoNextStep
aJobStep.OnFailureAction = SQLDMOJobStepAction_QuitWithFailure
,
Stepld OnSuccessStep
OnFailureStep:
DBCC CHECKDB , 3-
aJobStep.OnFailureStep = 3
aJobStep.OnFailureAction = SQLDKOJobStepAction_GotoStep

, JobStep JobSteps Job:


SQLJob.JobSteps.Add aJobStep

. ,
. 10, DBCC CHECKDB ,
, ActiveX-,
. ActiveX- SubSystem JobStep ActiveScripting, DatabaseName (VBScript JScript), Command . ( , Subsystem CmdExec. a
Command . ,

SQL Server

209

, , Command
IISRESET START.)
. 10. ,

* - Job
Dim SQLJob As New SQLDMO.Job
SQUob.Naaie - "Korthwind Saekup"
SQLJob.Description = "Check and Backup Northwind"
' Jobs
SQLServer.JobServer. Jobs. Add SQUob
' - :
Din aJobStep As SQLDMO.JobStep

Set aJobStep = New SQLDMO.JobStep


aJobStep.Naiae = "Step 1: Check NorthwiiKl"
aJobStep.StepId = 1
aJobStep,Subsystem = "TSQi"
aJobStep,BatabaseName = "Northwind"
aJobStep.Comiiarwt = "BBCC CHECKOB {'Northwlnd', REPAIR_FAST)"
aJobStep.OutpytFileHaHie *= "c:\temp\job1.tinp"
' DBCC CttECKDB , 3-
aJobStep.OnFailureStep = 3
aJotjStep.OnFailureAetion = SQLDMQjobStepAction_QotoStep
SQLJob.JobSteps.Add aJobStep
' - : .
1
JobStep
Set aJobStep = New SQLDHQ.JobStep
1
,
bakdir = SQLServer.flegistry.SQLDataPath & "\backup"
aJohStep,Kerne * "Step 2: Backup Northwlnd"
aJobStep.StepId * 2

aJooStep.Subsystem = "TSQI"

aJobStep.DatabaseHaiue - "Northwind"
aJobStep.Command = "BACKUP DATABASE [Northwind] TO DISK = '" _
bakdir & "\Korthwlnd.bak1 "
' ; ,
' 1-
.aJobStep.GutpytFlleNaroe ^ "c:\terBp\job2.tmp"
'
ajobStep.<toSiUceesaActiQn = SQLDHOJobStepActionjjotoNextStep
aJobStep.QnFailureAction = SQLDMOJobStepAction_GotHextStep
SQLJob.JobSteps.Add aJobStep
- :
Set aJobStep = New SQLDMO.JobStep

. , .

210

Microsoft SQL Server

. 10.

, ..,

aJobStep.Name - "Gather output and delete tap files"


JobStep.StepID 3
JobStep.Subsystem = "AetiveScrtpting"
' DatabaseName
'
avIobStep.DatabasefiaBe = "VBScript"
'
! Script As String
Script = "Did fso* stepld, file, text, filename" & vbCrlf & _
"Set fso - CreateObject(""Scrlptlne-PibSystemObjecf'")" _
4 vbCrlf & _
"* gather text front all temporary files and delete them '" _
& vbCftf 4 _
"For stepIO = 1 To 2" & vbCrLf &
filemne - ""c:\temp\Job"" & CStr(stepID) & "".trap"""
4 vbCrlf & _
Set file = fsQ.OpenTextFileCfilename, 1, True, True)"
& vbCrlf & _

text * text 4 file.ReadAll" & vbGrLf & _


file.Close" 4 vbCrlf & _
fso.DeleteFiie filenaffle" & vbCrtf & _
"Next" & vbGrtf S _
"Set file * fsD.CreateTextFUeC""" & txtFile & """, True)" _
& VbCrLf
' - , Jo
' Nothing
Script = Script 4
"file.WriteLine ""Output from '" & SQLOot.Nflffle
4 "' job at "" S )" 4 vbCrLf & _
"file.Wrltellra StrlRf(40, ""--")" & vbGrlf & _
"file.Write text" 4 vbCrLf 4 _
"file,Close" 4 vbGrlf & vbCrtf &
"Set fso * Nothing" 4 vbCrLf 4 _
"Set file Nothing" 4 vbCrLf
* Command JobStep
aJebStep.Coeraand ;= Script
'
aJobStep.GflSuccessActlon = SQiOMOJobStepActioR_QuitWithSuccess
adobStep.OnFailActien * SQlD)JobStepAction_QuitWithFailMre
SQUeb.JebSteps.Add aJobStep
'- .
' ,
SQUofe.StartStepIO 1
' SQL-
SQLJob.ApplyloTargetServer "(local)"

SQL Server

211

Job SQLServer
Invoke Start. ,
Start ,
.
. JobSchedule, JobSchedules Job. Schedule JobSchedule
, (. 11). , ,
. , ActiveStartDate ActiveEndDate Schedule Long , ActiveStartTime ActiveEndTime
Long .
. 11.

' ,
Dim SQLJob As SQLDMO.Jotj
Set SQLJob = SQLServer.JobServer.Jobs"Horthwind Backup")
'; JobSchedule
Dim SQLSchedule As New SQLBHQ.JobSchedule
SQLSchedule.Name = "Daily &ackup"
SQLSchedule.Schedule.FrequeneyType = SGieKOFreo_Dally
SQLSchedulS.Schedule.Frequencylnterval = 1
* - 18 2000 , 23:55
SQLSchedule.Schedule,ActiveStartDate = 20001018
SOLSchedyle.Schedule.ActiveStartTiffleOfBay 2355
'
' ( )
SQLSehedule.Schedule.ActiveEndDate SQLDMO.NOEHDDATE
SQtSchedule. Schedule, Active En dTimeOf Day *= SQLDMOJIQENOTIHE
Job
SQLJob.BeginAlter .
SSLJob. JobSchedules.Add SQLSchedule
SQUob.DoAlter

, , :

Microsoft SQL Server

, (. 12). (, Job, , JobScheduIe , . ,


UI, .

. 12.
SQL-DMO,
.
DMO ,
. , ,

.
(Francesco Balena) Visual Basic
Journal (), Visual Basic
Programmer's Journal, Programming Visual Basic 6.0 (Microsoft
Press, 1999). .
http://www.vb2themax.com.



Web*


,

.
, SQL Server
XML .
, XML-. XML-,
XSL-,
HTML. , .
SQL Server 7.0 SQL Server 2000.

, , n- Windows- .
Web- Microsoft IIS (Internet Information Services)
ASP, - (middletier) , Visual Basic,
Microsoft SQL Server.
, ,
. * MSDN Magazine. 2001. 8 (). . .

214

Microsoft SQL Server

,
, .

. (
) .
- , ,
. XML SQL Server. , , XML-.
XML ,
RAD (Rapid Application
Development) . . XML-, .
, , .
MSDN
Magazine http://msdn.microsoft.com/ msdnmag/codeOl.asp .


, XML-, XSL XML HTML (
, ). , XML-
. XML. XML ,
(parser) MSXML.
, XML- Visual Basic. , , . ,
XML-

Web

215

. , XML-
Visual Basic -, , , . ,
XML ,
X ML-.
. XML-
XML , XML
( MSXML)
. , (Patrick Escarcega) XML Wrapper Template: Transform
XML Documents into Visual Basic Classes (http://msdn.microsoft.com/
msdnmag/issues/01/Ol/xmlwrap/xmlwrap.asp),
MSDN Magazine 2001 .
. XML- .
,
-. , , , - .
XML-,
, ,
. , - (
) ,
. , .

XML- , , ,
XML? ,
,
, XML? -
! . . 1. .
ASP- ASP-
-, .

Microsoft SQL Server

216

aotryni

s KpSH.BHI
[
$*1
iSKSener

. 1.

XML

-, XML-. XML HTML HTML US- Response.


- , . , ; ( ).
, XML XML.
. ,
XML,
. , .
.
, ,
, . ,
,
. ,
.

Web-
, , Web, . Northwind, SQL Server. , .
Web- ,
login.asp (. 2). Employee ID (1-9)
Log In. Employee Detail ( -

Web

217

),
, (. 3).
http://myserver/

Microsoft Internet KMptoner


Histor

Address'!

http;//rnyserver/lagin, asp

Enter Your Employee ID To Log In


(fD's 1 Through 9 are Valid)

. 2.

http://niyserver/empdetai
Edit

Employee Information:
Ms. Nancy Davolio
Sales ^Representative
Create New Order
Here is a list
Order ID
11077;,
071

of the orderer? for which you are the sales representative.


Customer Name
Shipped Date
Hattiesnake Canyon Grocery
LILA-Supennercado

\ 10 67
ji|M
11039

Drachenblut Delikatessen
Save-a-bt Markets '--:-:!
LINO-Delicateses
Supremes delices
Bottom-Dollar Markets

1 1 027

. .

05/069
05/04/199

Total
1255^
S-484.50
.00

218

Microsoft SQL Server

Employee Detail XML- SQL Server XSL- XML- HTML. XSL , , .


, SQL Server XML .

ASP-
, ASP .
. , . , login.asp (employee ID). empdetail.asp.
RAD- ,
.
empdetail.asp:
' EmployeeDetail,
' . ,
' .
Set Writer = Server. CreateObjectC'COMASP.cWriter")
Response. Write(Writer. EmployeeDetail( ) )
'
Set Writer = Nothing

Empdetail.asp cWriter ( ) EmployeeDetail . EmployeeDetail HTML, .


ASP- - , , . 1.
. 1. ASP-,

login.asp

.
, .

. . .

Web

. 1. ASP-,

219

()

empdetail.asp

EmployeeDetail cWriter
Response.Write.
, , .

orddetail.asp

OrderDetail cWriter
Response.Write.
, .

neworder.asp

CreateOrder cWriter
Response.Write.
, .
, .

additem.asp

AddOrderltem cWriter
Response.Write.
, ,
.


COMASP.vbp Visual
Basic. spdaui.dll.
, cWriter, ASP-.
, ASP-
. ASP-
(ASP scripting context), IIS- Application, Request, Response, Server Session.
, , ASP ( , Visual Basic, VBScript).
ASP- OnStartPage . ASP- , IIS . OnStartPage
. , Visual Basic Microsoft Active Server Pages Object Library (asp.dll).
, cWriter, . 2. EmployeeDetail, VBScript-, empdetail.asp.
- MiddleTier.cEmployees GetDetail
, , . , GetDetail, XML-. .

Microsoft SQL Server

220
Set oEmployees = New MidflleTler.cEmployees
strEmployeeDetailXHL = oEmployees.GetDetail(lEmpID)

. 2. cWriter

AddOrderltcm

additem.asp

,
( ,
),
.

CreateOrder

neworder.asp

,
, .
,
,
orderdetail.asp.

EmployeeDetail
empdetail.asp

EmployeeLogin
login.asp

,
, .

.
, , ,


(empdetail.asp).

OnStartPage

ASP,
, - .
IIS,

OrderDetail

orddetail.asp

, ,
.

XML DOM- MSXML


XSL, empdetail.xsl.
, EmployeeDetail:
Set oXML = New MSXHL.DOMDocument
Set oXSL = New MSXML.DONDocument
oXHL.loadXML strEmployeeDetailXML
oXSL.Load App.Path & "\xsl\empdetail.xsl"
EmployeeDetail = oXHL.transfonnNode(oXSL)
HTML-,
EmployeeDetail
.

Web

221

-
- MiddleTier.vbp, Visual Basic spdamid.dll.
: cEmployees cOrders ( ). , GetDetail cEmployees, .
, , ,
.
GetDetail cAdapter DataAccessAdapter ( ),
CallSP;
Set oAdapter = New DataAccesssAdapter.cAdapter
with oAdapter
.SPName = "Employeejjet.Detail"
.Parameters.Item("EmployeeID").Value = lEmployeelD
strXML = .CallSP(daRecords)
End With

,
, . CallSP XML-,
, ,
, , . XML -,
XML
HTML.


,
( ).

XML. DataAccessAdapter.vbp, Visual
Basic spdaad.dll. : cAdapter,
cParameter, cParameters lExpose.
cAdapter ,
. , , CallSP. cAdapter
SPName Parameters.

Microsoft SQL Server

222

SPNarae . , . ,
. , ,
.
SPNanie ;
( ) , .
Parameters cAdapter, .
Parameters ( )
cParameters. .
cAdapter , CallSP:
Public Function CallSP(ReturnType As ReturnDataEnum) As String

ReturnType ReturnDataEnum. , . ReturnDataEnum :


Public Enum ReturnDataEnum
daParameters ==
daRecords = 1
End Enum

daParameters ,
, daRecords
. ,
.
cParameter ,
. cParameter
Parameters cAdapter. Parameters . , EmployeelD:
oAdapter. Parameters. Item("EntployeeID"). Value = lEmployeelD

, , SPName cAdapter,
.
cParameters

cParameter.

Web

223

lExpose . lExpose . cAdapter.


CallSP cAdapter
XML-
. ADO.
, XML
. , ,
XML,
, XML, XML-.
, , XML.
CallSP. (
, lExpose.)
1

:
strSPName ( ),
m_objParmCol ( cParameters cAdapter),
ReturnType ( ReturnDataEnum)

Set oAccessor = New DataAccess.cAccessor


Set oXML = New MSXML.DOMDocuinent
strlnvokingXML = m_objParmCol.ParametersXML(strSPName)
strResultXHL = oAccessor.GetDataXML(strInvokingXML, ReturnType)

CallSP ParameterXML cParameters,


( ) XML-
. ( .)
XML- GetDataXML cAccessor .


.
XML-, , ,
XML-. DataAccess.vbp,
Visual Basic spda.dll.
, cAccessor, : GetDataXML ParameterXML.

224

Microsoft SQl Server

GetDataXML
. GetDataXML :
Public Function GetDataXML(ByVal SPXMLState As String, ReturnType _
As ReturnTypeEnum) As String

SPXMLState XML-, ,
(
). XML- XML-
. ReturnType ,
. ReturnTypeEnum :
Public Enum ReturnTypeEnum
daParameters ==
daRecords = 1
End Enum

daParameters ,
. daRecords ,
. , ReturnDataEnum,
.
, GetDataXML, XML-,
. XML- .
ParameterXML SPName,
XML- .
:
Public Function ParameterXNL(6yVal StoredProcedureName As String) _
As String

, StoredProcedureName,
. XML-, XML , ,
. XML- .


, , .
, , ,

Web

,
, XML .
,
XML-.
, XML,
. , ADO , :
, ,
. , Web-, , , .
, ,
.
, SELECT , . 4. ,
, :
' , - Dim Set cmd
'
Set rs = cmd.Execute()
Do While Not (rs Is Nothing)

- rs...

'
Set rs = rs.NextRecordset
Loop

, ,
While NcxtRecordset
XML-.

(outermost) XML.
. XML-, , . , , Emplo-5947

226

Microsoft SQL Server

yee_GetDetail, . 4. (
) XML (. 5). (
<Order>. ,)
, . 4 SELECT.
.
SELECT:
SELECT "EnployeeDetail" AS DataSet
. 4. Etipioyee.J3eiDet.ail
CREATE PROCEDURE EfflployeejzetDetail
@EfliployeIO AS INT
AS

-- , ,
DOM-
SELECT "EmployeeDetail" AS OataSet

SELECT "Employees" AS NextResultset, "Eaiployee" AS RecordType
-- , DOM ,
SELECT EfoployeelD, LastName, FirstKams, Title, TitleOfCourtesy
FROM Employees
WHERE EmployeelD = EmployeeZD
-- , ,
SELECT "Orders" AS HextResultset, "Order" AS SecordType

SELECT ord.QrderlO, ord-CustoffierlD, cus.CompanyNaeie,
CGNVERT(NVARCHAR, ord.OrderDate, 101} AS OrderDate,
CQNVERT(WARCHAR, orrf.ShippedDate, 101) AS ShippedOate,
Total = CAST(CAST{SU(det,Quantity (1 - det.Discount) *
det.UnitPrice) AS DECIMAL*10,2)> AS NVARCHA8)
FROM Orders ord JOIN Customers cus
ON cus.CustomerlD a ord.CustoirerlO
JOIN [Order Details] det
ON det.OrderlD = ord.OrderlD
ord.EmployeelD = ^EmployeelD
GROUP BY ord.OrderlD, ord.OrderlO, ord.CustoinerlO, cu
SftlppedDate, orcf.OrderOate
0ER BY ord.OrderlD DESC

Web

22?

. 5. Employee_GetDetail
<?xral version="1.G"?>
<EfflployeeDetail xmlns; dt="urn: schereas-nticrosoft-coni-r datatypes" >
<18>
<raployee>
<EmployeeIO dt:dt=*"i4">K/EBiployeeID>
; <LastName dt:dt="strirrg">DavQllo</LastName>
<fi rstName dt : dt= "string ">Narvcy</Fi rstName>
!
<Title dt;dt="string">Sales Representative</TLtle>
<TitleOf Courtesy dt:dt="string">Ms.</TitleOfCourtesy>
</Employee>
</Employees>
<0rders>
dt;dt*"i4">11077</OrdefIO>
dt: dt="string">RATTC</CLJStomerIO>
,<CoiapanyNaaie dt:dt="string">Rattlesr>ake
Canyon Grocery</CompanyName>
<0rder0ate dt:dt="string">05/06/199a</0rderpate>
<Shipped8ate dt:dt="string"x/ShippedDate>
<Total dt;dt="string">1255.72</Total>
</Qrder>
<0rder>
<OrcferID dt:dt="i4">n07K/OrderIB>
<CustOBier:D (Jt:dt=1'strin9">LIUS</CiJstoinerII)>
<CompanyName dt:dt="string">LILA-SiJpermerca(Jo</CoiBpanytJarne>
<OrderDate dt:at="string">05/05/1998</OrderDate>
<ShippedDate dt:dt="string"></ShippedDate>
<Total cft:dt="string">484.50<Aotal>
</Srder>
</Orders>
</ Etnp loyeeDet ail>

, DataSet. EmployeeDctail. DataSet.


XML (. 5).
,
SELECT:
SELECT "Employees" AS NextResultset, "Employee" AS RecordType
SELECT EmployeelD, LastName, FirstName, Title, TitleOfCourtesy
FROM Employees
WHEHE EmployeelD = @EmployeeID

, XML.
: NextResultSet RecordType. NextResultSet ( Employees)
XML-, XML-, RecordType ( Employee) XML-, . .
Employee, , . . 5 ,
XML-, .
, . 5
SELECT , . 4. , , . , ,


, ( ,
, ).
, .
CREATE PROCEDURE Employee J3etIDFromOrder
@OrderID AS INT,
eEmployeelD AS INT = NULL OUTPUT
AS


SELECT EmployeelD = EmployeelD FROM Orders WHERE OrderlD = eOrderlD


. GetEmployeelD
cOrder :
Set oAdapter = New DataAccessAdapter.cAdapter
With oAdapter
.SPName = "Employee_GetIDFromOrder"
.Parameters.Item("OrderID").Value = lOrderlD
.CallSP daParaieters
lEmployeelD = .Parameters.Item("EmployeeID"}. Value
End With

, MeTozia CallSP cAdapter


EmployeelD
.

, Web

229

(
, ). , . 6 , . . cOrders
CreateOrder. :
Set oAdapter = New DataAccessAdapter.cAdapter
With oAdapter
.SPName = "Order^CreateOrder"
,Parameters.Item("EmployeeID").Value = lEmployeelD
.Parameters.Item("CustomerID").Value = ICustomerlD
.CallSP daParameters
INewOrderlD = .Parameters, Item("RETURN_VALUE").Value
End With

. 6< ,

CREATE PROCEDURE Grder_CreateOrder


@EmployeelO AS INT,

^Customer-ID AS NCHAR(5)
AS


DECLARE OrderlU AS INT

INSERT Orders (EmployeelD, Customer-ID) VALUES (@EmployeeID, @Custonier)

SET $0rderXD - ^IDENTITY
"- : ,
--
UPDATE Orders SET ShipName = cus.CompanyName, SnipAddreSS = cus.Address,
ShipCity = cus.City, ShipRegion ~ cus.Region,
ShipPostalCode = cus.PostalCode, ShipCountry = cus.Country,
QrderDate = GETDATEO
FROM Customers cus
WHERE cus.CustomerlD = CustomerlD AHD Orders.OrderlD = @>OrderID
--
RETURN OrderIO
, RETURN_VALUE Parameters cAdapter.
, ( - ).

230

Microsoft SQL Server

XML-
, XML-
.
cAccessor GetDataXML. GetDataXML .
XML SPXMLState GetDataXML ,
. XML,
Employee_GetDetail (. 4).
<CallSP SPName="Employee_GetOetail">
<RETURN_VALUE Direction="4" Datatype="3" />
<EmployeeID Direction="1" Datatype="3">K/EmployeeID>
</CallSP>

<CallSP>. SPName . ,
<CallSP>. , RETURN_VALUE. Direction . ADO
. PararneterDirectionEnum, ADO:
Public ParameterDirectionEntm
adParamUnknown =
adParamInput = 1
adParamOutput = 2
adParamInputOul:put = 3
adParamReturnValue = 4
End Enum

Datatype * . DataTypeEnum, ADO.


XML EmployeelD
adlnteger (3 -- adlnteger, ADO). , ,
, ; DataTypeEnum . MSDN Online Library.


,
, -

Web

. , ,
XML,
. , , .
XML, .
, spdatest.exe. . 7. Northwind_SQL. , , , ,
Stored Procedure Name.
. , , . , , . :

Customer ListCustomers;

XML Store-d Procedure Date Access TesiITnhty Kelp Pfl

i Click til* "Lift Psraraftters" iroiuniaiid button The


ListViewvril bs populated with the parameter; for the stcs
procedures
3 For each required inptit parameter
Doabls cbck on ths parameter ^ fh;
ListVisw.
3b Snter a value in the Value
3-: Cbek die Update- conanand bjttwi :o store ths

. 7.

Microsoft SQL Server

Einployee_GetDetail;

Employee_GetIDFromOrder;

Order_CreateOrder;

Order_GetDetail;

Order_Updat:eOrder;

Product_ListProducts;

Valid Employee.

Employee_GetDetail.

List Parameters, .
(, ).
(. 8).

Crdsrs;.
^;"."7inr>
s.Ordi>|-iD dl -l=11t.i">11077c/Ofd-l'I!J>

Jt:iit=!'itrifta">Rattiesnake
Canyon Grocery c/CompanyName?

. 8.

XML

. 7 , Employee_GetDetail Employee! D.

Web

233

. ,
Update. Call Stored Procedure
.
XML- GetDataXML . , XML-,
. XML-
(. 8).
, Help .
XML, .

Parameter List XML XML-,


.
cParameters. ( Parameter List
XML List Parameters.)

Call SP XML XML-,


SQL Server. XML-
,
.

Raw Return XML XML-,



. XML- , .

Return XML XML, , . XML-


CallSP cAdapter.
<NoRecordsReturned/> , ,
, .




ADO-. :
' , cmd Dim
' ADOOB.Command
' Set. ,

234

Microsoft SQL Server

' Dim ADODB.Parameter


Set prm = cmd.CreateParametersC'faParaTieter", adlnteger, adParamlnput)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("@P<iraffleter2", adVarChar, _
AdParamlnput, 40)
cmd.Parameters.Append prm
cmd.Execute

, : SQL Server 7.0, Command Refresh Parameters, Parameters


. , . :
' , cmd Dim
' ADODB.Command
' Set
With cmd
.Parameters.Refresh
With .Parameters
,Item("@Parameter").Value = 10
.Item("saParameter2"}.Value = "Some Text"
End With
.Execute
End With

. -, - , , , . ,
. , Parameter, . XML- ,
.


.

(, ).
SQL Server ,
1.

SQL Query Analyzer , . ( SQL Server Northwind, SQL Server.)

Web

235

2.

Northwind.

3.

SQL_XML.sql, Database.

4.

F5, , .

: Northwind, . , . ,
,
Northwind. , ,
, ,
, , .


(spda.dll) DSN ADO- Connection,
. DSN Northwind_SQL ,
. Integrated Security* Northwind
.
DSN, . SQL Server Books
Online.

+


, +.
, +
,
- . +.
+, .
1.

DataAccess.

2.

spda.dll RegSvr32.exe. - DLL . Registering COM Applications http://


msdn.microsoft.com/ library/psdk/com/registry_32er.htrn.
, Windows NT. /. .

236

Microsoft SQL Server

DLL +, .
1.

Visual Basic DataAccess.vbp.

2. cAccessor , Implements COMSVCSLib.ObjectControl, ,


+ Services Type Library.
3.

Project Properties, Make


Compile__MTS = 0 pile_MTS = ~l.

4. DLL +.
: , DLL,
MSI Installer, . .
Platform SDK ( Component Services Help).
, Microsoft Transaction Server (MTS) Windows NT 4.0.
MTS object control library Implements ,
MTS +.


(spdaad.dll) ,
-, , .
1.

Data Access Adapter.

2. spdaad.dll, ,
RegSvr32.exe. DLL ,
, DLL, , DCOM.
DLL +, ,
DLL , MSI
Installer .



-.
spdamid.dll .
1. MiddleTier.
2. spdamid.dll, ,
RegSvr32.exe.

Web

23?

, Web-, COMASP (spdaui.dll). ,


XSL ,
COMASP DLL.
1. COMASP.
2.

spdaui.dll, , RegSvr32.exe.

ASP-
ASP- .
1. ASP , IIS ASP-. ,
. , (
) ASP.
2. IIS- , ASP-.
, ASP.
3. Properties Directory Security. Edit Anonymous Access and Authentication Control. Edit Anonymous Access Frame. - ,

Northwind. Allow IIS to Control
Password. OK ,
. , IIS Anonymous.
, ,
IIS
, .


(spdatest.exe) , .
, , XMLwriter (http://www.xmlwriter.com).
XML/XSL- XML.com
O'Reilly (http://www.xnil.eom/piib/pt/r/874). , XML HTML,

238

Microsoft SQL Server

XML-XML. , ,

. . XML-. ,
, . XML :
, XSL-, XML.
(Dave Grundgeiger) Software Inc.
(http://www.tarasoftware.com) ( ), ,
Microsoft. CDO & MAPI Programming
with Visual Basic (O'Reilly, 2000). Visual Basic .NET,
O'Reilly.
{Anson Goldade) .
#.
(Varon Fugman) Beacon Technologies Inc.
( ). , , - ,
Visual Basic, IIS, MTS/COM+ SQL Server.


SQL
Server CE 2.0 .NET Compact
Framework*

.
. SQL Server CE
2.0. ,
SQL Server CE . SQL Server CE 2.0 ,
. -.


,
, . Microsoft, , .
.
Microsoft SQL 2000 Windows CE Edition ( SQL Server
2.0) Microsoft SQL Server,
MSDN Magazine/ . 2003. 1 (). . .

240

Microsoft SQL Server

Windows CE. SQL Server


2.0
,
Windows Windows CE .NET; ,
, . . SQL Server 2000. ,
SQL Server CE 2.0 .
.
SQL Server CE, , ,
.NET Compact Framework.
,
SQL Server CE, , . SQL Server CE
SQL Server CE.


Windows-, . SQL Server CE 2.0 , , ,
, , , .

, Windows CE.
, Pocket PC () Handheld PC (HPC).

Bluetooth 802.11, .
Windows CE . . ,
, .
. , -

SQL Server CE 2.0

241

PC Card .
Pocket PC, .
Windows .

, .
, OEM-
Windows , ,
. OEM-
Windows 4,. , .NET
Compact Framework ,
,
Microsoft ,
Windows , Compact Flash (CF), - ,
Global Positioning System (GPS), . , Windows ,
. 1. , .
. 1.


{Sales Force
Automation, SFA)

()

, ,

Multiple Listing System (MLS)


( ,
, )
, ,

, ,
( , 16-32 ).

242

Microsoft SQL Server


. ,
. , .
, . API- ,
. , SQL Server CE 2.0 , .
SQL Server
.
. . SQL Server Merge Replication ( ) ( SQL Server 2000).


SQL Server CE 2.0
, . ,
eMbedded
Visual Tools 3.0, SQL Server CE 2.0 , -
eMbedded Visual Basic, eMbedded Visual C++.
eMbedded Visual Tools, , SQL Server CE 2.0
Windows CE 3.x .
Microsoft . Windows .NET
,
. , eMbedded Visual
Basic Visual C++, Visual Basic
.NET, C# ADO.NET.
Microsoft Smart Device
Extensions (SDE),
Visual

SQL Server CE 2.0

243

Studio .NET. Visual Studio .NET SDE Windows .


Visual Studio .NET ( Everett) .NET Compact Framework, Pocket PC 200
Windows CE .NET k.x.

SQL Server CE 2.0


SQL Server CE 2.0 OLE DB. SQL Server 2000 DBPROP_INIT_DATASOURCE . , \Windows\Northwind.sdf, IDBProperties::SetProperties
\Windows\Northwind.sdf DBPROP_INIT_DATASOURCE.
, SQL Server CE
. -
DBPROP_
SSCE_DBPASSWORD DBPROPSET_SSCE_DBINIT,
.
.
,
SQL Server 2000. ,
. eMbedded Visual Basic ( eMbedded Visual C++). SQL Server CE 1.0.
. 1 , char(50)
,
ListBox. SQL Server CE UNION SELECT
, . , UNION SELECT:
Dim strSQL As String =
"SELECT * FROM TableA UNION SELECT * FROM TableB"

SQL Server CE 2.0


ADO.NET. ,
eMbedded Visual Tools 4; OLE DBCE. SQL Server 2000,

. -, SQL Server , (?) , . -, SQL Server . SQL Server 2.0 :


Dim strSQL As String = _
"INSERT INTO TableA (coll, co!2) VALUES (?, ?)";

. 1. ;

Dim strSQL As String "SELECT CONVRT(char(5Q), title), .


td.sales FRQH titles;"
Dim ceCn As New SqlCeConnection("data source\ssceSample.SDF")
1

Diffl ceDr As SqlCsOatafteader

Try
:

ceCn.QpenO

Catch a As SqlCeException
MsgBox(a.ToStrinaO)
End Try
Try
Dim ceCiad As New System.Data.SqIServerCe.SqlCeComraand^strSQl, ceCn)
' ListBox
Dim listfloxl As Hew ListBoxO

With listBoxl
'
.Size = New System.CeDrawing.Size(20B, 160)
.Location = New System.CeDrawing.Point(8, 64)

fle.Controls.Add(HstBox1}
ceDr ceCmd.ExecijteReaderO
lle ceDr.ReadO
. Items.Add(ceDr.GetString(0
End While
End With
Catch a As SqlCeExceptlQfi
MsgBox(a.ToStringO)
Catch a As Exception
MsgBox{a.ToString()J
End Try

ceOr.CloseO

. . .

SQL Server CE 2.0

245

. 1. ()
Try
ceCn.Glose<)
Catch a As SqlCeException
Msg8ox(a,ToString())
End Try
(index pull).
Pull SQL
Server SQL Server .
SQL Server , SQL Server CE 2.0 .
SQL Server CE, , (. 2).
. 2. Pull
1

RDA
Dint ceflda As New RemoteDataAccessO
Din* strSQL = "SELECT * FROM Customers;"

bin* strftemoteConnect = "provider=sqloiedb;data source=" &_


strDataSource & _

"; Initial Catalog=Uorthwirtd;user idssa;password=sa"

Try

ceRda.InterrretUrl = strlnternetURL.
,ceRda.LocalConnectionString = strLocalConnect
' FOO
ce8da.Pull("FOQ", strSQL, strRemoteConnect, _
Data.SqlServerCe.RdaTrackOption.TrackingGrO
Catch a As SqlCeExcept!on
MsgBox<a,ToString(})
End Try

SQL Server CE
, , .
, , Visual
Basic .NET # .NET Compact Framework, try/catch. Visual Studio .NET,
.
, eMbedded Visual Basic, -

Microsoft SQL Server

246

On Error GoTo.
try/catch SQL Server SqlCeException,

.
SQL Server CE 1.0 , . DLL. DLL
SQL Server ,
.


SQL Server CE 2.0 Connectivity Setup Wizard, (. 3). SQL Server CE ,
SQL Server , SQL Server CE, . , Microsoft Internet Information Services (IIS),
, , NTFS IIS SQL Server.
4* Microsoft ! ? CE Connectivity Wizard - ft<rasote RacrtVrtfcrwraft SOI- Server Ctterceweb^J
^j Fie

Aden

yew

Favorihw

Window

|0|]

.!i,i*!Kl|

* -* Lf
_J ^..tcde Root
-; Microsoft SQL Sever CE

:||

,Fo|(ja

HTTp Car!en

HTTPAu!hfnlice!ion

HTFS Pamisaons

Thf! foldia should contain the Seiwi Agent [Ssceja20 d([

p?r^^R^5iWs^^7^^^

- .

Sel the HTTP perrrmiHis Id" the conterU fokta 1 p^imission is lequneti by SQL Server CE
P Bead
P Runicripl5[aJchasASP]
C7 ' f :-

W,it,
fi< Browse

. 3.

Connectivity Wizard

!:

- '- '-!;.;," '.

I "'A

Bl2Wie

SQL Server CE 2.0

247

SQL Server ,
IIS Windows SQL Server
2000 ISAPI DLL. , SQL Server HTTP
(. . Pocket Internet Explorer),
Remote Data Access (RDA) Merge Replication.
SQL Server ,
128- .
,
,
.
, , . Pocket PC 2002 ,
RSA 128- .
Pocket PC 2002,
http://www.microsoft.com/rnobile/pocketpc/downloads.
Microsoft SSL IIS Basic Authentication. Microsoft
Windows CE .NET ( 4.x ) Kerberos, (credentials) Windows
2000 Server ( .NET Server) CE.NET-,
, Windows CE .NET 4., SQL Server CE 2.0 Kerberos.
SQL Server CE 2.0
, SQL Server 2000.
SQL Server CE 32 , 249.
SQL Server CE 2.0 SQL Server Client
Data Provider. , , SQL Server. , ,
, .
, SQL Server Client Data Provider SQL Server SQL Server CE.

Microsoft SQL Server

248

SQL Server CE 2.0 ISQLW


Enterprise Manager SQL Server (. 4). ISQLW Start Visual Studio .NET SDE
eMbedded Visual Tools.

. 4.

ISQLW

ISQLW
, , . , Query Analyzer SQL Server .
SQL Server CE 2.0
SQL Server: RDA Merge Replication. RDA SQL Server 7.0 (
). Merge Replication SQL Server 2000. SQL Server CE SQL Server
. 5.
RDA SQL Server CE 2.0 Windows CE
SQL
Server , .

SQL Server.
Windows CE RDA
SQL SQL Server, ,
, .

SQL Server G 2.0

SOL Server
Client Agent


SGI Server

IIS

SQL Server CE
service Agent

Hi
out

SQL Server Reconciler


()

.out

. 5.

SQL Server SQL Server CE

SQL Server RDA . ,


SQL Server SQL Server
IIS. RDA IIS.
HTTP, SQL Server ,
(publishing rule) Microsoft ISA Server ( Microsoft Proxy Server).
RDA ,
RDA .
. RDA :
, .

250

Microsoft SQL Server

RDA SQL Server 2000 SQL Server 7,0. RDA Visual Studio .NET eMbedded Visual Tools.
SQL Server Merge Replication SQL
Server 2000 - (Publisher/
Subscriber). Merge Replication
, , , . ,
SQL Server 2000, SQL Server
( ) .
Replication SQL Server
, ,
Merge Replication .
SQL Server , RDA,
.
SQL Server 2.0 ( ) SQL Server CE Managed Provider, ,
Visual Basic .NET # .NET Compact Framework.
ADO.NET ,
SQL Server CE Managed Provider .NET Compact Framevvork . SQL
Server CE.
SQL
Server CE. , , eMbedded Visual Basic ( eMbedded Visual C++),
, Visual Studio .NET.
SQL Server CE: ,
, . SQL Server
- .
, .NET Compact Framework, SQL Server CE 2.0 ; System.
Data.SqlClient System.Data.SqlServerCe. System.Data.SqlServerCE.SqlCeException try /catch
Visual Basic .NET #.

SQL Server CE 2.0

, , Merge Replication,
Synchronize ,
(DDL).


SQL Server CE 2.0 . # SmartDevice, Visual Studio .NET .NET Compact Framework.
, Pocket PC 2002.
,
- NorthwindCE .NET Compact Framework SDK. SQL Server, Northwind SQL Server 2000. NorthwindCE SetupRepl.bat,
Nwind_SQLCE.
SQL Server 2000 Publisher Distributor.
Nwind_SQLCE SQLCEReplDemoNet .
.
~ SQL Server Errterfmse Manager - [Cens&te RootUJicrosoft SQL SwversVSQL Serve... |- ItljfXj
"| Fife

Action

$ei4

Look

^indo-rt

-...jeJKJ-

help

<&=, (t] gf* | , rj 4; f s S^ Q 33 ^


Is Console Root
Hi ^fj Microsoft SQL Servers
' jjjj S(3_ Server Group
~. i$3 MBLAPOl (Windows NT)
!*. \2\ Databases
:*' Data Transformation Services
+ Sj.1 Management
'rl CiJ Replication
E
4-^ Publications
^ SQLCEReplDernoNet:Nwind_SQLCE
JiB Subscript iori5
-; Replication Monitor
'r."-i^ Publishers
-i ^ MBLAP01

5QLCERep(DemoNet N wind_5QL^

8 Items

gents__ ^I^KL_J
?i)MBPPC01:-7
^SQLCE5Lib*l:-l
^)SQLCE5ub#J:-2
^)SQLCESub#1;-3
)SQLCE5ub#lH
)SQLCESub#l:-5
j|sQLCESUb#l;-6

Anonymous
Anonymous
Anonymous
Anonymous
Anonymous
Anonymous
Anonymous

t. -.^J Agents
Replication Alerts
Cil Security
* ;j Support Services
'i1 jii] Meta Data Services

<: ;

. 6.

252

Microsoft SQL Server

SQL Server ,
Publisher/Distributor, , SetupRepl.bat - NorthwindCE. , (. 6).


SQL Server CE 2.0, SqlCeReplication.Synchronize. () Nwind_SQL ( SQL Server 2000)
SQL Server ,
SqlCeException ,
Windows- SmartDevice . 7.
Employees , LastName . List View. Synchronize, SQL Server 2000
SQL Server . , SmartDevice
, !
PiSQl-CE Z.GReplDenm lVjfH||fj
: Last Name:

::::::::-:::::;::

:::::::.!:: " : : 1: : : . : : . ! : Find Now ;


: Employe E

ID

Synchronize
EX*

;::::

^Enroll

"--'
. 7.

Windows-

, SetupRepl.bat NorthwindCE, a
SQL Server CE Server Agent IIS
sqlce, HTTP (,
, -

). SQL
Server Connectivity Management, SQL Server CE 2.0
.
,
SqlCeEngine SQL Server SQL Server Nwind_SQLCE Replication. DBInit, Form_Load,
( )
D Sync, (. 8).
. 8.
private void OBInltO
I

try

if (! System, 10- File. ExistsCsSubscriptionDB))


<
SqlCeEngine oEng = new SqlCeEngine{"data source=" +
sSubscriptionDB);
oEng. CreateQatabaseQ;
DBSync();

catch (SqlCeException ex)


ShowErrors(ex);
catch (System.Exception ex)
MessageBox.Show(ex.Message);

DBSync Replication
.
SQL XML-. SQL Server. Synchronize
(. 9).


. DBSync SQL Server

254

Microsoft SQL Server

2000 SQL Server


.
. 9.

private void DBSyncO


// Replication
SqlCeReplication oRepl - new SqlCeReplicationO;

try
//
oflepl.Publisher = "MBLAPQT;
oRepl.PublisherDatabase = "Nwind_SQLCE";
oFtepl. Publication = "SQLCEReplDerooNet";
//
ofiepl.P^blisherLogin = "sa";
oRepl.PublisherPassword "sa";
//
cRepl-SubscriberConnectionString =
"Provlder=MicrosQft.SQLServer.QLDB.CE.2.Q;
Data Source=" * sSubscriptionDB;
oflepl.Subscriber * "H8PPC01";
//
oRepl.InternetUrl = "http://mblap01/sqlce/sscesa20.dll";
//
oRepl.Exchangetype = ExchangeType.BiDirectional;
oRepi.Synchronize();
catch (SqlCeException ex)
ShowErrors(ex);
catch {System.Exception ex)
MessageBox.Show(ex.Messag);
finally
oRepl,8ispose();

SQL Server CE 2.0

255

, SDE- try/catch/finally. ShowErrors SQL Server . . 10 (unwinding) SQL Server


.
. 10.
public static void ShowErrors(SqlCeException ex)
SqlCeErrorCollection oErrors * ex.Errors;
StrirtgBullder oStrBlcJ = new String8uilder();
Exception Dinner = ex.InnerException;
foreach (SqlCeError oErr In oErrors)
4:;

oStrBld.Append("\nError Doee: "


oErr.Hflesult.TaStringC'X"));
eStrBld.AppendC"\nMessage ; "
o8trBld.Append<"\nMinor Err.: "
QStrBId.Append<"\nSource
: "

+
+ oErr.Message);
+ oErr.NativeError);
+ oErr,Source);

foreach (int iHuffiPar in oErr.NurnericErrorPararBeters)


if (iNumPar != 0)
oStrBld.Append("\nNum. Par.

: " -f iNumPer);

foreach (String sErrPar in oErr.ErrorParafneters)


if (sErrPar 1= String.Empty)
oStrBld.Append{"\R Err. Par.

'* sSrrPar);

HessageBox.ShQfcKoStr&ld.ToStrifigO,
oStrBld.RemoveCO, ostraid.l

Find Employees, Click Find Now. SqlCeConnection .


SqlCeCommand
Employees (. 11).
RTRIM, FirstName
LastName ListView.

Microsoft SQL Server

256

, 11.
private void Find Employees (}
{
// SqlCeCormection
SqlCeGonnection oCon ~ new SqlCeConneotion("DataSource="
sSubscriptionDB);

try
oCon.OpenC);
SqlCeCommand oCmd = oCon,CreateCoinBiand();
oCfnd.CoitiraandText =* "SELECT EmployeelQ, RTRDt(LastName) +
, * + RTRlM(FirstName) AS Y'Full Hanre\" mm
Employees WHERE lastName LIKE ? 0ROER BY LastNaffle";
//
oCmd. Parameters. Add( new SqlCeFaraffleter("p1",
txtUstNaae.Text + "1));
SqlCeDataReader oReader = oCffld.ExeeuteReader<>;
// ListView
ivwEfflployees. Items, 1();
while (oReader.ReadO)
{
ListVlewItem oltem = IvwEmployees. Items. Add<new
ListViewItem(new String [3i(oReader.6etString(1),
oReader.Get!nt32(0) . ToStringf) J)};

catch (SqlCeException ex)


ShowErrors(ex);
catch (System.Exception ex)
MessaeBox.Show(ex.Message);
finally
//
if CoCon.State == ConnectionState.Open)
oCon.CloseQ;
if (oGon I- null)
oCon.Dispase();
} -

SQL Server CE 2.0

Parameters SqlCeCommand LIKE SELECT.


SqlCeDataReader List View. , .
Pocket PC 2002 Emulator, . 12.
Pocket PC 2002
Emulator

Help

: 18
Buchananj Steven
CaSahan, Laura
DavollOj Nancy
Dodsworthj Anne
Fuller, Andrew
King, Robert
Levelling, Janet

I ID

:
1
i

-----

7
3

. 12. Pocket PC


, .
SQL Server , ,
, ( , -
). , .
CF Media. , -

9-5917

258

Microsoft SQL Server

, CF. , - ,
.

SQL Server CE 2.0


SQL Server CE 2.0 . SQL
Server CE .
,
. SQL Server CE 2.0 http://www.microsoft.com/sql/ce/downloads/ce20.asp.
(Mark Brown) , (David
Meunier) IdentityMine Inc. (http://
www.identitymine.com),
(, ). IdentityMine
-
Microsoft .NET Enterprise. mark.brown@identityrnine.com
david.meunier@identitymine.com .



Notification

,

.
MR - , 1 (push
technology). Notification Services,
SQL Server 2000 .NET Framework, (notification applications)
,
, .

Notification Services SQL Server. , ,
Web- ( ).

90- , (alerts). , - ,
,
, .
* MSDN Magazine/ . 2002. 5 (). . ,

260

Microsoft SQL Server

. , ,
- , , -
.
Web- . ,
, .
: ,
, , , . , , .
, , . -

( SMTP) (SMS). - , .
, .
, .
,
(, SMS, WAP, Instant Messaging Microsoft .NET Alerts), , ,
.

GPS (Global Positioning System). Web- ( ).

261


,
, , , .
- , ( ) . , -
.

Web- . , , PDA,
, .
, . Web-
. , , .


Notification Services SQL Server , .
-, . , .
,
.

, .
Notification Services .

262

Microsoft SQL Server

, , , Transact-SQL XML.
, Notification Services-
,
, , , , Windows. Notification Services , ,

.

Notification Services
Notification Services
SQL Server, ,
.
,
(),
. Notification Services , .
Notification Services
Notification Services API. , .

,
. , , , ,
.
Notification Services , . .

, ,
.
Notification
Services.

263


(subscriptions) , ,
. , , .
: (scheduled subscriptions)
(event-driven subscriptions).
,
, (
). .
,

. (subscription management application).
Web ASP ASP.NET. Notification
Services API Windows-.
. 1.

Notification Services API

. 1.

, Notification Services (subscriber data) , (subscription data)


, , .

264

Microsoft SQL Server

Notification Services API


Notification Services ,
,
,
.
Notification Services API ( COM Interop) (enumerations).
,
.

ADF
Notification Services , . .
,
XML- ,
(application definition file, ADF). ADF Notification Services. ADF
.
. 2 , Stock
ADF. ,
<Schema> <EventClass>. ,
<FieldType> Transact-SQL. <FieldTypeMods>
, .
. 2.

<EventClasses>
<1 -- Stock. -->
<EventClass>
<! . >
<EventCZassName>Stock</EventClassNaBie>\
<!-- Schema, >
<!
( ). -->
<Field>
<FieldNarae>StGekSymboa</FieldNarBe>
<FieldType>char(10)</FIeldType>
<FieldTypeMo<Js>fiot nuU</FieldTypel*ods>

. . .

265

. 2. ()
</Field>
<! .> ;
<Field>
<FieldNaine>StQckVaIue</Field.Name>
<FieldType>money</FieldType>
<FieldTypeMods>not nuIl</FleldTypeMods>
</Field>
</Schema>
</EventClas5>
</EventClasses>

.

SQL Server,
.
, , Notification Services,
.


Notification Services
(event
providers). DLL, Notification Services,
.
.

.
API. API ,
( API COM Interop ). XML API,
XML- (stream). ,
.
,
Notification Services
, (batches). -

266

Microsoft SQL Server


, . . . 3.

. 3.


. , ,
. (push collector) (pull collector) (push) (pull) . ,
, , . : , , (
), , ,
Notification Services.


Notification Services
: File System Watcher Event Provider SQL Server Event Provider.

, .
File System Watcher Event Provider ,
. ,

267

(welt-formed) XML-. , , .
File System Watcher Event Provider XML XML API, .
, : .
SQL Server Event Provider
T-SQL.
, . ,
-
(collection interval), .
, API
.
(, Web, , Web-)
Notification Services .


(event chronicles). ,
, . ,
( ),
( ) .



,
.
Notification Services
(notification generator). , , (raw notification). ,
, ,
, .
(.
).

268

Microsoft SQL Server

.
Transact-SQL, , , . , .

, .
, ,
, (. 4).

, 4.

. , , ,
, ,
.
,
, , , . (notification distributor)
, ,
,


,
, .
(. 5).

269

,

:

.'. I 1
** 1 &
1 & I ; I
. 5.

, (threads).
, ,
. ,
, ,
, , (digest notification). , , (aggregator),
, ( ). , , .
, (content formatter), ( , ,
) , .
, (locale), ,
, , .
. , , .
SMTP;

270

Microsoft SQL Server

. ,
, .
(multicast notifications)
: , .
,
. , , . ,

.
. , , , .
,
: , .
. ,
.
.


, Notification Sen-ices

. ,
. Windows-.

, .
Notification Services
SQL Server. SQL Server (joins),
.
,
T-SQL!

271



XML- - . ,
(, ,
, ) ,
.
(scale-up),

.
,
, Notification Services
.
SQL-, ,
.
(scale-out), Notification Services
, .

XML
.

Notification Services ,
SQL Server, . Notification Services (
http://www.microsoft.com/sql/ns)
, .
(Mark Brown)
IdentityMine Inc. (http://www.identitymine.com),
( ). IdentityMine
-
Microsoft .NET.
mark.brown@identitymine.com.




SQL*

, SQL (stored
procedures),
.
, .
.NET Framework (reflection services) System. Reflect ion , . ,
Reflection .NET .
,
SQLCommand . , .

, , ,
, ,
, , , (command object). -
, (data service layer)
. , : ,
* MSDN Magazine/ . 2002. 2 (). . .

276

.
, Microsoft .NET
, ,
#, Visual Basic .NET ,
(common language runtime, CLR).
ADO , , . - IBuySpy Portal (http://www.ibuyspy.com)
(. 1).
. 1. GetAn noun cements ( IBuySpy)
8 PROCEDURE GetAnnounceraents
<;

tHodulelD int
)
AS
SELECT
CreatedByllser,
CreatedDate,
Title,
Mo relink,
relink,
Expi reOate,
Description
FROM
Announcements
WHERE
KodulelD = @HoduleXB
AND

ExpireDate > 6etDate()

,
IBuySpy . : . ADO Visual Basic
for Applications (VBA), - , . 2.
-
, VBA-. :

277

Dim Connection As ADODB.Connection


Set Connection = OpenConnection()
Dim Recordset As ADODB.Recordset

Set Recordset = GetAnnouncements(Connection, 13)


Connection.Close
. 2. GetArmouncements ADO
function GetAftnoLmcementsCByVal Connection As ADODB.Connection,
ByVal HodulelD As Integer) As ADODB.Recordset
Dim Command As AMOB,Command
Set Command = New ADODB.Command

Set Command.ActiveConnectlon = Connection


Command. ComfliancfText = "GetAnnouncements"

Command, CommandType = adCmtfStoredProc


Dim Parameters As AOODB.Parameters
Set Parameters = Command.Parameters
Parameters.Append Command.CreateParaineter("eRETURN_VAI_UE", ;
adlnteger, adPararaReturnValue, 0}
Parameters.Append Command. CreateParameter("@MofuleIQ", _
adlnteger, adParamlnput, 0)
PafaiBeters("@ModuleID").Value * HodulelD
Dim Recordset As ADQDB.Recordset

Set fteoordset = New AD08B.Recordset


Recordset.CursorLocation = adUseClient

Recordset,Open Command, , adOpenStatic, adLockReadOnly


Set Recordset.ActiveConnection = Nothing
Set GetAnnouncemertts = Recordset
End Function

: Value Parameter
Variant, ModulelD GetAnnouncements Integer.
,
GetAnnouncements, . - , (disconnected recordset)
Command.
, .
, Visual Basic
SQLDMO .
XML- ,
XSLT-.

278

- 3.

AnnouncementsDB.GetAnnouncements

public class AnnQuneententsBB {


public DataSet SetAnnouncesentsUnt module!^) {
// Connection Coffimand
SqlCormeetion RyConnection = new SqlConnection{
ConfigurationSettings.ApE^ettingsr'connectioflStrtng"3);

SqlDataAdapter sryCoflffliand
new SqlDataAdaprter{"8etAnnounceBeRts",
^Connection);
// Command SPROC
rayCoMaod.SelectComiaRd.CQmantfType = CoiimandType.StoredProeedure;
// SPROC
SqlParajseter pararaeterModuleld = new SqlPararaeterClN'loduleld",
SqlBbType.Int, 4);
parameterModuleld.Value = moduleld;
myCosimaRcf.SelectCofnraand.Parameters.AddCparMeterHoduleld);
// DataSet
DataSet myDataSet new SataSetO;
myCoraiBafld. Fill(myOataSet);
// DataSet
return nyBataSet;

.NET, . ADODB.Connection SqlConnection System.Data.SqlClient ( SQL


Server). ADO- Command SqlComrnand. Parameter SqlParameter.
. . 3 - Get Anno Lincements IBuySpy.
, - Windows DNA
.
- #
Visual Basic .NET.
, , VIJA,
# Visual Basic .NET? , .

CLR . , ,
, ,

279

Reflection
, CLR, , .
(assembly) ( ),
System.Reflection. . 4 ,
#. PortalDatabase -
Get Announcements, VBA-.
, , .
,
:
. 4, Reflection #
using System;
using System. Reflection;
using System. Data;
using System. Data. SqlClieot;
sealed class .PortalDatabase
t
public static DataSet GetAnnoundements(SqlConnection connection,
int moduleld)
{
return null;
sealed class ReflectionSaeiple
{

static void Main()


{

MethodlnfoO methods = typeof(PortalOatatiase).QetMethods(


BindingFlags. Static | BlndingFlags, Public f
SindingFlags. DeclaredOnly);
fo reacti (Methodlnfo method in methods)
{
Console. WriteLine('40},{1} [{2}]", method. DeclaringType. Name,
method. Name, method. ReturnType);
foraach (Parameter Info paramlnfo in method. SetParaaetersO)
Console. WriteUneCAttO} {1}",
pararalnfo. ParaineterType,

280

PortalDatabase.GetAnnouncements [System.Data.DataSet]
System.Data.SqlClient.SqlConnection connection
System.Int32 moduleld

Main AnnouncementsDB. BindingFlags ,


, GetMethods. BindingFlags.Static BindingFlags. Public , GetAnnouncements
public static, . BindingFlags. DeclaredOnly ,
. , AnnouncementsDB System.Object.
, ,
BindingFlags.DeclaredOnly . Main , Methodlnfo,
.
. 5.

SqICommand

sealed class SqlCommandGenerator


{
private SqlCoiranandGeneratorO 0
public static SqICommand GemrateCommaRflKSqlConnectiora connection,
Metnodlnfo metnod, objectt] values)

Sq3.Command command = new SqlCoHimand(method.Namef connection};


command. CoroBiaRdType = CofUBandType.StoredProcedure;
ParaffleterlnfoH parameters - method.GetPararoetersO;
for (int i * 1; I < parameters.LengtK; i++)

SqlParameter sqlParameter = new SqIParameter();


sqlParameter.ParametsrName = "@" + parameters[i].Name;
sqlParameter.Value - values[l];
comm and. Paraaeters.AdcJ{ sqlParameter);

}
return command;

,
SqICommand SqlParameter. , , # Visual
Basic .NET , . , SqICommand . ,

. 5. (connection object),
, , Generate Command SqlConimand.
, , , , SqlDbType, SqlParameter. , SqlParameter
Value. SqlDbType
, Value.
, SqlParameter
(guessing mechanism). SqlDbType
.NET Framework (System), C#
Visual Basic .NET, . 1.
. 1.
SqlDbType

System

C#

Visual Basic .NET

( )

System. Char
System.Int64

char
long

Char

Biglnt
Binary

System. Array
of System.Byte

byte

Byte

Bit

System. Boolean

bool

Boolean

Char

System. String

string

String

DateTime

System. DateTime

System.DateTime

Date

Decimal

System. Decimal

decimal

Decimal

Float

System.Double
System.Array
of System.Byte

double

Double

Image

byte

Byte

IM

System.Int32

int

Integer

Long

Money

System. Decimal

decimal

Decimal

NChar

System. String

string

String

NText
NVarChar

System.String

string

String

System. String

string

String

Real

System. Single
System. DateTime

Smalllnt

System. Intl6

SmallMoney

System. Decimal

Text

System.String

Timestamp

System. Date Time

Tinylnt
Uniqueldentifier

System.Byte

float
System.DateTime
short
decimal
string
DateTime
byte
System. Guid

Single

Small Dale Time

System. Guid

Date
Short
Decimal
String
Date
Byte
System, Guid
, . .

. 1.

()

SqIDbType

System

C#

Visual Basic .NET

VarBinary

System. Array
of System. Byte

byte[]

Byte()

VarChar

System. String

string

String

Variant

System.Object

object

Object

GenerateCommand PortalDatabase.GetAnnouncements, .
GetAnnouncements Methodlnfo , Type.GetMethod. . 6,
Type.GetMethod. Type.GetMethodlrnpl,
. Type.GetMethod
Type.GetMethodlmpl:
Type.GetMethodlmpl("GetAnnouncements",
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static, null, CallingConventions.Any,
new Type[] { i:ypeof(SqlConnection), typeof(int)
}, null);
. 6.

ptfblic static DataSet GetAnnouncements(SqlGonnectlon connection,


Int moduleld)
Hethodlnfo methodlnfo =
typeof(PortalDatabase).GetMethod ("QetARnoufseenmnts",
RSW Type[] { typeof(SqlConnection), typeof(int) });
SqlCommand command =
SqlGofflffiandGerte rato r. Gene rateCommand (connection.,
methodlnfo, new object[] { noduleld });
DataSet dataSet = new DataSetC);
SqlDataAdapter dataAdapter = new SqlDataAdapter{commaRd};
dataAdapter.Fill(dataSet);
return dataSet;

, Type GetMethodlmpl . ?
System.RuntimeType, System.Type. RuntimeType MSCORLIB.DLL, ,

283

, CLR System.RuntimeType ,
typeof # Get Type
Visual Basic .NET. , Type. Get Method
RuntimeType- Get Method Impl, SelectMethod Binder. Binder , RuntimeType. Get Method Impl Binder Type.DefaultBinder. ,
, Binder.SelectMethod, Binder.
. 6 , , ,
-
Type.GetMethod.
- ,
Type.GetMethod. , , , . Framework Class
Library (FCL) , ,
. , : MethodBase. GetCurrentMethod System.Reflection.
, MethodBase ( thodlnfo , Constructorlnfo
), .
GenerateCommand, thodlnfo. :
public static DataSet GetAnnouncementsCSqlConnection connection,
int moduleld)
{
SqlConrnand command = SqlCommandGenerator.GenerateCommand(
connection, (Methodlnfo) MethodBase.GetCurrentMethodQ,
new object[] { moduleld });
// ...
}

: MethodBase.GetCurrentMethod , . .
,
- Inside FooBar? , MethodBase.GetCurrentMethodQ.ToString, ,
. , MethodBase,
.

284

Inside Fool Inside Foo2.


, . Get Met hod MethodBase.GetCurrentMethod.
. , , ?
, ,
sp.
, #-
.
GetAnnouncements, SqlConnection. SqlCommand, .
, ,
- . -
,
, .

-
,
http://download.microsoft.com/download/msdnmagazine/code/Aug02/WXP/EN-US/NETReflection.exe,
. ,
, . ,
SQL Server, System.Data.SqlClient ,
System.Data.SqlDbType.
: SqlCommand Method Attribute, SqlParameterAttribute, NonCommandParameterAttribute SqlCommandGenerator. , (custom) , a SqlCommandGenerator
SqlCommand
- .
. 5, .

SqICommandMethodAttribute
SqICommandMethodAttribute . -,
, # Visual Basic .NET, .
, SqlCommandGenerator
(assertion failure), . (,
.) -, SqICommandMethodAttribute ,
, .
System. Data. CommandType :
CommandType.StoredProcedure ( ) CommandType. Text ( SQL-). -, SqICommandMethodAttribute CommandText, SQL-. ,
-. ,
IBuySpy Portal spGetAnnouncements, GetAnnouncements, :
[ SqlCommandMethod( CommandType.StoredProcedure, "spGetAnnouricements") ]
public static DataSet GetAnnouncements(SqlCofinection connection,
int moduleld)

, :
[ SqlCommandMethod(CommandType.StoredProcedure) ]
public static DataSet GetAnnouncements(SqlConnection connection,
int moduleld)

, SQL-, CommandType. Text


SQL . Announcements
, SQL-:
[ SqlCommandMethod(CommandType.Text, "SELECT * FROM Announcements WHERE
ModulelD = @ModuleID AND ExpireDate > GetDateO") ]
public static DataSet GetAnnouncements(SqlConnection connection,

286

int moduleld)

SqiCominandMethodAttribute ,
; Attribute Usage . AttributeTargets.Method,
.
, SqiCominandMethodAttribute, , , .

NonCommandParameterAttribute
NonCommandAttribute ;
, System.Attribute, . , . , . NonCommandParameterAttribute , ,
, Visual Basic .NET, SqlCommand:
[ SqlCommandMethod(CommandType.StoredProcedure} ]
public static DataSet GetAnnouncementsC
[ NonCommandPa mete ] SqlConnection connection,
int moduleld)
I

1
, SqlConnection
, , , , SQL-. SqlCommandGenerator
, ; . ,
, -,
.
NonCommandParameterAttribute, SqlCommandMethodAttribute, Attribute Usage
. , Sample.Data, Sample.Data.Sql, .

287

,
.

SqIParameterAttribute
SqlParameterAttribute . SqlCommandMet hod Attribute SqlNonParameterAttribute
, ,
. , - ; SqlCommandGenerator .
SqlParameterAttribute , ;
Name, SqlDbType, Size, Precision, Scale Direction. , Name, SqlDbType, Size ,
. (direction), (precision) (scale) , Direction, Precision
Scale. SqlParameterAttribute
. 7.
. 7.

SqiParameterAttribute

SqlCofBfflandHethc^(GofflandType.StorectProce6ure} }
public static OataSet GetCustowrsC
E NonCoaiiBand'Paraffleter ] SqlConrtection connection)
{ ... $
ESqlCoaf!dHettd{CoiranandType.StoredProcedure) ]
public static SataSet GetCustomersByStateC

t HofiCoRimandPararfteter 3 Sql Connection connection,.


[ SqlParamter(2) 1 string state)
{ ... }
i SqlComfftandNethQd( . Stored? rocedu re ) 3
public static DataSet GetCu atoms rBy!d(
E Command-Parameter 3 SqlConrveetion connection,
int customerld)

. StoredProcedure) 3
public static int AddQrderltesK
E NonOommandParameter 3 SqlConnection connection,
;
{ SqlParameterC'PartNr", 20) ] string partHuiaber,
[ SqlParameterCSqlDbTypa. Decimal, Scale = 9, Precision = 4) ] decimal
sltPrice, Int quantity)
{ ... }

' " .,- -r - - -

288

, , . SqlParameterAttribute , ,
.
* , . , .
SqlParameterAttribute . : IsNameDefined, IsSizeDefined, IsPrecisionDefmed, IsScaleDefined, IsTypeDefined IsDirectionDefined. SqlParameterAttribute : (defined) (undefined).
, ,
, , , ,

. SqlCommandGenerator
. Name, Size, Precision Scale ,
. , ,
_name null ; . , . _ _direction , ,
.
: __typeDefined _directionDefined
.

SqlCommandGenerator
, , ,
SqlCommand.
GenerateCommand
, . 5. , GenerateCommand ,
, . NULL ( Nothing Visual Basic .NET),
Generate Command . StackTrace
System.Diagnostics, (stack trace).
* . . .

2S9

,
StackTrace.GetFrame (, 0, GenerateCommand):
if (method == null)
method = (Methodlnfo) (new StackTrace<).GetFrame(1).GetMethod());

.
Type.GetMethod. , MethodBase.GetCurrentMethod . ! : - . . -, ,
. -, AttributeUsage SqlCommandMethodAttribute
. -, StackTrace.GetFrame MethodBase ( Methodlnfo ), GenerateCommand Methodlnfo. , GenerateCommand, InvalidCastException.
- ( ),
,
NULL , :
. , , Type.GetMethod,
MethodBase.GetCurrentMethod ,
StackTrace 12- .
.
MethodBase.GetCurrentMethod
NULL. , , MethodBase.GetCurrentMethod - ,
, Framework, ,
. , FCL (permissions) .
, GenerateCommand , SqlCommandMethodAttribute. ( , , , .) GenerateCommand SqlCommand Connection, CommandType CommandText.
10-5947

290

CommandText, .
, CommandText ; . ,
GenerateCommand , ,
,
SQL-
. GenerateCommandParameters, ,
, .
SqlParameter SqlComraand. ,
:

KonCommandPararaeterAttribute,
;

SqlParameterAttribute, ,
,
SqlParameter;

SqlParameterAttribute ,
;

SqlParameter
.

, (assertions), , ( NonComrnandParameterAttribute), , , GenerateCommandParameters. , -


, .


, , (direction) SqlParameter. ,
, . #
( ), ( ref) (output only) (
out), ParameterDirection.Input, ParameterDirection.InputOutput ParameterDirection.Output. Visual Basic .NET , ParameterDirection.Input (

291

ByVal), ParameterDirection.InputOutput ( ByRef).


ParameterDirection.Output , SQL-, , (
) . ,
GenerateCommand . (
) , (boxed) - ,
.
SqlParaineter
.
. AddAnnouncements IBuySpy Portal (. 8). ,
(auto-assigned identity). , 9
, out Ctt-. SqlCommandGenerator ref,
, .
. 8. identity
CREATE PROCEDURE AtWAnnGunceflient

Title
tHoreLlRk
@MobileMo relink
ExpireOate
^Description

nvarchar(IQQ),
nvarcHar(150),
nvarchar{150),
nvarchar(15Q), .
OateTime,
nvarchar(20QO),
int OUTPUT

AS

INSERT INTO AnfflOtmceiiBnts

(
Module ID,

CreatetfByUser,
CreatedDate,
Title,
HoreLink,
. . .

292

. 8.

Identity ()

MobileMo relink,
ExpireDate,
Description

)
VALUES

@ModuleID,
SUserName,
aetDeteO,
@Mo relink,
ExpireDate,
^Description
SELECT

. 9. #-
public static void AddAnnouncefflent(
[ NonCoBimandParameter ] SqlConnection connection, int nroduleld*
[ SqlParaeter(1QQ) ] string userName,
SqlParameter(150) ] string title,
[ SqlParameter{l50) ] string ntoreLink,
SqiParameter(150) ] string mobileHoreLink,
DateTirne expireDate,
' [ SqlParameter(2000) ] string description,
out int itemld)
= 0; // ,
// "itemld"
SqlCommand command = SqlGofflfnand6enerator.6enerateCoMand(connection,
null, new object{3 { moduleld, userKame,
title, raorelink, mobileHoreLink,
expireDate, description, itemld });
command. ExecuteNonQueryO;
itemld = (int) command.Parameters["@IteeiID"].Value;

, Reflection , . . 10
Swap, (late binding). Swap , Swap-

Proxy , .
, Visual
Basic .NET, (
Option Strict Off) , #. , . 11 ,
. 10, Visual Basic .NET. SwapProxy ,
, Reflection, Visual
Basic .NET . Type.InvokeMember,
Methodlnf.Invoke.
. 10. Reflection Parameters,
class Sample
public static void Swap(ref int a, ref int tj)
int teiap = b;
b = a;

a - temp;
public static void SwapProxyCref int a, ref int b)
objectl} parameters = new ob]ect[] { a , b }',
typeof(Sample).GetMethod("3wap").InvQke(nuXl, parameters);
a = (int) parameters[0};
= (in-t) paraiaeter&Et];
static void Hain(stringn args)
I
int a = 1;
Int b * 2;

SwapPraxy(ref a, ref b);


System. Console, WriteLine<"a = IQ>. b =

. 11.

Swap Visual Basic -NET

Class Sample

Public Sub SwapCByBef a As Integer, Byflef b As Integer)


Dim temp As Integer == b ,
b=a
a * temp
. , .

294

. 11.

Swap ...

()

End Sub
End Class
Module Module!
Sub Main<)
Difo a As Integer = 1
Dim b As Integer = 2
Dim As Object * New San*ple<)
o.Swap(a, b)
System.Console.WriteLine("a = {Q}, b = ", a, b)
End Sub
End Module
, Visual Basic .NET
IL-, #. Main ,
ILDASM, . 12. ,
IL-, : IL-
_Vb_X_array_2 .
. 12. Main IIDASM
.method public static void Hair*() oil managed
{
.entrypoint
.custom instanoe void [mscQrlibJSystem.STAThreadAttribote::.ctor()
* ( 01 00 00 00 )
// Code size 114 (0x72)
: .naxstack
.locals init ({0] int32 a,
[1] int32 b,
[2] object 0,
[3] objeetn _Vto_t_array_2,
[4] obJectE] _V&..t_array_1,
E5] boolU _Vb_t_array_Q)
. "f3At2P088-C2SG-HDO-B442-OOA0244A1DD2}'",
4994B45C4-E6E9-11D2-9Q3F-OGC04FA3G2A1J",
"100000000-0000-0 000 0000-OOOOOOOOOOQO)"

// Source File "C:\Documents and Settings\atifa\Hy Documents\Visual Studio


Projects\vbref\Module1.vb"
//000015:
Sub MainO
|L_0000:
//000016:
//000017:
DiiB a As Integer = t
Idc.i4.1
IL.0002: StlOG.O
. . .

. 12, Main ILDASM


//000018:
1:
IL_GQQ4:
//00001:
,11.0605:
ILJKKte:
//000020;
ILJJOQb:
IL.OOQc;
ILJJOGd:
IL_0012:

IiJH>l3;

295

()

Din b As Integer = 2

lde.14.2
stloc.1
Dim As Object = SarapleO
instance void vbref .Sample: : .ctor<)
newobj
stloc.2
o.Swap(a, b)
ldloc.2

Umll
idstr

"Swap"

ldc.14.2

newarr

ILJ)Q18: stloc.s
IL_001a: Idloc.s
ILJWic : Idc.i4.0
IL_001d: ldloc.0
IL_001e: box
ILJ3C23; stelern. ref
24: Idloc.s
ILJ3026: Idc.i4.1
ILJ327: ldloc.1
IL_0028: box
Il_002d; steleffl. ref
IL_002e: Idloc.s
IL_0030: Stloc.3
: 11.0031: Idloc.s
11.0032: Idnull
11^0033: Idloca . s
IL_0035; call

Imscorlib]SysterB. Object
_b_t_array_1
_Vb_t_array_1

[msGorlib]System.Int32
_Vb_t_array_1

[mscorlib}System, Int32
_Vb_t_array^1

Vb^t.array^S
void
[Microsoft.VisualBasiclMierosoft.VisualBasic.Helpers.LateSinding
: :UteCall(object, class [mscorllblSystera.Type, string,
objectC], striRa[3,boolCl&)
IL_003a:
_Vb_t.array_0
IL_003b: Idloc. s
It_0t3d: ldc.14.1
IL_003e; Idelem.i1
IL.003f: brfalse.s IL_OQ4a
IL_0041 : Idloc. 3
Il_OQ42: ldc.14,1
IL_0043 : Ideleei. ref
ILJ)Q44: call
tntaa
[Microsoft.Visual&asiclHicrosoft.VisualBasic.Helpers.IntegerType
:: FroinObject(object)
ILJXMS: stJoc. 1
IL_004a: Idloc.s
.Vb
IL_.004c: Ide,i4,0
1L 004d: Idelem.i1
. . .

296

. 12. Main -ILDASM (}


ILJ)Q4e: brfalse.s ILJHffit
IL_0050: ldloc.3
IL_0051: Idc,i4.0
ILJ)052; Idelem.ref
IL_0053: call
int32
[HierosQft.VisualBasiGJMlerosoft.VIsualBasic,Helpers.IntegerType
::FromQbJect(object)
IL_0058: stloc.O
//000021 :
sSystem.Console.WriteLineC'a = {0}, b = {1}", a., b)
IL_0059: Idstr
"a = {0}, b = U)"
It^OOSe: ldloc.0
ILJ)05f: box
CfflscorUb]System.Int32
1L,0064: ldloc.1
tniscorlib3Systent.Int32
Il_0065: box
006: call
void [BiscorlibjSystem.Console; ;WriteLine(string,

object,
ooject)

Il_006f:
//000022:
//000023:
End Sub
IL_0070:
II 0071:

ret

} // end of method Modulel:;Nain


, , , Visual Basic .NET,
, System.Reflection.Emit, .

NULL-
, NULL-.
NULL- , -
int # Integer Visual Basic .NET.
System.Data.SqlTypes. , Pubs :
CREATE PROCEDURE [GetEmployeesByJob](rjob_id SMALLINT = NULL) AS
SELECT *
FROM [employee]

WHERE [job_id] = ISNULL(@job_id, [job_id])

297

@job_id NULL,
#- Sqllntl6 short,
:
[ SqlCommandMethod (CommandType.StoredProcedure)]
public static DataSet GetEmployeesByJob(
[ NonCommandParameter ] SqlConnection connection,
[ SqlParameter("Job_id") ] Sqllnt16 Jobld}
{
SqlCommand command = SqlCommandGenerator.GenerateCommand(
connection, null, new object[] { jobld });
DataSet dataSet = new DataSetQ;
SqlDataAdapter dataAdapter = new SqlDataAdapter(command);
dataAdapter.Fill(dataSet);
return dataSet;
I
, jobld
NULL NULL;
DataSet dataSet;
dataSet = GetEmployeesByJob(connection, new Sqllnt16(5));
dataSet = GetEmployeesByJob(connection, 5); //
// Sqllnt16
dataSet = GetEmployeesByJob(connection, SqlInt16.Null);

GetEmployeesByJob #, Visual Basic .NET .


Sqllntl6.op_lmplicit, IntelliSense Visual Studio, GetEmployeesByJob , . Visual
Basic .NET:
Dim dataSet As DataSet
dataSet = GetEmployeesByJobfconnection, New Sqllnt16{5))
dataSet = GetEmployeesByJob(connection, Sqllnt16.op_lmplicit{5))
dataSet = GetEmployeesByJob(connection, SqlInt16.Hull)



Sql Parameter Attribute
sealed ( Nonlnheritable Visual Basic
.NET).
, .

298

, , Attribute;
(seal) . , . SqlParameterAttribute
, (user-defined types),
. SQL Server.
, . NVARCHAR(IOO), SQL Server
. , . SqlParameterAttribute
, . , ,
SqlParameterAttribute
sysname SQL Server. , SysNameParameterAttribute :
sealed class SysNameParameterAttribute : SqlParameterAttribute
{
public SysNameParameterAttributeC) : base{SqlDbType.NVarChar,
128} {}
public Sy$NameParameterAttribute{string name) :
base(name, SqlDbType.NVarChar, 128) {}

, , ,
, . ,
, , . 13.
- ,
, SqlCommandMethodAttribute
CommandType, CommandType.StoredProcedure. -
- !

. 13.
using
.usinf
using
class

299

System;
System. Reflection;
Sample.Data.Sql;
Sample

static void Hain(string[3 args)


Assembly assembly = Assembly.LoadFrom(args[0]);
foreach {Type type in assembly.GetExportedTypesO)
foreach <HethodInfo aietlwdlnfo iR type.GetHethodsO)
SqlCofflfflandHeth-odAttribute attribute =
CSqlCofBffiandHethodAttribute) Attribute.GetGustomAttribute
(iiethodlnfo, typeof(SqlCoramandMethodAttri&ute;
if (attribute != null &&
attribute. CoiwnandType ==
System.Data.CormandType.StoredProcedure)
Console, Write("{6}.{1}",
nethodlnfo.NaBe);
If (attribute.CofflaiandText.Lervjth 1= 0)

Console.WriteC -> {0}", attribute.CoiwaandText);


.Writellne();

. , ,
SQL- (. 14), #- , . ,
. , ( , ).
, .
. 14.

SQt- #-

set noeount on

declare @sp varchar(lOO)


set esp = ' '
. . .

300

. 14.

SQL- ...

()

declare @oid int


select eoid = o.id from sysobjects where . = @sp
declare @last int
function signature
select iglast = maxCc.eolid)

froffl

dtjQ.syscolufftns

where

c.id = oid

select case c.colid


r

when 1 then [ SqlComiriandMethodCCQBfflandType.StoredProcedure) ]'


+ char(l3) +
'public static SqlCoifimaRcJ ' + esp + '(* + char(13)+
t tteiConnnandParaieeter ] ScilConftection
' connection'
+ (13) *
else ' '
end
+ '
' +
case t.name
when "char' then
SqlPararaeter('*convert(nvarchar(10}, c.length)*') '
when 'varchar' then
[ SqlParameter(f+convert(nvarchar(tO>, c.lengthH') J*
'nchar' then
[ SqlParameter('+convert(nvarchar(10)h c.length /2)+')3'
when "nvarchar" then
'[ SqlParameterC'+cor>vert(nvarchar(10),c.length/2)+')]*
else
end

case t.name
when 'char' then 'string'
when 'nchar' then 'string'
when 'varchar' then 'string'
when 'nvarchar' then 'string'
when 'bit' then 'bool1
when 'datetiiae' then 'DateTime'
when 'float' then 'double'
when 'real' then 'float'
when 'int' then 'int'
else 'object /* ' + t.name + ' */'
end
' + lower(substrlng(c.name, 2, 1)} + su*string(c.name, 3, tOO)
case c.colid

when 91ast then ')' + char(13) + "{'


else ','
end
. . .

. 14.
front

SQt- ...

301

()

dbo.syscolumns

left outer join dbo.systypes t on c.xusertype = t.xusertype


where
c.id = @old
order by
c.colid

,select

case c.colld
when 1 then
return SqlGo[nmandGenerator.GenerateCofflffland(connection,'
+ char(13)
else " "
end
+ '
' + lowerCsubstrlnsCc.name, 2, 1 + substring
c.name. 3, 100)

case o.colid
when elast ttierv ');' + char(13) + ',}*
else ','
end
from
dbo.syscolumns
where
c.ld = @oid
order by
c.colic)

, isqlw (SQL
Query Analyzer), ,
@sp !
(result pane),
. ,
SqlCommand, , .
SqlDataAdapter, SqlDataRcader.
isqlw,
, (grid).
Results Options (. 15). , , SQL Server 2000, , ,
7.0.
Visual Basic .NET
, .

302

Default results target:


Results output fornut: ("]

Maximum characters per column:


f" Flint column headers
~ crol results a; received ("]
" Output queijj

[256


Results ( Text

" Right align numerics ["]


~ Discard results
" a query batch c:orrplBtes:

. 15.


Print column headers

, Reflection . Reflection
( )
, ,
. CLR- . . ,
,

.
. , Sql Command Generator
.
(Atif Aziz) Skybow AG
Microsoft'oBeq (ex-Microsoftie).
.NET Framework.
Microsoft.
atif.aziz@skybow.com.

, : , ,
, .
,
.
, . ,
.
, . , ,
? ,
, ,
.

. .
. , . ... . 10 ,
, , .
MSDN Magazine/ . 2002. 3 (). . .

304

1. ,
,
: , . ,
,
. ,
.
, - (crosssite scripting attacks) SQL- (SQL injection attacks)
. .
.

2.
, , ,
. , /++-. , , , .
,
.

, .
,
- ,
.
++-:
void DoSomething(char *cBuffSrc, DWORD cbBuffSrc) {
char cBuffDest[32];
memcpyCcBuffDest, cBuffSrc, cbBuffSrc);
}

? , cBuffSrc
cbBuffSrc , , , .
, (
) , cBuffSrc cbBuffSrc cBuffDest. memcpy
cBuffDest, DoSomething, cBuffDest
.
, .

305

, , , , cBuffSrc cbBuffSrc:
void DoSomethtng(char cBuffSrc, DWORD cbBuffSrc) {
const DWORD cbBuffOest = 32;
char cBuffDest[cbBuffDest];
ttifdef
DEBUG
memset(cBuffDest, 0x33, cbBuffSrc);
Sendif
memcpy(cBuffDest, cBuffSrc, min(cbBuffDest, cbBuffSrc));

, , . -, ,
. , ! -, ,
, . , (
), . ( ,
!) ; : memcpy
, , .
Microsoft , ( Windows Security Push),
, , , . http://msdn.microsoft.com/library/
en-us/dnsecure/html/strsafe.asp.

3. -
, - , Web , - Web-.
ASP.NET:
<script language=ctf>
Response,Write("Hello, " + Request.QueryStringC'name"));
</script>

. , ,
!
URL:
tittp://explorations! . com/welcome. aspx?name=Michael

# , , . , , HTML-. URL:

306

fittp://northwindtraders. com/welcome.aspx?name=<script>alert( 'hi! ');


</script>

Web-,
hi!>>. ? . ,
, -
HTML-, cookie
.
cookie - .
.
. , , . , :
Regex = new Regex(@""[\w]{1,40}$");
if (.Match(strName).Success) {
// ! .
} else {
// ! .
}

, 1 40
- .
,
HTML- ! , , - .
HTML ,
. HTML-
escape-. HttpServerUtility.HtmlEncode ( ASP.NET) Server.HTMLEncode ( ASP) .

4.

, , , SQL-.
, SQL- , Microsoft SQL Server
Oracle.

307

:
void DoQuery(string Id) {
SqlConnection sql= new SqlConnection(@"data source=localhost;" +
"user id=sa;password=password;");
sql.OpenO;
sqlstring= "SELECT hasshipped" +
11
P
FROM shipping WHERE id= " + Id +
;
SqlCommand cmd = new SqlConimand(sqlstring, sql);

. -, Web- SQL
Server (sa).
, . -, sa
password!
, SQL-. 1001, SQL- (
):
SELECT hasshipped FROM shipping WHERE id = '1001'

: '100 DROP table shipping , :


SELECT hasshipped FROM
shipping WHERE id = '1001'
DROP table shipping - ';

. , , shipping! SQL ,
, , SQL-!
, , ,
SQL Server. . .
sa, SQL
Server . SQL Server sa; Windows- (!) .
SQL- . , (, , ):

308

= new Regex(@"~\d{4,10}$");
if {I r.Match(Id).Success)
throw new Exception("Invalid ID");
SqlConnection sqlConn= new SqlConnection(strConn);
string str="sp_HasShipped";
SqlCoiwand cmd = new SqlCommand(str, sqlConn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@ID",Id);

, -
SQL- , -
. ,
, .

5. !
. , 30%
,
, , . , , .
: ,
. , ,
, . , , ,
. \32-
CryptoAPI; System.Security.Cryptography .

6.
- 90% , . Internet Information Services (IIS) 6.0
. :
, , . ,
.

7.

(common language runtime, CLR) .
, , ,

309

. , , , , .
, . , ,
,
, . , .
, , . ,
( !) , ,
. , ,
, , .
, . ,
.
- ( ), , .
, ,
.
,
, , -
,
.
, .
, , Microsoft .NET Remoting; , , .
.NET Framework,
. , ,
, ,
,

310


.
,
. 1. . 2 , XML-,
. , , ,
.
. 1.

using. System;
using System.Security.Permissions;
// ,
//
[assembly: PenuissionSetAttribui.e(
Securi tyAc t i n.R e q i jest M i n i mu m,
- - File-"iin_per.xEsl"}3
// ,
// ,
[assenbly: PerissionSetAttrbute<

SecurityAction. ftetjuestOptlonal,
File="ept_pe nn.xffll")3
// ,
// ,
//

, .
,
. ,
, CLR-, .
PerniitOnly Deny,
, . , , . , , , .
,
. , Assert.

311

. 2.
using System;

using System.Security;
using System.Security.Permissions;
class App {
static void Nain(stringU args) {
//
IPermission a new flvlroRfflentPennis3ion{
Envl ronmerrtPe rmissionAccess. fleat),
"HyEnvi ronnrentVar");

IPermission b new FileSlalogPeraisslonC


FileOialogPermissiQnAccess.Qpen);

PermissionSet ps ~ new Penai$sionSet(


Pe riHissionState. Hone);
ps.AcfdPerBiisslon(a);
ps.AddPerBiission<i>);
Console. WrlteLine(ps.ToXBlO);

8.
: , , .
, . , , , .
, .
, .
. ,
,
. , , , ?
. . -, , . , .
? , , ,
.
. -

312

,
- , .
, ,
.
.
. , , . , .
. , . :
bool accessGranted = true; // !
try {
II , c:\test.txt
new FileStream("c:\test.txt", FileMode.Open,
FileAccess.Head).Close();
.
catch (SecurityException x) {
//
accessGranted = false;
I
catch ( . . . ) {
// -
i

, CLR , SecurityException . , , , (DACL)? ,


.
:
bool accessGranted = false; // !
try {
// , c:\test.txt
new FileStream(@"c:\test.txt", FileMode.Open,
FileAccess.Read).Close();
// , !
accessGranted = true;
}
catch (...) {}

313

,
.

9.
( )
Windows, (impersonation). , . ,
, , , DACL , ,
,
(impersonation token) . . .
, DACL , , , , .
,
, .

. . , Web-.
ASP-, ISAPI
ASP.NET, Web.config :
<identity

impersonate="true">

: , .
(. 3). ISAPI, Web-.
IUSR_MACHINE ,
. -
SYSTEM! ,
. , IUSR_
MACHINE? ! RevertToSelf, . .
: CreateProcess. -

314

, , .
ftSPflfT WP-

. 3.

? , ,
, . , SYSTEM, Web- Web-.
,
IWAM_MACHINE, , , . ,
IIS 6.0, Windows .NET
Server, SYSTEM.
, Web- .
- . - (in-process COM server),
,
. , -
. !
, .
, DCOM
RPC. ,
. ,
(, ) . , , ... , ? - , , -

315

, . ,
,
.
(- ), .
, ,
, .
, .

10. ,

.
, Windows, , ,
, ? Windows
, ,
, , ?
? , .
, , ,
. () ,
( ), , , , ,
, , , , . ,
, . , ,
(access violation). ,
. !
FILEMON (http://sysinternals.com), , , .
Program Files (
),
. , Program Files -

316

. , -
,
, .
Windows XP
(http://www.microsoit.com/vvinlogo).
. - , . ,
.
, , RunAs (.
Security Briefs 2001 . http://msdn.microsoft.com/msdnmag/issues/01/ll/security/security0111.asp). , . ,
, ,
, .
Web-
(http://www.develop.com/kbrown);
Writing Secure Code (Microsoft Press, 2001)*,
, , .
(Michael Howard) Security Program
Secure Windows Initiative Microsoft. Writing Secure
Code "Design Secure Web-based Applications for Microsoft
Windows 2000 ( Microsoft Press).
(Keith Brown) DevelopMentor ,
. . "Programming Windows Security {AddisonWesley, 2000), Effective COM.
.NET.
http:// www. deve I op. m/ k b rown.

* ( 2003 .).

DataRelation
ADO.NET

ADO.NET ADO ,
.
ADO.NET

, INNER JOIN. , DataRelation
. DataTable. DataRelation,
,
DataSet.

ADO.NET ADO ,

(rowsets). , DataSet DataTable, , DataTable,
. ADO.NET DataTable , , . ( ) ,
, DataTable (grid) EjataTable
. DataRelation ADO.NET.

MSDN Magazine/ . 2002. 5 (). . .

318


ADO.NET
, INNER JOIN. ,
DataRelation
.
, DataTable,
DataRelation, , DataSet,

DataRelation?
, , . , , , ,
. ,
.
, , ADO.NET- DataRelation (http://msdn.
microsoft.com/msdnmag/issues/02/02/data/data0202.asp)*. , , , DataGrid Web-. (DataGrid DataTable,
.)
DataRelation ,
SQL-.
(customer), (orders), (order details) Northwind. , DataTable, (joined) , DataTable,
, ( ,
).
, ,
, . , DataTable.
. . . ADO.NET: . 77.

DataRefation ADO.NET

319

DataTable , .
: ,
, .
DataTable ,
. , , ,
DataTable.
, , . , , .

. -
ADO.NET. , DataTable,
,
. DataRelation, , ( GetChanges) . .


, DataTable DataRelation, ,
. , , , (, ), . 5 , 5
, 25 .
SQL.
:
DataTable.
(join queries). , SQL- ,
, . . . ,
(. 1).
, ,
, -

320

. , ,
,
. DataRelation , . DataSet
. . ,
.
. 1.
SELECT

,
c.Gustoflierlu,

.,
e.ContactName,
o.QrderlD,
o.QrderDate,
Qd.ProdtietlD,
p.PrcKHictNaine,
od.UnitPrice,
od.Quantity
FRQH
Customers
JOIN Orders ON c.CustQinerlD = o.CustoraerlD
JOIN [Order Details] od ON o.OrderlD = od.QrderlD
INNER JOIN Products p ON od.ProductID = p.ProduotlD

DataTable .
DataTable (, , ), DataRelation, DataTable ,
DataTable. ,
DataTable, ,
SqlCommand, Customers
Northwind. SqlCommand SQL-
, Sql Data Adapter, DataTable .


XML-
, ADO.NET
.NET-. ADO ,
(data shaping). -

DataRelation ADO.NET

321

, , .
, SHAPE.

, ADO.NET SQL SQL, . XML ADO
XML-. ADO XML
, ADO.NET.
XML- ADO,
XML, , , ADO.NET
. , - .

DataRelation
DataRelation?
DataSet, DataTable,
, . DataTable DataRelation. DataSet DataTable, DataRelation, , ,
, .
DataSet , (. 2).
DataSet DataTable: DataTable , , . DataSet,
, . DataRelation: , . DataRelation
. 3 ( , . 2).
DataRelation
Relations DataSet DataTable
. DataRelation, ADO.NET, . , ,
. , -

11-5947

322

.
, . 3, (
Boolean), , (constraints). .
. 2. DataSet

//-
string sCn = "Data Source=(local);Initial Gatalog=northwind;
User ID=sa;Password*yourpassword";
SqlGonnection oCn = new SqlConnection (sCn);
DataSet oDs = new BataSetO;
//- DataTable
string sSqlGustoraer = "SEIECT CustoBierlD, ,
ContactName FROM Customers";
SqlDataAdapter oOaCustomer = new SqlDataAdapter(sSqlCustQmer,
oDaCustofflB . FH-KoDs, "Customer");

oCn);

//- OataTable
string sSqlOrder = "SELECT CustoroerlD, OrderlD, QrderDate FROM Orders";
SqlDataAdapter oDaOrder = new SqlDataAdapter(sSqlOrder, oCn);

oDaQrder.Fill(oOs, "0rder");
//- OataTable
string sSqlOrderQetail = "SiLECT od.OrderlO, od.ProductIO,
p. ProductNaiee, " +
" od.UnitPrice, od.Quantity FROM [Order Details] oel ""+
" INNER JOIN Products p 0*1 od.ProductIO = p.ProductXS";
SqlOataAdapter oOaQrderDetail = new SqlDataAdapter(

sSqlOrderDetail, oCn);;.
oDaOrderDetail.fill(oDs. "OrderDetail");

. 3. DataReiation
//- DataReiation
Dataftelation oDr_Customer20rder = new DataRelatiGn("Customer20rder"
o&s.Tablest"Customer"].Columns["CustoflierID"1,
oDs.Tables["Order"].Columns["CustomerID"]};
oDs. Relations. Add(oDr_Custoitier20 rder);
//' DataReiation
DataReiation oBr_Grder20rderCtetail =
new DataRelatian("Order20rderDetail",
oOs.Tables["Order"].GoluHins["OrderID"],

oOs.Tables["OrderDetail"].ColuinnsE"OrderIO"J);
oDs-Relations,Add(oDr_Order20rderDetail);

DataRelation ADO.NET

323

DataSet , DataTable, DataSet DataGrid Web-, DataSource:


dataGridl.DataSource = oDs;

DataGrid , : DataTable
, DataRelation.


, (foreign key constraints) DataSet .
DataRelation- Customer2Order (. 3), (unique constraint)
(customer.customerid)
(order.customerid).
, DataSet DataGrid Web-. ,
, DataTable, , . , ,
, false EnforceConstraints DataSet.
, :
.
SQL Server 2000
. , SQL Server 2000
, .
ADO.NET ,
DeleteRuIe UpdateRule ForeignKeyConstraint. (rules) . , CustomerlD DataTable ,
CustomerlD DataTable .
,
Rule : Cascade ( ), None, SetDefault
SetNull.
,
ForeignKeyConstraint. . ForeignKeyConstraint
DataRelation:

324

ForeignKeyConstraint oFKey;
oFKey = new ForeignKeyConstraintC'CustomerForeignkey",
oDs.Tables["Customer"].Columns["CustomerID"],
oDs.Tables[ "Order"]. Columns["CustonierID"]);
oFKey.DeleteRule = Rule.Cascade;
oFKey.UpdateRule = Rule.Cascade;
oDs.Tables["Customer"].Const tnts.Add(oFKey);
oDs.EnforceConstralnts = true;


DataRelation, , / . , ,
, DataRelation, . , . 4.
. 4.
//-
Dataf)ow[] oRows = oDs.Tables["Custoroer"3.Rows[0],GetChildRows(
oDr_Custoiner2Qrder);
string sHsg = "The orders for the first custoiaer are: \";
//- 10
for (int 1=0; 1 < ofiows.Length; i++)
i
//-
DataRow oRow = oRowstij;
sMsg +- "\t" + oSow"CustoiBerID"].ToString(} +
" " + oRow["l>rderID"],ToStrinfl() +
" " + oRow{"OrderDate"].ToStrlftg() + "\n";
}
//-
MessageBox.Snow(sNsg);

, DataTable? , GetParentRows.
,
Get Parent Row. , DataTable
DataTable :
DataRow oRow = oDs.Tables["Order"].Rows[0].GetParentRowC
oDr_Customer20rder);
HessageBox.Show(oRow["CompanyName"].ToSt ring());

DataReiatio ADO.NET

325

ADO.NET
XML. , XML ADO.NET,
DataSet XML. WriteXml, WriteXmlSchema, GetXml GetXmlSchema DataSet,
XML- . GetXml
DataSet, , XML- . GetXmlSchema
( ), GetXml , :
MessageBox.Show(oDs.GetXml(>};

DataSet, XML-
ReadXml ReadXmlSchema. ,
DataSet XML- WriteXml, DataSet XML- ReadXml.
, ADO.NET, , ,
.
. , ,
.
{Johnny Papa) - MJM Investigations
{, ).
ADO, XML SQL Server.
, VSLive.
datapoints@1ancelotweb.com.


ADO.NET.
MSDN Online Code Center http://msdn.microsoft.com/code/
default.asp?URL=/code/sample.asp?url=/msdn-files/026/002/313/
msdncompositedoc.xml.

. , , Microsoft SQL Server Microsoft


Desktop Engine (MSDE) SQL (SQL
managed provider). OLEDB- ADO (ADO
managed provider).
, , ADO,NET DataReader DataSet.
DataReader
. -

Priya Dhawan Building Distributed Applications with .NET. Data Operations on Hierarchical
Row Daca//MSDN Library. 2002. February. - . .

327

,
SELECT, XML-, SQL Server
2000. DataReader
(forward-only) , .
DataSet, ,
. , . .
, SQL Server .NET Data Provider XML- SQL Server 2000.
API-, ExecuteXmlReader, SQLCommand.
ExecuteXml Reader SQL- SQL XML, ,
XmlReader. ExecuteXmlReader , XML-, ,
SELECT FOR XML.


.
, .
SQL- (batch of SQL expressions) SELECT. , SELECT FOR XML, SQL Server 2000 XML.

ADO.NET- DataReader
SQL- SELECT (result sets)
DataReader.
, . DataReader ,
. DataReader .
NextResult Read DataReader.

328

Dim sqlCmd As SOLCommand


Dim sqlDataRdr As SQLDataReader

Dim fid As Integer


Dim rptLine As String
Try

' , ,
' Orders OrderDetails
sqlCmd = New SQLCommand(}
With sqlCmd
.CommandType = CommandType.StoredProcedure
,CommandText = "GetOrders"
.Connection - New SqlConnection(myConnString)
End With
'
sqlCmd.Connection.Open(}
' ; DataReader
sqlDataRdr = sqlCmd.ExecuteReaderQ
'
Do
While (sqlDataRdr.Read)
' -
rptLine =
For fid = 0 sqlDataRdr.FieldCount - 1
rptLine = rptLine & sqlDataRdr.Item(fld).ToString
If fid < sqlDataRdr.FieldCount - 1 Then
rptLine = rptLine & ", "
End If
Next
End While

If Not (sqlDataRdr.NextResult) Then
Exit Do
End If
Loop
Catch E As Exception
Finally
1
DataReader
sqlDataRdr.Close()
End Try
. ''Example 1 BDAdotNetData4.vb {
).

XmlReader ADO.NET- SqlCommand


Microsoft SQL Server 2000 XML.
SELECT XML, FOR XML. ExecuteXmlReader SQLCommand XML- SQL Server 2000.

329

ExecuteXmlReader System,XmLXmlReader,
XML-, SQL Server 2000.
, FOR XML,
ExecuteXmlReader SQLCommand.
Dim sqlConn As SqlConnection
Dim sqlCmd As SqlCommand
Dim xmlRdr As XmlReader
Try

sqlConn = New SqlConnection(myConnString)
'
sqlCmd = New SqlCommandQ
1

With sqlCmd
.ConwandType = CommandType.StoredProcedure
.CoromandText = "GetOrdersXHL"
.Connection = sqlConn
End With
1

sqlConn. OpenO
' DataReader
xmlRdr = sqlCmd.ExecuteXmlReaderC)
'
xmlRd .MoveToContent()
' -
outXML = xmlRdr.ReadOuterXml
'
xmlRd r.MoveToElement()
1
Orderld
xmlRd .MoveToAtt ribute("Orde rid")
Catch e As Exception
'
Finally
sqlConn.Closet)
End Try

. Example 2 BDAdotNetData4.vb (
).

ADO.NET- DataSet
DataAdapter
DataTable DataSet. DataAdapter Connection.

330

, DataSet . (relationship).


DataSet ( DataRelation), . ,
( DataRow)
( DataTable).
GetChildRows DataRow.
DataRelation,
.
DataRelationCollection, DataSet.
DataSet .
. , , (foreign key relation),

DataTable DataTable.
(order details) Orders OrderDetails. DataSet Orders Details, ,
Orderld, DataTables.
Dim sqlDA As SqlDataAdapter
Dim hierDS As DataSet
Dim orderfiow As DataRow
Dim detailflow As DataRow
Dim detailRowsO As DataRow
Dim 1 As Integer
Try
' DataAdapter
sqlDA = New SqlDataAdapterQ
' DataSet
hierDS = New DataSet
'
sqlDA.TableMappings.Addf"Orders", "Orders")

sqlDA.TableMappings.AddC'Orderst", "OrderDetails")
With sqlDA

SelectCommand
.SelectCommand = New SqlCommandO

331

' SelectCommand
With . SelectCominand
.CommandType = CommandType.StoredProcedure
. CormnandText = "GetOrders"
.Connection = New SqlConnection(myConnString)
End With
' DataSet
.FilKhterDS, "Orders")
End With

Fill DataSet , SQLDataAdapter DataSet


. Fill,
SQL Data Adapter .
'
luerDS.Tables("Orders"). PrimaryKey = New DataColumnQ
{ hierDS.Tables("Qrders").Coltimns("Orderld")}
hierDS.Tables("OrderDetails").PrimaryKey = New DataColumn{)
{ hierDS.Tables("OrderDetails"),Columns("OrderDetailId")}
'
hierDS.Relations.Add("Order_Detail",
hierDS.Tables("Orders").Columns("OrderId"),
hierDS.Tables("OrderDetails").Columns("Orderld"))
'
orderRow = hierDS.Tables("Orders").Rows(0)

detailRows = orderRow.GetChildRows("Order_Detail")
'
For i = 0 detailRows.Length - 1
detailRow = detailflows(i)
1
- OrderDetails
strDetail = detailRow("Order!d").ToString & ", " &
detailRow("OrderDetailId").ToString & ", " & _
<JetailRow("ItemId").ToStrlng & ", " &
detailRow("UnitPrice").ToString & ", " &
detailRow("Quantity").ToString)
Next
Catch E As Exception
'
Finally
1

End Try
. Example 3 BDAdotNetData4.vb (
).

332


(committing) ,
, . ,
, (referencing
table) ,
(referenced table). ,
,
. ,
, .
ADO.NET- DataSet ,
,
, . ,
.

ADO.NET- DataAdapter
Update DataAdapter ,
DataSet, . DataAdapter InsertComrnand, UpdateCommand, DeleteCommand.
Update, DataAdapter
, Command
.
Update, InsertCommand, UpdateCommand DeleteCommand , DataSet. ,
DataSet , DeleteCommand.
Insert, Update Delete Command Builder. DataAdapter- InsertCommand, UpdateCommand DeleteCommand, Update insert, update
delete ,
DataSet. CommandBuilder
SelectCommand DataAdapter SQL-, . ,
CommandBuilder Insert, Update Delete, SelectCommand.
InsertCommand, DeleteCommand
UpdateCommand, ,

333

,
, .
,
, .
InsertCommand. UpdateCommand DeleteCommand
DataAdapter
.
DataTable. ,
DataAdapter
.
DataSet DataAdapter.


, ( ) .
, ,
,
;
. Update DataAdapter,
, .

Insert
,
DataSet Id Identity.
,
,

. DataAdapter, DataSet.
. Update DataAdapter,
( Order), . Update DataAdapter, ( OrderDetails).
Dim sqlConn As SQLConnection
Dim sqlDAOrder As SqlDataAdapter
Dim sqlDADetail As SqlDataAdapter

334

Dim
Dim
Dim
Dim
Try

hierDS As DataSet
sqlCmdBldrDetail As SqlCommandBuilder
orderRow As DataRow
detailflow As DataRow

' SQLConnection
sqlConn = New SqlConnection(Common.getConnectionString)
' SQLDataAdapter Order
sqlDAOrder = New SqlDataAdapterQ
' SqlDataAdapter OrderDetails
sqlDAOetail = New SqlDataAdapterO
' DataSet
hierDS = New DataSetO
' SQLCommandBuilder
' Update
sqlCmdBldrDetail = New SqlCommandBuilder(sqlDADetail)
With sqlDAOrder
' SelectCommand
.SelectCommand = New SqlComraandf)
1
Select
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Exec GetOrderHeader @0rderld=-1"
.Connection = sqlConn
End With
' InsertCommand
.InsertCommand = New SqlCommand()
' Insert
With .InsertCommand
.CommandType = CommandType.StoredProcedure
.CommandText = "InsertQrderHeader"
.Connection = sqlConn
' Insert
.Parameters.Add (New SqlParameter("@CustomerId", SqlDbType.Int))
' Direction
.Parameters("@CustomerId").Direction = ParameterDirection.Input
1
SourceColumn
.Paranteters("@CustomerId").SourceColunm = "Customerld"
.Parameters,Add
(New SqlParameter("@OrderDate", SqlDbType.DateTime)}
' Direction
.Parameters("@OrderDate").Direction = ParameterDirection.Input
' SourceColumn
,Parameters("OrderDate").SourceColumn = "OrderDate"
.Parameters.Add (New SqlParameter("@OrderId", SqlDbType.Int))
Direction
.Parameters("@0rderld").Direction = ParameterDirection.Output
' SourceColumn

335

.Parameters("eOrderId").SourceColLimn = "Orderld"
End With
' Orders
.Fill(hierDS, "Orders")
End With
With sqlDADetail
1
SelectCommand
.SelectCommand = New SqlCommand()
1
Select
With .SelectCommand
,CommandType = CommandType.Text
.CommandText = "Exec GetOrderDetails @0rderld=-1"
.Connection = sqlConn
End With
1
Details
,Fill(hierDS, "Details")
End With
'
hierDS.Relations.AddC'Qrderjtetail", _
hierDS.Tables("Orders").Columns("OrderId"),
hierDS.Tables("Details"}.Colunms("Orderld"))
' Orders
orderRow = hierDS.Tables("Orders").NewRow()
1
Orders
orderRow.Item("CustomerId") = 1
orderRow.ItemC'OrderStatus") = 400
orderRow.Item("0rderdate"} = Now()
' OataSet
hierDS.Tablesf"Orders").Rows.Add(orderRow)
1

sq!DAOrder.Update(hierDS, "Orders")
1
Details
detailRow = hierDS.Tables("Details").NewRow()
detailRow.ItemC'Orderld") = orderRow.Item("0rderld")
detailRow.Item("ltemld") = 13
1

DataSet
hierDS.Tables{"Details").Rows.Add(detailRow)
'
sqlDADetail.Update(hierDS, "Details")
Catch e As Exception
'
Finally
1

End Try
. Example 4- BDAdotNetData4.vb {
).

336

: , ,
, ,
.
.

InsertCommand
XML, .
INSERT,
Update Data Adapter,
InsertCommand. . InsertCommand , Command. SQL .
SourceCoIumn.
DataAdapter, .
Dim
Dim
Dim
Dim
Try

sqlConn As SqlConnection
sqlDAOrder As SqlDataAdapter
sqlDADetail As SqlDataAdapter
hierDS As DataSet

'
sqlConn = New SqlConnection(Common.getConnectionString}
' SqlDataAdapter Order
sqlDAOrder = New SqlDataAdapter()
1
SqlDataAdapter OrderDetails
sqlDADetail = New SqlDataAdapterf)
1
DataSet
hierDS = New DataSetO
With sqlDAOrder
' SelectCommand
. SelectCommand = New SqlCommandO
' Select
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Exec GetOrderHeafler 0rderld=-1"
.Connection = sqlConn
End With
1
InsertCommand
.InsertCommand = New SqlCommandO
' Insert

With .InsertCommand
.CommandType = CommandType.StoredProcecJure
.CommandText = "InsertOrder"
.Connection = sqlConn
' Insert
.Parameters.Add
(New SqlParameter("@Order", SqlDbType.NVarChar, 4000))
1
Direction
.Parameters("@0rder").Direction = ParameterDirection.Input
.Parameters.Add (New SqlParameter("@OrderId", SqlDbType.Int))
Direction
,Parameters("@OrderId").Direction = ParameterDirection.Output
' SourceColumn
,Parameters("@QrderId").SourceColumn = "Orderld"
End With
' DataSet
.Fill(hierDS, "Orders")
End With
With sqlDADetail
' SelectCommand
.SelectCommand = New SqlCommandO
' Select sqlDADetail
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Exec GetOrderDetails @OrderId=-T
.Connection = sqlConn
End With
1
DataSet
.FllKhlerDS. "Details")
End With
1

hierDS.Relations.Add("Order_Detall",
hierDS.TablesC"Orders").Columns("Orderld"), _
hierDS.Tables("Details").Columns("Orderld"))
' Orders
orderRow = hierDS.Tables("Orders"),NewRow()
1
Orders
orderRow.Item("Orderld") = -1
orderRow.ItemC'Customerld") = 1
orderRow.Item("OrderStatus") = 400
' DataSet
hierDataSet.Tables("Orders").Rows.Add(orderRow)
' Details
detailRow = hierDataSet.Tables("Details"). NewRow()
detailRow.Item("0rderld") = orderRow.Item("0rderld")
detailRow.Item("ltemld") = 13
' DataSet

337

338

hierDataSet.Tables("Details").Rows.Add(detailRow)
' Details
detailRow = hierDataSet.Tables("Details").Newflow()
detailRow.Item("OrderId") = orderRow.Item("0rderld")
detaiinow.ltem("ltemld") = 12
1

DataSet
hierDataSet.Tables("Details").Rows.Add(detailRow)
sqlOAOrder.InsertCommand.Paraiiieters("@Order"). Value = _
hlerDataSet.QetXnlO
'
sqlDAOrder.Update(hierDataSet, "Orders")
Catch E As Exception
'
Finally
'
End Try

. Example 5 BDAdotNetData4.vb (
).

. .
.

Update
DataSet Update DataAdapter. Update Select.
, , .
Dim
Dim
Dim
Dim
Dim
Try
1

sqlConn As SqlConnection
sqlDAOrder As SqlOataAdapter
sqlDADetail As SqlDataAdapter
sqlCmdBldrDetail As SqlCommandBuilder
hierDS As DataSet


sqlConn = New SqlConnection(Common.getConnectionString)
1
SqlDataAdapter Order
sqlDAOrder = New SqlDataAdapter()
' SqlDataAdapter OrderDetails

339

sqlDADetail = New SqlDataAdapter()


DataSet
hierDS = New DataSet()
' SQLCommandBuilder,
' Update
sqlCmdBldrDetail = New SqlComrnandBuilder(sqlDADetail)
With sqlDAOrder
1
SelectComntand
.SelectCommand = New SqlCommandO
' Select
With .SelectCommand
,CommandType = CommandType.Text
.CommandText = "Exec GetQrderHeader @0rderld=2"
.Connection = sqlConn
End With
' DataSet
.FilKhierOS. "Orders")
End With
With sqlDADetail
SelectCommand
,SelectCommand = New SqlCommandO
' Select
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Exec GetOrderDetails e0rderld=2"
.Connection = sqlConn
End With
' DataSet

.Fill(hierDS, "Details")
End With
1

hierDS.Relations.Add("0rder_Detail", _
hierDS.Tables("Orders").Columns("OrderId"), _
hierDS.Tables("Details").Columns("OrderId"))
hierDS.Tables("Orders").Columns("OrderId").Readonly = False
'
orderRow = hierDataSet.Tables("Orders").Rows(O)
orderRow("OrderId") = 1
'
sqlDADetail.Update(hierDS, "Details")
Catch E As Exception
1

Finally
1

End Try

. Example 6 BDAdotNetData4.vb (
).

340

UpdateCommand

, .
Update, Update DataAdapter, UpdateCommand.
. UpdateCommand , Command.
Dim
Dim
Dim
Dim
Try

sqlConn As SqlConnection
sqlDAOrder As SqlDataAdapter
sqlDADetail As SqlDataAdapter
hierDS As DataSet

sqlConn = New SqlConnection(Common.getConnectionString)
1
SqlDataAdapter Order
sqlDAOrder = New SqlDataAdapterf)
' SqlDataAdapter QrderDetails
sqlDADetail = New SqlDataAdapterf)
' DataSet
hierDS = New DataSetQ
With sqlDAOrder
' SelectCommand
. SelectCommand = New SqlCommand()
' Select
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Exec GetOrderHeader @0rderld=1"
.Connection = sqlConn
End With
' UpdateCommand
.UpdateCommand = New SqlCommandO
' Update
With .UpdateCommand
.CommandType = CommandType.StoredProcedure
.CommandText = "HoveOrderDetails"
'
.Parameters.Add{New SqlParameter("FromOrderId", SqlDbType.Int
.Parameters("@FromOrderId").Direction = ParameterDirection.Input
.Parameters("eFromOrderIci").SourceColumn = "Orderld"
. Parameters("@FromOrderId").SourceVerslon =
DataRowVersion.Original
.Parameters.Add(New SqlParameter("@ToOrderId", SqlDbType.Int
.Parameters("@ToOrderid").Direction = ParameterDirection.Input
.Parameters("@ToOrderId").SourceColuinn = "Orderld"
.Parameters("@ToOrderId").SourceVersion = DataRowVersion.Current
.Connection = sqlConn

341

End With
' DataSet
,Fill(hierDS, "Orders")
End With
With sqlDADetail
' SelectCoromand
sqlDADetail.SelectCommand a New SqlCommandO
1
Select
With .SelectCommand
.CommandType = CommandType.Text
.ComrnandText = "Exec GetOrderDetails @0rderld=1"
.Connection = sqlConn
End With
1
DataSet
.FilKhierDS, "Details")
End With

hierDataSet.Relations.Add("Order_Detail",
hierDS,Tables("Orders").Columns("OrderId"),
hierDS.Tables("Details").ColumnsC"OrderId"))
hierDS.Tables("Qrders").Columns("OrderId").Readonly = False
'
orderRow = hierDS.Tables("Orders").Rows(Q)
orderRowC'Orderld") = 2
'
sqlDAOrder.Update(hierDS, "Orders")
Catch E Exception
1

Finally
1

End Try

. Example 7 BDAdotNetData4.vb (
).
SourceVersion Orderld .

, .
.
,
.
ADO.NET DataSet ,

. ,

342

- ,
DataSet. DeleteProperty ForeignKeyConstraint ( ).
Dim
Dim
Dim
Dim
Dim
Dim
Try

sqlConn As SqlConnection
sqlDAOrder As SqlDataAdapter
sqlDADetail As SqlDataAdapter
hierDS As DataSet
sqlCmdBldrOrder As SqlCommandBuilder
sqlCmdBldrDetail As SqlCommancfBuilder

' SQLConnection
sqlConn = New SqlConnection(Common.getConnectionString)
' SqlDataAdapter Order
sqlDAOrder = New SqlDataAdapterO
' SqlDataAdapter OrderDetails
sqlDADetail = New SqlDataAdapterO
' DataSet
hierDS = New DataSetO
' CommandBuilder,
sqlCmdBldrOrder = New SqlCommandBuilder(sqlDAOrder)
sqlCmdBldrDetail = New SqlCommandBuilder(sqlDADetail)
With sqlDAOrder
1
SelectCommand
sqlDAOrder.SelectContmand = New SqlCommandO
' Select
With .SelectCommand
.CommandType = CommandType.StoredProcedure
.CommandText = "GetOrderHeaders"
.Connection = sqlConn
End With
1
DataSet
.Flll(hierDS, "Orders")
End With
With sqlDADetail
' SelectCommand
sqlDADetail.SelectCommand = New SqlCommandO
' Select sqlDADetail
With .SelectCommand
.CommandText = "Select * from OrderDetails"
.Connection = sqlConn
End With
1
DataSet
.FllKhierDS, "Details")
End With

hierDS.Relations.Add("Order_Detall",
hierDS.Tables("Orders").Columns("OrderId"),

343

hierDS.Tables("Details"J.ColumnsC'Orderld"))
' Orders
orderRow = hierDS.Tables("Orders").Rows.
Item(hierDS.Tables("Orders").Rows.Count - 1)
' Orders'.
1

' Details DataSet.
orderRow. DeleteO
'
sqlDADetail.Update(hierDS, "Details")
sqlDAOrder.Update(hierDS, "Orders")
Catch E As Exception
'
Finally
'
End Try

. Example 8 BDAdotNetData4.vb (
).
.
. Data Adapter- sqlDADetail Details DataAdapter sqlDAOrder.

DeleteCommand
Delete,
Update DataAdapter, DeleteCommand.
. DeleteCommand
, Command.
SourceColumn. DataAdapter, .
Dim sqlConn As SqlConnection
Dim sqlDAOrder As SqlDataAdapter
Dim sqlDaOetail As SqlDataAdapter
Dim hierDS As DataSet
Try
' SQLConnection
sqlConn = New SqlConnection(Cominon.getConnectionString)
1
SqlDataAdapter Order
sqlDAOrder = New SqlDataAdapterO
' SqlDataAdapter OrderOetails

344

sqlDaDetail = New SqlDataAdapterf)


' DataSet
hierDS = New DataSetO
With sqlDAOrder
' SelectCommand
.SelectCommand = New SqlCommandO
1
Select
With .SelectCommand
.CommandType = CommandType.StoredProcedure
.CommandText = "GetOrderHeaders"
.Connection = sqlConn
End With
' DeleteCommand
.DeleteCommand = New SqlCommandO
' DeleteCommand
With .DeleteCommand
,CommandType = CommandType.StoredProcedure
.CommandText = "DeleteOrder"
.Connection = sqlConn
'
.Parameters.Add(New SqlParameter("@OrderId", SqlDbType,Int))
' SourceColumn
.Parameters("@OrderId").SourceColumn = "Orderld"
End with
' DataSet
.Fill(hierDS, "Orders")
End With
With sqlDaDetail
' SelectCommand
.SelectCommand = New SqlCommandO
1
Select
With .SelectCommand
.CommandType = CommandType.Text
.CommandText = "Select * from QrderDetails"
.Connection = sqlConn
End With
' DataSet
.Fill(hierDS, "Details")
End With
'
1

Orders
orderRow = hierDS.Tables("0rders").Rows.
Item(hierDS.Tables("Orders").Rows.Count - 1)
' Orders.
'
' Details DataSet.
orderRow. DeleteO

345

'
sqlDAOrder.Update(hierDS, "Orders")
Catch E As Exception
'
Finally
'
End Try

. Example 9 BDAdotNetData4.vb {
).

DataReader XmlReader , , .
, (contention),
.
DataSet ,
. , Insert, Update Delete , ,
. ,
XML- SQL Server 2000 ADO.NET.



Web

,
Web , ADO.
Microsoft Transaction Services (MTS).

. ,
. ,
Web- , . !
, Web-
ASP, Visual Basic, COM+ JScript. - .
Microsoft Internet Developer 1998 .
(Charles Caison)
SQL Web-.
Web-. (, .) MSDN Magazine ,
Web ,
, .
+ Microsoft Transaction Services (MTS).
* MSDN Magazine. 2001. X6 (). . .

Web

347

(, , MSDN Magazine http://msdn.microsoft.com/msdnmag/codeOl.asp ). Internet Explorer


Netscape Navigator.

. 1 Web-,
ADO- (paging) ,
JScript DHTML. : . Previous Next
, .

. , (. 1) Next, (. 2).
jJAulhiiri D.suldji Miuiusi.H fnterrml EH|I|OIHI

Authors Display

1409-56-7006 Abraham

Sennet

Berime)

J648-9?-1372 Reginald

BlotcriBt-Halls

Corvallis

Oft

J23B-9S-7766 Cheryl

Carion

Berksl*)

J72?-S1-54E4 Michel

DeFrance

Gary

1713-45-1667 Innes

del Castillo

Arbor

. 1.

. 1 , . 2
. , Go to page (. 3).

Records per page. , Refresh . ; ,

348

346-92-7186

Sheryl

Hunter

Pski Alto

. 2.

. .

. , 25 , .
Refresh. -

Web

349

(. 4), , . , (, ), ,
. , ,
, .
3 AulhiiK Dispidy

5Z7-?2-3M6

Mir lnlfii-t 1 wtoi

Monvngstar

Greene

Nasfw

Purr
5J6-92-7106

Sheryl

Hunter

Paid Alto

756-30-7391

Livia

i-arsen

Oaklird

486-29-1766

Charlene

Lockslev

San Francisco

MacFssther

Oakland

. 4.

CA


ADO
,
. . , . 5 .


, Edit,
, . , ,
.
, . 6 Edit Akiko Yokomoto,
, . -

350

,
. .

'-*

^' . ^ -

'....

;^.-

:..

Authors Display

,j
. 5.
AutNut 4

Authors Display

. 6.

Web

351

, . , ,
, , .


: ( Pubs
Microsoft SQL Server 7.0 SQL Server 2000), (ActiveX- Visual Basic MTS), ASP-
(. 7). ASP- HTML-, Web-. ASP- . ( ASP.NET ,
.)

DHTMUJScript

t
/LAN

WTS/COM*

:
. 7.

ASP-
, (ASP/HTML). View_Authors.asp, GenericDisplay ToolPartlofS.asp, GenericDisplayToolPart2of3.asp, GenericDisplayToolPartSofS.asp Styles.css. View_Authors.asp Web-,
URL .

352

, . ( , .) ?
,
, ,
. -.
. 8.
Edit, Browse. . . 9. .
, .
Edit Browse . onclick (. 8),
.
, 8.

'-
sTitle = "Authors Display"
'-
sFormAction = "Vlew_Authors.asp"
'- JScrlpt-.,
sOnRowClick.Prlitiary = "Edit(>;"
*-
sfiowImageSsurce^Primary = "Edit.glf"
- JSeript-,
sQnRowClick_Secondary "Browse;"
'-
sflow!mageSotjrc9__SecQndary = "Browse.gif"

. 9.
<script
<!ft


UUiQUAGE="javascript">
___,._

//- ***4 QenericDlsplayToo


//-
//
var vflowKeyValue;

. , .

Web

353

. 9. ()
GertericDisplayTool**

// __ , __________
function Edit Q
{
elertfPat code here to go edit this record, using the priinary key
vRowKeyValue};
}
function BrowssO

alert('Pttt code here t& go view this record, ysing the primary key
vHawKeyValue);

//- ***

//-
---

//

fuRetion

----

'

"-"

SetftoKeyValue{vKeyValue}

{
vfiowKeyValue = vKeyValue;
:..}
;

// ___________

//- ** GenericDisplayTool***
' i -

I i ____________

//

</

-:..

, , - .
ASP- .
ActiveX-, ASP-
.

<
'-
Set oAuthors = Server. Great eOb]ect("WebDisplayTool.QAuthor")
vRSArray = oAuthors. Getflecords(sUserID, sPassword, _
IPageSize, ICurrentPage, vSortOrder)
Set oAuthors = nothing

, ActiveX -, , 12-5947

354

. , , ,
. ( .)

ActiveX-
ActiveX- (WebDispIayTool) Visual Basic 6.0; (QAuthor) (basCommon).
QAuthor GetRecords,
ASP- . GetRecords
Pubs (. 10)
prAPP_Get_Authors, .
. 11, ADO- Recordset , , vSortOrder, GetRecords. ,
, ,
( ). Recordset . ,
, ( ).
Get Rows. .
. 10.

'-
* "prAPPjSet.Authors"
Set oCn CreateQbjeetC'ADQDS.Connection")
With oCn
.Provider * gsProvider
.Cursor-Location = adUseClient
.ComwetioriTineout = 15
.IsolationLevel = adXactReadUncommitted
.Open gaGonnectionString, sUserlD, sPassword
End With

Set oCffid - CreateQb}ect("Al30DB.Command")


With oCfnd
Set . ActiveCennection * oCrv
. ConrniandTirneout = 30
. Comma ndType = adCrndStoredProc

. . .

Web

355

. 10. ()
. ComroandText - sProcKame
End With
Set oRs * CreateQbject("ADQDB.Recordset")
With oRs

Set .Source * oCrad


.CursorLocatton = adUseClient
.GursorType = adQpenStatic

. Ue&Type = adLockfleadOnly

.Open
.AetiveConnection * Nothing

CloseObject oGn
End With
. 11.

If Not . Then
'-
'- ...
If IsArray(vSortOrder, 2) Then
Set oRs * SortRecordset(ofls, vSortOrder)
End If

'-
EstablisnPagtng ofts, IPageSize, IPafleNuiber

*- ( = )
vData " oRs-SetfiowsClfageSize)
vRs(geBL_RSArray_Data) * vData

End If

Get Rows , ( 0) vRs. ? vRs


, . Get Field MetaData (. 12).

356

. 12.

"-
vFieldHetaData = GetFieltfKetaData(oRs)
'-
vFiel(JetaOata<geSL_Author_SSN><ae8L_FleldProperty_Caption) * "SSJT
vFieldetaData(geBL_Author_FirstNajne)(geBL_FiBldProfrty_Caption} _
* "First Mane"
vFieldMetaData(geBL_Author_UstNaBie)(eBL_FieldPropertymCaptlon) _
= "Last Name"
vFleldHetaDataCgeBL.Author.AddreesXseBl^FieldProperty^aption)
* "Address"
vFieldMetaData{ge8l,_Author._City)(geSL.FieldfrGpertyJJaptiOEv) = "City"
vFieldHetaData(ge8L_Author_State)(ge8L_FieldPropefty_Gaption) * "State"
vFieldMetaData(fle8i-Author_Zip)(ge8L_FieldProperty_Gaptioii) = "Zip Code"
vFieldHetaibtaCg9BL_Author_Corttract)(geBL_FieldProperty_Gaption}
* "Contract"
'-

vFiBldMet8Data(geBUAuthor.SSN>(ge8L_FieldPro(3erty_VJsible) * True
vFieIdHetaBata(geBl^Author_FirstHame)CgeBL_FieldFroperty_Visible) = True
vFiel(JHetaDataCgeBL_Author_LastName}(geBL_FeldProperty_Vislble) ~ True
vFieldMetaDataCgeBL_Author_Addres3)(geBL_FieldPrQperty_Vlsible) = False
vFieldMetaDataCgeBL_Author_City)(g0BL_FieldProperty_Visible) True
vFieldJtetaDataCgeBL.Author.S-UteXgeBL.FieldProperty^Visible) = True
vFleldetaData(geBL_Author.Zip>(geBL_FleldProperty_Visible> False
vFieldfetaData(geBL_Author.Contract)CgeBL^FieldProperty_Visible) = False
*-
vFielfHetaData(ge8L_Aut^ior_SSN)(geBL_FieldProperty_PriiBaryKey) = True
vRs<Be&L^RSArray_FteldftetaData) *

, . ,
, ,
. ASP- , , . (. 12).
, . ,
vRs.
vRs. . 13, ,
, . vRs ASP-.
vRs . 14.

Web

357

. 13.
'- ,

Wltft ofts
ReDira vRecordsetM@taData(0 To 2)

vRecordsetHetaData(geBl_RecordsetProperty_fiecordCount) _

= oFts.RecordComt
vBecQr6settetaDataCgeBL_ReGor(JsetProperty_PageCoimt) _
= PageCount(oRs.RecordCount, IPageSize)
vRecorusetM8taData(seBL-RecordsetProperty_PageHui8ber) = IPageNumber
End With
vRsCgeEU-JlSArray.ftecordsetMetaBata) * vRecordsetHetaSata
GetRecorcfs * vfls

(vBs)




^



. 14.

vRs

ASP-
ActiveX- MTS. . ASP-, Web-. , ( View_Authors.asp).
View_Authors.asp GenericDisplayToolPagelofS.asp. ASP-.
, , ASP, -

358

ActiveX-. View_
Authors.asp ActiveX-.
, GenericDisplayToolPage2of3.asp.
(. 15). . ,
,
.
. 15.

'- *-
vQata * vRSArray(ge8lJi$Array,J)ata)
vFieldHeta&ata - vRSArray(ge8L_f!SArray_FieldltetaData)
vRSNetaData * vR8Array(geBl_RSArray_ReGordsetKetaQata)
oft error resune next
bDataExists = UBound(vData, 2)
bDataExists = CBool(err 0)
if Not bDataExists then
IRecordCount 0
IPagedount 0

else
IReeordCourvt * vRSHeta0ata(geBL_Reoord89tProperty_RecordCoufit)
IPageCount = vRSHetaBata(geBL_8ecord8etProperty_PageGount)
ICurrentPage * vfl^etaData{geBI,_RecortfsetProperty_PageNijfflber)

end if
on error goto 0
if LerKlLongestFieldLenstt*} * 0 then
'- - 30
1LongestFieldLength = 30
end if
%>

, View_Authors.asp, GenericDisplayToolPageSofS.asp. HTML-, Web-. (custom) .

Web

359

, Web- . , , ActiveX- -
.
. ,
, .
, ,
. , .
. .
, ,
, .
Pubs, SQL Server, IIS. ,
.
(Johnny Papa) - MJM Investigations
(, ),
ADO, XML SQL Server. , VSLive.
datapoints@lancelotweb.com.

ADO XML:

DataManager


.
,
. ,
, +-,
Windows- ,
ADO- , XML.

: XML. , XML
, ,
? -
, /
-. ?
ADO- , , - ADOR,
. ASP-, , - ADO . , ,
XML, . ,
.
,
* MSDN Magazine. 2001. 8 (). . .

ADO XML;

361


.
, , +, Windows- , ADO- , XML. DataManager,
, -.
, DataManager . , , .
DataManager,
http://msdn.microsoft.com/msdnmag/code01.asp ( ). Windows NT 4.0
Microsoft Transaction Server (MTS) Shared Property Manager
(SPM). Windows 2000, +.

DataManager
, Visual Basic DataManager. .
ADO- , .
XML WebBrowser.
, -,
.
, ,
.
, (combobox), .
(grid) WebBrowser
. ( Visual Basic, .)
. . 1 Pubs (SQL Server),
ADO- .
2-D Array
. , . 1.
. 1, ( )
(ProductID, ProductName . .), . ,
ADO- , , .

362

. 1. SQL- ADO-

, . , DataManager , . , ,
.
XML, , . 2. ; XML
field, .
XML ( ).
Dai^Acreti I ifii I r;st ( mi
XML IbUi

clield 1*"0" Narae="F


NumeiricC3le-"255" Precisian--" 10" islcientity^True" }3rjLj!Jabie-:'False"
Uptlatisbiw='False" FixedL^tigth--"True1 l.onc)8iiiary="Felse"
<T'ield inde::-"I"

,- Type- = 202" Defined'iize^HD"


Precision-"255' isSrlsntiiy-'Fatse"

<t'ield lnde:s"2" Nsme-"Supp!lerID"

. 2. XML

ADO XML;

363

, , ,
DataManager.

DataManager
DataManager C_JDataManager.
ExecuteSQL SQL-. ExecuteSQL
, SQL, .
ExecuteSQL :

sSQL SQL-, ;

sINIAppName -, DataManager;

sINIFullPath -;

iDataReturnType , .

DataManager , - INI-, . ( DataManager


, - DataManager, .) INI-
, ,
( ) ADO. ( INI- TestBL.ini .)
sINIAppName sINIFullPath INI- (
.ini) , sSQL
SQL-, IDataReturnType , . DataManager ,
ExecuteSQL:
Public Enum enumDataReturnType
geDataReturnType_2DArray
geDataReturnType_ADOR
geDataReturnType_XML
End Enum


ExecuteSQL SetConnectionParameters (. 3),
INI-, -,
.

364

. 3.

SetConnectkmParameters

Private Sub SetConnectlonPararoeters(Optional sIHXAppName As Variant, .

Optional slNIFullPath As Variant)

With UKudtCormeetionPararaeters
'-
.sDataSource * SetlNIValueCn.oError, .sINIConnectlonSection,
"BataSouree", ., m.sIKlFullPath)
'-
. sDatabaseNairte * GetI8IValua(m.oError, .sINIConnectiofiSeetion,
"DatabaseName", m.sINIAppName, m.sINIFullPath)
'-
.eDatatmseProvider = GInt(GetISIValue(ai,oError, _
.sINIConftectionSection, "DatabaseProvider", _
ffl.slIAppName, ra.sIHIFuUPath
'
,sUserI& * GetIHIValue(m.oError, .sINICdnnectionSectiDn,
"AppIP", ., m.sINIFullPatft)
'-
.sPassword = GetINIValue(m.orror, .sINIConneGtionSection,
"AppFassword", .sINIAppNaiee, m.sINIFullPath)

GetlNIValue (. 4) , MTS SPM. , , INI- . GetlNIValue INI-,


, SPM . SPM , INI ExecuteSQL.
. 4. GetlNIValue
Public Function Set INIValue(Error As C.ErrorManager,
ByVal sSection As String, SyVal sKey AS String, ByVal slNIAppName _
As String, Optional sINIFtillPatfi As Variant) As Variant
Const sfft0C_NAME As String = isOW.NANE & ".GetlHIValue"
On Error GoTo Err
Const sPRpPHT_HANAGER As String ~ .
"HTxSpffl. SharsdPropert^roupManager, 1"
Dim oINI As CJNIHanager
Dim oSharedPropertyGroupManager As SharedPropertySroup%nager
Dim oSharedPropertyGrotip As SharedPropertySroup
Dim oSharedPropsrty As SharedProperty
Dim bGroupAlreadyExists As Boolean
Dim bPropertyAlreadyExists As Boolean

. . .

ADO XML:

365

. 4. GetlNIValue (.}
Diai vtfalue As Variant
"-
Set oSharedPropartySroupManager * ereateGb3eet(sPfi0PERTY_MAKASEfl)
Set GSbaredPropertyGroup * _
o8haredFroperty6roupHanager,CFeatePropertyGroup(sINIAppNarae &
"." & "IHIValues", LoeHSetGet, Process, bGrowAlreadyExists)
Set QSharetJProperty * eStiaredPrGpertyGroup.CreateProperty _
(sSection & "," & sKey, bPropartyAlreadyExlsts)
If bPropertyAlreaSyExists Then
SetlNlValue * oSftaredProperty.Value
Else
Set oIHI - New ELININamger
*- INI ,
If HasValue{sllFuXlPath) Then
GlNl.FilePath * sINlFullPatft & "\" & slHXAppName & Mni"
::;. End If
Walue = oINI. Value (sSection, sKey)
oSftared?roperty. Value - Walue
QetlNIValue = Walue
End If
'-
Set oIHI => Nottiifig
Set oSharedProperty = Nothing
St oSharedPropertyGroup = NotMRg
Set oSharedProperty - Nothing
Exit Ftmctlon

Err;
oError.Push Err, Err,Source, Error,

SQL-
SetConnectionParameters
, ExecuteSQL ADO- Connection. , Connection, ADO- . Connection (. 5).
. 5 . ADO ,
. ConstructReturnData
(. 6), .

366

. 5-
*- Select Insert
S^t oRs = ttew ADQDB.Recordset

With oRs
'- ,
"-
Set .ActiveConnection * oCn
.Cursorlocation * adUseClient
.CtirsorType = adDpenStatlc
.LockType = adLockBatchOptimlstic
'-
.Open Source:=sSQL, Options:=adCmdText
'-
Set .ActiveConnection * Nothing
btf With
'-
If ISataReturRType = geData8eturnType_ADOFt Then
Set ExecuteSQl * oRs
Else
&<eeuteSQl * eQHStruet8eturnQata(oRs, IDatsfleturnType)
End If

. 6.

ConstructReturnData

Private Function ConstructfieturnOata(8yRef oRs As ADOOB.Recordset, .


ByRef IDataReturriType As entra^itaReturnType) As Variant _
Const sPROC_NAH6 As String = iBsOBJ_NAH 4 ".ConstructReturnOata"
On Error SoTo Err
-
If Ia6bj8Ct(o8s) "Hiert
If oBs.State adStateOpen Then
Select Case lOataReturnType
Caae geOataReturnType_2DArray
If Hot oRs.EOF Tnen
ConstructReturnData * oRs.GetRows
Efid If
Case getotaReturnType_XHL
ConstructReturnBata * BundXHL(oRs)
End Select
End If
End If

. . .

ADO XML:

367

, 6. ConstructReturnData
Exit Funetion
Err;
ai.oError.pysh l-rr, Err.Source, Error, sPflQCJIAM
la.oirror.Raiselast
End Function

ConstructReturnData
GetRows
XML BuildXML.
BuildXML BuildXML C_XML, ADO- XML. , , ,
. XML
MSXML.DOMDocument.

XML
XML, BuildXML
<xml>, <metadata>,
. <metadata> <fields>,
<field>:
'- XML-
Set m.oXML.documentElement = m.oXML.createElementC'xil")
- With <xml>
With m.oXML.documentElement
'-
'- MetaData
,appendChild CreateNode("metadata")
'- MetaData Fields
.GhildNodes(lMetaDataTag).appendChild CreateHode("fields")

<field> Name, Type, IsNullable . . . 7 , <field>.


<data> <rows> . <rows>
<row> . <row> . <row> <fields>,
<field> ADO- . . 8 , XML-.

368

. 7. <field>
'- <fields>
With ,chlldNode3(lMetaDataTag).childNodes<lM8tal>ataFieldstag}
'- Recordset MetaData Field
Fuf ICol = 0 To 0RS.Fields.Count - t
"- Field
.appendCtiild CreateNodef"field")
'-'
With .chUdNodes(lG01),Attributes
'- Index
.setNamedltem CreateAttribute("Index", ICol)
'- Naiue
. setNainedlt&m CreateAttribute{"Name", ofis.Fieltfs(lCol).Hanie)

. 8.

XML

'- Bata
.appendChlld CnaateNodeCdata")
'- Data Rows
.etvildNodes(lDataTa(j).appendChild GreateNode("rows")
oRs.HoveFirst
'- With <rows>
With .childHodes(10ataTag),chiltfNodes(IDataRowsTae)
Do While Not ofls.EOF
IRow ofls.AbsolutePosition - 1
'- Row
.appsRdChlld CreateNodeC'row")
'- Index
.childNodes(lflow).Attributes. setNamedlteie
CreateAttribute("Index", 18ow)
'- Fields
.ctiildNodes<lftow).appendChlld CreateHode("fields")
'- Witti <fields>
With ,childNodes(Ifiow).childNodes(IDataRowsRowFieldsTag)
'- ^ Recordset Bata Field
For ICol * 0 To ofis.Fields.Count - 1
'- Field
.appendChiltf CreateMode{"field")

. . .

ADO XML:

, 8. XML (&)
- With <field>
With .childNodes(lGol)
'- Index

.Attributes. setNaraedltem CreateAttribute


("Index", ICol)
'- Name
.Attributes.setNamedltem CreateAttribute
("Name", oRs.Fields(lCol).Name)
.Text = Q8s.FiBlds(lCol).Value & ""
End With
Next
End With
ofls.MoveNext.
Ucp

End With
End With
8XHL - m.oXHL.xml
Set ofis = Nothing .
BulldXHl SXML
, XML .
. <metadata>, fields, <data>.
, .
XML; !

, . DataManager -, .
, Visual
Basic Pubs SQL Server. , .
(Johnny Papa) - MJM Investigations
(, ),
ADO, XML SQL Server. , VSLive.
datapoints@lancelotweb.com.

13-5947


Web-
Visual Basic
.NET ADO.NET

Visual Basic .NET ,


. , (threading model),
(custom classes) (data streaming).
, Web- .
, -,
(transparency) (opacity).

,
- , , . Visual
Basic .NET, ,
.
,
Visual Basic 6.0. HTML- Web,

* MSDK Magazine/ . 2002. 4 (). . .

Web-

371

, .
, robots.txt
, HTML-
. , Spider (),
, , Microsoft ,NET Framework. , Spider - Visual Studio
.NET, Visual Studio.
,
, Visual Basic 6.0.
(multithreaded object), (
) . .NET- .
, , Visual Basic .NET: ,
robots.txt, ,
, ,
(UI), . , .
, . , (parsing module)
, HTML- . ,
.
, ( ) .
, , HTML- (parsing instructors).


, Visual Studio .NET, Visual
Basic Windows Application, -

372

(Spider) . UI.
, , ;
.

Visual Basic. , Visual Basic .NET , ( FRM-), ,
, FormA FormB,
FormA
FormB. Visual Basic 6.0 ,
.
, ' ,
. 1, Options . 2.

. 1.

, .
Solutions Explorer, modUtils
; clsBoxOverride clsSpider.
.

Web-

373

QK

Cancel

Files

d FromParse

Files Included In Perse


:

'fi -

*.;<,:

. 2.

Options


,
, .
: , Web-. Spider
. 3.

clsSpidet
1

clsSpider
2

clsSpider
3

clsSpider
4

clsSpider
5

. 3.

Spider

Spider , .
,
. Spider
clsSpider, ,
.
HTML (
), -

374

, . eh Thread Status,

(file streams), , .
,
Thread,Abort .
(thread-safe code)* , , , .
, Visual Basic
,NET SyncLock.
SyncLock , ,
.
ehFinished frmMain ( http://
msdn.microsoft.com/msdnmag/code02.asp ).
,
m_sPages ( ):
SyncLock (m_sPages)
' , SyncLock
End SyncLock
Spider - RaiseEvent, , ( clsSpider), . SyncLock, m_sPages ,
.
SyncLock ,
, . SyncLock , m_sPages
SyncLock.
, , .
m_sPages , . SyncLock

. . .

Web-

375

. .
, SyncLock
,
. , .
. ehThreadStatus SyncLock
(progress bar controls). ( )
(listbox), . ,
SyncLock , . SyncLock , ,
.
, .
Process Thread,
,
ehFinished ,
Spider ,
m_sPages.
, ,
.
m_sPages ,
clsSpider; ,
, m_sPages m_sPagesDone.
, .
,
.


.NET Visual Basic (streaming). (stream) ,
,
-, . Spider
: (-) .
- . -
TCP/IP- -

376

, . , System.Net,
:
Imports

System.Net

Web-:
Dim myReq As HttpWebRequest = HttpWebRequest.Create(m_sURLToProcess)

m_sURLToProcess URL,
.
response:
Dim myResponse As HttpWeDResponse = myReq.GetResponse

response,
HTML- . , Web-. , , http://www.optigontech.net/, Web-
(http://www.optigontech.net/default.asp).
, , HTML-. :
m_sPageResponded = myResponse. ResponseUri.ToStringO

. , .

-, . ,

BinaryReader;
Dim iContentLengtn As Integer, sTotalBuffer() As Byte
tContentLength = myResponse.ContentLength
Dim br As New BinaryReader(myResponse.GetResponseStreamO)

:
ReDim sTotalfiyfferfiContentLength - 1)
Dim sBuffer() As Byte
m_iBytesRead = 1: iTotalBytes = 0
Do Until m_iBytesReatJ = 0
ReDim sBufferfiContentLength - 1)
Ti_iBytesRead = br.ReadfsBuffer, 0, iContentLength)
ReDim Preserve sBuffer(m_iBytesRead - 1)

Web-

377

If m_iBytesRead > 0 Then Array,Copy(sBuffer, 0, sTotalBuffer,


iTotalBytes, sBuffer.Length)
iTotalBytes += mj.BytesRead
RaiseEvent evThreadStatus(iTotalBytes, iContentLength,
m_iThreadIndex)
Loop

RaiseEvent .
, .
: ,
clsSpider. .:
Array.Copy(sBuffer, 0, sTotalBuffer, iTotalBytes, sBuffer.Length)

API- memcpy,
Visual Basic. . . , , , , API- DLL, .
If, . - :
. :

, . , , . clsSpider ,
, .
sTotalBuffer HTML- , .


, clsSpider ,
. Visual Basic .NET
, On
Error Goto . Try, Catch Finally Visual Basic .NET , Spider.
, ProcessRobots Web-
robots.txt 5, .
:

378

Try

Catch When Err.Number = 5


' , Robots.txt
Debug.WriteLirie("ProcessRobots: " & Err.Number & ": "
& Err.Description & " " & Err.Erl)
WriteErrorLog("ProcessRotiots: " & Err.Number & ": "
& Err.Description & " " & Err.Erl)
End Try

Try/Catch . ,
( , - Web- Unix
HTML-). StartThreading. Try.
- , . Catch :
Debug.WriteLine("StartThreading: " & Err.Number & ": "
& Err.Description & " " & Err.Erl)
WriteErrorLogC'StartThreading: " & Err.Number 4 ": "
& Err.Description & " " & Err.Erl)
, ,
Try/Catch :
Try
Try

For i = LBound(m_oThread) To U0ound(m_oThread)


If Not IsNothing(n_oThread(i)) Then m^oThread(i).Abort()
Next i
Catch
Debug.WriteLineC'StartThreading: " i Err.Number & "; " &
Err.Description & " " & Err.Erl)
WriteErrorLogC'StartThreading: " & Err.Number & ": " & _
Err.Description 4 " " & Err.Erl)
End Try
End Try

Visual Basic .


Try/Catch, ,
. , ,

Web-

379

, , , ,
, , .
WriteErrorLog modUtils.vb.
-.
:
Dim sErrFileName As String = Application.StartupPath 4 "\Spider_"
& Format(Now(),"yyyMMdd") & ".txt"
Application. Startup Path:
App.Path, Visual Basic.
Text Writer,
:
Dim wt As TextWriter = File.AppendText(sErrFileName)


TextWriter,
:
TextWriter.Synchronized(wt)

TextWriter:
wt.WriteLine(Format(Now, "hh:mm:ss tt") & "
wt,Close(}

" & sErrString)

,
, . TextWriter.Synchronized .


Spider -,
SQL Server . , ,
Microsoft Access. :
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
,
:

380

Public g_sConn As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data


Source=" & Application.StartupPath 4 "\spider.fndb"

. , : drGetReadOnly ( DataReader ) lExecuteSQL (


SQL- ).
drGetReadOnly lExecuteSQL . 4 . 5 . : drGetReadOnly ExecuteReader OLE- DBCommand, a lExecuteSQL
ExecuteNonQuery.
. 4.

drGetReadOnly

' DataReader
Public Function drGetReadGnly(ByVal sSQL As String) As OleDbDataReader
Try
1:.
2:
3:
4:
5:

Bint cn As New QleDbCortnection(g_sCQnn)


cn.OpenO
Dim cind As OleOSCoBintand = Hew OleDbGommand(sSQt, cn)
Dim dr As QleDbDatafleader = cmd.ExecuteReader()
Return dr
Catch
'HsgBoxfErr,Number & ": " & Err.Description & " " 4 Err.Erl)
10:
Debug.Wr:LteLine("dr6etReadOnIy: " & Err.Number & ": " & _

Err.Description & " " & Err.Erl)


500;

WriteErrorLogC'drGetReadGnly; " & Err.Rtfffiber & ": " &


Err.Description & " " & Err.Erl)
End Try:
End Fynctiorv

. 5.

(ExecuteSQL

SQL-
Function ISxecuteSQLCByVal sSQi. As String) As Long
Try
Dim en As New OleDbConnection(g^sGonn)
cn.0pen()
Dim end As OleDtiCasimand = New 01eDbCotmand(sSQLt cn)
Dim IRecsAffected As Long = cmd.ExecuteNonQueryO
cn.CloseC)
Return IRecsAffected
Catch
"KsgBoxCErr.Number & "; " & Err.Description & " " & Err.Erl)
10:
Debug.WriteLineC'lExecuteSQL: " 4 Err.Nufliber & "; " & _

. . .

Web-

. 5,

381

(ExeeuteSQL ()

Err.Description 4 " " & Err.Erl & vbCrLf & sSQl)


WriteErrorLogC'lExeeuteSQLi " i Err,Number & ": " 4
Err.Description & " " & Err.Erl & vbCrLf & sSQL)
End Try
End Function
500:

ItemData?
Visual Basic 6.0 ItemData (listboxes)
(comboboxes)
. .
, (collection)
. Visual Basic .NET ,
.
Visual Basic .NET (. 6). clsBoxOverride ToString, ,
, clsBoxOverride
New, .
, 6. clsBoxOverride

clsboxQverride

, ItemData (
Visual Basic .NET),
,
.
, .
: New

Option Explicit On
Public Class clsboxGverride
' ItemData
Private m_sSiteName As String
Private m_sSiteURL As String
Private m_iSiteIti As Long
Puulic Sub New(Byval sSiteName As String, _

,. . .

382

. 6.

clsBoxOverride

ByVal sSSteURL As String, ByVal ISitelD As Long)


BLsSiteNarne = sSiteName
m_sSlteURL = sSitem
m_iSiteID = iSitelB
End Sub
Public Property SiteNaroeC) As String
Set(ByVal Value As String)
ie_sSitePfame == Value
End Set
Get
Return m_sSiteNarae
End Set
End Property
Public Property SiteL/RLO As String
SeUByVal Value As String)
flLsSiteURL = Value
End Set
Get
Return Bi_sSitel/Rt
End Get
End Property
Public Property SiteJBO As Long
Set(ByVal Value As Long)
flt_iSiteID Value
End Set
Set
Return m_iSiteID
End Get
End Property
Public Overrides Function ToStringO As String
Return H]_sSiteNauie
nd Function
End" Class


Items.Add. , . * ToString , . , :
lstSites.Items(lIndex).SiteURL.ToStringO

Web-

383

, (
clsBoxOverride): Set Get ;
Public Property SiteNameO As String
Set(ByVal Value As String)
m_sSiteName = Value
End Set
Set
Return m_sSiteName
End Get
End Property

Spider
MouseMove, IstSites URL, .


( , ). Visual Basic .NET (transparency)
(opacity) .
-,
, , ,
. - Visual Basic .NET . ,
. -, , TransparencyKey
, . ,
(. 7): -
.
,
. Opacity
:
' ,
'
.Opacity =
Me.ShowO
For i = 1 100 Step 10
Me.Opacity = i / 100

Application.DoEvents()
Next i
He.Opacity = 1

384

ment This is a les! document. This is a lest docunenl Th


merit. This is a Issl document This is a lesl document. Th
ment This is a test document. This is a test document, Th
! Jjjjjtetf lafiLita rumen! This is a test document. Th
^
This \^s test document Th
jjn^hiyrSS ^* jSfJf jfyjgfbtffnsnl Th
nsnl Thi/*& tttlVc-'ytea^ffiftp'ICtetu'rieril Th
ment. ThJs is a test Ibcument./his i; ! document Th
ment. F*s is a t?st document*Fhis is test document Th
nt. This is a t?si document. This is a test document Th
nen? This i? test document. This is a test document. Th
ment This is a last doc-! This is a test document. Th

. 7.

Opacity 0 (
) 1 ( ). , , Opacity 1/10 ,
.
Application.DoEvents. , .
.

Spider
, .
Spider Yellow Pages Web.
, . Spider Web- (,
, ).
.
Visual Basic .NET . , .
, III , Visual Basic .NET.
!
(Mark Gerlach)
Optigon Technical Associates, Microsoft {Microsoft Solution Provider).
MCSD MCDBA. gerlachm@optigon.net
mgerlach@mostwantedsoftware.com.


.NET*

, ,
ADO.NET, +. ,
.

,
Web, Windows. ,
Visual Studio .NET Microsoft .NET Framework. !
( 2002 .) +,
MSMQ .NET (http://msdn.microsoft.com/msdnmag/
issues/02/02/basics/basics0202.asp). ,
,
+
ADO.NET. .

.NET, ?
,
?
! -. .
MSDK Magazine/ . 2002. 2 (). . .

ADO.NET. , Order Derails


Northwind.
, , . SQL Server
SQLClient. , OLE
, .
, , ADO.NET, . , ,
, Windows-,
.

DBStuffADONET (. 1). ,
. ,
. , ,
.
,
SqlConnection Sql Transact ion. .
RunSQLWithDataSet, 2002 . (http://msdn.microsoft.com/msdnmag/issues/02/04/basics/basics02Q4.asp). ,
DataSeL SQL .
, , , . OpenConnectionTrans SqlConnection .
, BeginTransaction, Transaction Current :
Public Sub OpenConnectionTransO
ConnectionCurrent = New SqlConnsction(sConnectionString)
ConnectionCurrent.Open
TransactionCurrnt = ConnectionCurrent.BeginTransactionO
End Sub

, OpenConnection:

.NET

38?

Public Sub OpenConnectionQ


ConnectionCurrent = New SqlConnection(sConnectionString)
ConnectionCurrent.Open()
End Sub

, :
Public Sub Commit!ransaction()
TransactionCurrent.Commit {)
End Sub

:
Public Sub Rollback!ransactionO
TransactionCurrent.Rollback()
End Sub

, . :
Public Sub CloseConnection()
If ConnectionCurrent Is Nothing !hen
Exit Sub
End If

If ConnectionCurrent.State = ConnectionState.Open Then


ConnectionCurrent.Close()
ConnectionCurrent = Nothing
End If
End Sub
, ,
?
RunSQLN on Query. SqlCommand, Connection (ConnectionCurrent), Transaction (TransactionCurrent). ExecuteNonQuery SQL-,
, (. 2).
RunSQLScalar, SQL- . ,
, , Unit Price - .
,
. , , .
. , ,

388

. - Windows
.
. 1.

DBStuffADONET.vb

Imports System.Data.SqlCllent
Public Class DBStuffADONET
Private sCormectionString As String = _
"Server=localfcost;uid=sa;pwd=;database=NortnWind"
Private ConriectionCurrent As SqlConnection
Private TransactionCurrent As SqlTransactian
Public Sub NewQ
End Sub
Public Sub NewCSyVal sNewCormectionString As String)
If sNewConnectioflString <> "" Then
sConnectionString = sNewConnectionStrinfl
End If
End Sub
Public Function HunSQLWithDataSet(ByVal sSQL As String, _
Optional ByVal sTableName As String ~ "Tablel"} As DataSet
Dim oDataSet As New DataSetO
Dim oOataAdapter As SqlClient.SqlBataAdapter
' DataAdapter
oQataAdapter = New _
SqlClient.SqlDataAdapter(sSQL, sConnectionString)
1
DataAdapter
oOataAdapter. Fili(oDataSet, sTableNaeie)
oDataAdapter * Nothing
'
Return oOataSet
End Function
.
Public Sub OpenGonnectionTrans(-)
ConnectionCurrent * New Sqieonnection(sConnectionString)
ConnectionCurrent.OpenO
'
TransactionCurrenta ConnectionCurrent. BeginTra/isactionQ
End Sub

Public Sub OpenConneetionO


ConnectionCurrent = New SqlConnection(sConnectionString)
ConnectionCurrent.Open()
End Sub
, . .

.NET

, 1.

DBStuffADONET.vb

()

Public Sub CoiBinltTransactionO


TransactionCu rrent. Commit()
End Sub
Public Sub RollbacKTransactionO
TransactionCurrent.Rollback)
'End Sub
Public Sub CloseConnectionO
If ConnectionCurrent Is Nothing Then
Exit Sub
End If
If ConnectionCurrent.State ConnectionState.Open Then
ConnectionCurrent.Glose{)
CormectionCurrent ~ Nothing
End If
End Sub
Public Function RunSQLHonQuerytByVal sSQL As- String) As String
'
'
Dint cmdLocal As New SqlCommandO
cmdLocal.Connection = ConnectionCurrent
cmdLocal.Transaction = TransactionCurrent
Try
cmd Local. CommandText = sSQt
cmdLocal. ExecuteNonQueryO
Catch exc As Exception
Return "Error occurred " & exc.Message
Finally
End Try
End Function
Public Function RunSQLScalar(ByVal sSQL As String) As String.
'
'
Dim cmdLocal As flew SqlCommandO
Dim bConnectlonAlreadyOpen As Boolean = True :
Dim sTeffip As String
If ConnectionCurrent Is Nothing Then
bConnectionAlreadyOpen False
ilself ConnectionCurrent.State <> ConnectionState.Open Then
bConnectionAlreadyOpen = False
End If
If bConnectionAlreadyOpen = False Then
. . .

390

. 1.

DBStuffADONET.vb
bConnectionAlreadyOpen = False
OpenConnectionC)
End If
cmdLocal.Connection = ConnectionCurrent

Try
cmdLocal.CommandText = sSQL
sTemp = CStr(cmdLocal.ExecuteScalar()}
Catch exc As Exception
sTemp = "Error occurred " & exc.Message
Finally
If Not bConnectionAlreadyOpen Then
ConnectionCurrent.Close()
ConnectionCurrent = Nothing
End If
End Try
Return sTeuip
End Function
End Class

. 2.

RunSQLNonQuery

Public Function RunSQLNonQuery(8yVal sSQL As String) As String


'
'
Dim cmdLocal As New SqlComraandO
cmdCocal.Connection * ConnectionCurrent
cmdLocal,Transaction = TransactionCurrent
Try

cmdLocal.CommandText = sSQL
cmdLocal,xecuteNonQuery{)
Catch exc As Exception
Return "Error occurred " & exc.Message
Finally
End Try
End Function
. Windows-. . ,

.NET

() .
. Quantity Discount 1 ,15 .

New Order tins items

. 3.

ADO.NET

, Insert ADO.NET Order Details .


. , Orders (cboOrders)
Products (cboProducts), . - , .
,
.
cboProducts.Visible False True
, . -
. , , cboProducts Panel.
Panel (pnlProduct), cboProducts cboProducts;
, cboProducts. . . . 4.
Orders cboProducts.
(, txtProductName_l), .
, (http:/
/download.microsoft.com/download/msdnmagazine/code/May02/WXP/ENUS/Basics0205.exe). ,
. Insert ADO.NET
, cmdlnsertADONet Click.

392

. 4.

:
Dim sSQL As String
Dim sStatus As String = ""
Dim sOrderlD As String

CloseConnection. ,
, , :
oDB.CloseConnection()
:
oDB.OpenConnectionTrans{)
: , , , :
IblMessage.Text = ""
If txtProductName_1.Text <> "" Then
sOrderlD = cboOrders.SelectedValue
If sOrderlD = "" Then
IblMessage.Text = "You must select an order to add line items to"
Exit Sub
End If

InsertOrderDetail:

.NET

393

' 1-
sStatus = InsertOrderDetail(sOrderID,
txtProductID_1.Text,
txtUnitPrice_1.Text,
txtQuantity_1.Text,
txtDiscount_1.Text)
sStatus (
, txtProductID ). , InsertOrderDetail:
2-
If sStatus = "" And txtProductID_2.Text <> "" Then
sStatus = InsertOrderDetail(sOrderID,
txtProductID_2.Text,
txtllnitPrice_2.Text,
txtQuantity_2.Text,
txtDiscount_2.Text)
End If

,
, .
Insert Order Detail , . sStatus - , , , RollbackTransaction.
IblMessage:
/
If sStatus <> "" Then
IblMessage.Text =
"Rolled back transaction due to error " & "on row " & " N - " & sStatus
oDB, RollbackTransactionO
Exit Sub
End If

, , , CommitTransaction,
. IblMessage , , .
oDB.CommitTransactionO
IblMessage.Text = "Line items inserted ok"
oDB.CloseConnectionC)
InsertOrderDetail . :
Function InsertOrderOetaiKByVal sOrderlD As String, _
ByVal sProductID As String, ByVal sUnitPrice As String,
ByVal sQuantity As String, ByVal sDiscount As String) As String

394

:
Dim sSQL As String
Dim slnsertStatus As String
SQL- , :
sSQL = "INSERT INTO [Order Details] " _
"(OrderlD, ProductID, UnitPrice, Quantity, Discount)
sSOL &= "VALUE$<" & sOrderlD & "," & sProductlD & "," _
& sUnitPrice ft ","
sSQL 4= sQuantity & " , " & sDiscount & ")"

"

Try/Catch RunSQLNonQuery, SQL-. : slnsertStatus


, .
Catch:

Try
slnsertStatus = oDB.RunSQLNonQuery(sSQL)
If slnsertStatus <> "" Then
Throw New System.Exception(sInsertStatus)
End If
Catch exc As Exception
Return exc.Message
End Try
End Function
. . , ADO.NET , .
. , , . ,
, ADO.NET , , . , ADO.NET , , ,
.
( )
basics@microsoft.com.
(Ken Spencer) 32 Tech (http://
www.32X.com), ,
Microsoft.

II

ASP.NET
HTTP-
ASP.NET

Web-

Web-

ASP.NET


2003 .
-
www.ITbook.ru


.; (095; 142-0571; ./ (095) 145-4519;
e-mail; info@4usedit.ru; http:// www.ru sedit.ru

.: [095] 142-0571: (0951145-4519


e-mail: info@ru5edrt.iu: http:// www rusedn.ru


(Training}
Microsoft Press -

,

.

Ri
.: (095] 142-0571; ./ (095)145-4519;
e-mail: mfo&fsedit.ru; tittp:// www.rjsedit.ru


:


, 38,
.: (095] 778-7269
6 -- . , 6,
.: (095) 928-3567
. , 8,
.: 1095) 290-4507
-, 40,
.: (095) 137-6019
" . , 28,
.: (095) 238-5001
" -, 7S,
. (095) 152-4511
13, . 1.
. (095)150-6917
" . 2- -, 54.
.: (095) 978-5017
" . . 8,
.: (095) 229-6483
-:
, -., 28
.: (812)318-6402
. -., 20
.: (812)312-0563.314-7184

-., 57, .: (812) 273-5053
, . . 2,
.: (812) 164-6565, 164-1413
, -., 13
.: (812) 312-6734
...
.:(812)247-1483
-
.: (812) 567-7025
:
,
. , 12,
,:(3432)59-4200
:
" ,
-. -14,
. 2-
:
000 Ton-, : (3832) 36-1026

():
.
. .: 8-327-908-28-57, (3272) 76-1404

():
000 -
.: (+1038044) 269-0423
,
.: (+1038044) 268-5346

liiitirm InfipmsfrDft S

*-^1^|^|$*.



MSDN Magazine/


Web: ,
Web.
XML XML " . " (XML Schema, 3511. Web . .). dteerw *.1.
ASP
ASP ASRNT.


,
',
ADO.NET.

I'SOAR !'-8,', NET Fram

.NET -
.NET .
'. ' '
, .

"
:


Microsoft,
.


,
Microsoft."
,
Microsoft
(MSDN Magazine/ ;
1, 2002 .)


MSDN Magazine/ - ~
w ww.microsoft.com/irii5/msdn/magazitm



.
-:
" : '/'
' :=
~- -!?11 ; .
,
. ; :
*8
- ,
.
-.
**: ,
++,

www.ITbook.ru

H t l H l H

1/!
iqHHBtf uAioo"'
f%

13N'OQV
euizBgeiAi MQSW Ajejqn MQSVi
!

111

Оценить