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
ISBN 5-7502-0234-8
, 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
Microsoft ADO.NET
. , ,
.NET
ADO.NET:
81
ADO.NET
.NET Data Access Framework
102
122
ADO.NET
ADO.NET-
133
.NET
152
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/ , , .
, ,
.
.
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-.
,
.
.
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
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 :
(, , ..),
.NET, .
.NET
13
, 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
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
.
:
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 .
Microsoft ADO.NET
20
, ,
Profiler, SQL Server,
Performance Monitor Microsoft Windows 2000.
Profiler .
1.
4.
Run, . Audit
Login , Audit Logout
.
Performance Monitor .
1. Start Programs Administrative Tools | Performance Performance Monitor.
2. , , Add Counters.
3.
4.
User Connections.
5.
Add, Close.
.NET
21
SQL Server
.NET Data Provider.
,
. , , .
, ,
, ( ); , .
Windows
SQL Server
Windows, .
,
( Windows), SQL Server.
, .
SQL Server Windows , .
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;
Windows (http://rnsdn.microsoft.com/library/en-us/dnbda/
html/#daag_usingwindows registry);
(http://msdn.microsoft.com/library/en-us/dnbda/
html/#daag_usingcustomfiles);
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),
.
.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.
. , UDL-
.
.
UDL- .
. UDL- . NTFS,
, .config.
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, ,
.
. .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
.
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;
, 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
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
, ;
,
, 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
\
// , 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 );
)
!
,NT
33
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 )
,
. , .
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
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 ), .
SqIDataReader
SqIDataReader, ExecuteReader SqlCommand, :
,
;
, ;
, DataSet;
, , lEnumerable;
;
, (binary large objects, BLOB). SqIDataReader BLOB- .
BLOB .
(BLOB).
SqIDataReader .
, .
Close SqIDataReader .
~ , ,
SqIDataReader, ExecuteReader mandBehavior.CloseConnection. , , SqIDataReader,
Microsoft ADO.NET
40
,
.
,
, Cancel
Close . Cancel ,
.
Close , , ,
, .
ExecuteReader
SqlCommand, Close
.
, , SqlDataReader, . SqlDataReader .
XmlReader
XmlReader, ExecuteXmlReader SqlCommand, .
XML,
, DataSet, .
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
;
, ,
ExecuteReader SqlCommand ConimandBehavior.SingleRow. , OLE DB
.NET Data Provider, . CommandBehavior.SingleRow IRow (
), IRowset. SQL
Server .NET Data Provider .
, , SqIDataReader , .
SqIDataReader .
. ,
(credit rating) .
, DataSet DataTable.
, , : . , Web-
, ,
. .
.
.NET
43
SqlDataReader.
ExecuteScalar ,
, .
, .
, , ,
,
( 100 200).
, ExecuteQuery,
/ , , ,
,
, , ExecuteScalar, .
ExecuteScalar .
, , , .
,
-
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 .
46
Microsoft A.DO.NET
SQL Server , 1433 , :
, + 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- .
BLOB .
.
, ( 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)
. ,
, . , , .
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.
AutoComplete, .NET
.
false
( ). , true, . ,
, , .
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 :
.
void SomeOtherMetliodO
{
try
//
ContextUtil.SetComplete(); //
I
catch (SqlException sqlex)
{
LogExceptionf sqlex );
//
ContextUtil.SetAbortO; //
// ,
//
>
finally
{
//
.NET
59
false
, ,
. , ,
Boolean , . , .
(data paging) , . ,
,
; , / /.
.
, :
, ;
,
. , -
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
GO
, ,
last Product ID
.
, , , , identity-
.
,
, ( ), .
.
Coll
12
13
\
\
\
2
2
I
1
...
X
W
X
AS
int
.NET
03
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
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")]
// 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
{
3 -5947
66
Microsoft ADO.NET
4.
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
{
.NET
67
SqlDataReader, ExecuteReader
SqlCommand.
4.
5.
, Close.
XmlReader
SqlCommand XmlReader, XML- . ( )
XML. SQL Server 2000
SELECT FOR XML.
.
public void RetrieveAndDisplayRowsWithXmlReaderO
{
68
Microsoft ADO.NET
xreader.CloseC);
}
catch
{
throw;
}
finally
{
conn.Close();
}
:
.
CREATE PROCEDURE DATRetrieveProductsXML
AS
XML XmlReader, .
1.
SqlComraand , XML (,
FOR XML SELECT). SqlCommand
.
2.
ExecuteXmlReadcr SqlCommand
XmlTextReader .
XmlReader, ,
XML- .
3. Read XmlTextReader.
, . , Products Nortlrwind.
.NET
69
// 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.
5.
6.
.
CREATE PROCEDURE DATGetProductDetailsSPOutput
eProductID int,
@ProductName nvarchar(40) OUTPUT,
@UnitPrice money OUTPUT
AS
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.
ExecuteScalar
ExecuteScalar ,
. / ,
ExecuteScalar .
, .
72
Microsoft ADG.NET
3.
ExecuteScalar. ,
,
.
4. .
.
CREATE PROCEDURE
ProductID int
AS
LookupProductNameScalar
.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.
3. .
4.
ExecuteNonQuery SqlCommand.
5.
6.
Value SqlParameter.
74
Microsoft ADO.NET
.
CREATE PROCEDURE LookupProductNameSPOutput
SProductlD int,
@ProductName nvarchar(40) OUTPUT
AS
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.
4. .
5.
ExecuteNonQuery SqlCommand.
6. .
7. Value SqlParameter.
.
CREATE PROCEDURE CheckProductSP
isProductlD int
AS
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
Transact-SQL
, Transact-SQL.
CREATE PROCEDURE MoneyTransfer
@FromAccount char(20),
taToAccount char(20),
^Amount money
AS
BEGIN TRANSACTION
-
UPDATE Accounts
78
Microsoft ADO.MET
END
-
UPDATE Accounts
IF @@RowCount = 0
BEGIN
.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
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-;
,
, .
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:
<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
'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:
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
//
//__...., _______ ..
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
SqlService (. 4).
, .
ArrayList , AddParameter
.
,
SqlService. , / .
. 4.
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/
V/ ( - )
V/ ;
'//
Microsoft ADO.NET
92
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
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
'//
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
'//-
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
'//-
// -
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
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};
100
Microsoft ADO.NET
RunProc, DataSet, , , ,
void:
public void RunProc(string sProcName)
, WebForm.aspx
(. 13). ( Visual Basic
#.) DataGrid,
HTML.
F-gyortes
Vcots
He p
Cnndirfienrs
Confections
MeaLJPuJtri/
;S
Seafood
Prepared riieuU
Dried fruit and bean (urd
'' and Hih
-lie
1J090
. 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*
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 .
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
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 -
. , , 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 (-
109
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()
//
//
//
//
//
//
//
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.
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
{
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, , ,
. 5. IDataReader IDataRecord
// IDataRecord
public int FleldCount
public object this[string nafae];
public object this[int 1]
113
12,4
Microsoft ADO.NET
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-
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
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 ,
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 -
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.
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
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
. . .
Microsoft ADG.NET
126
. 2. DataSet ()
//- SqlCommand DataAdapter DataSet
//
//- ()
//
oOs.Tables["OrderPetail").ColuiBns.AtM("ExtendedPrice",
typeof(tieeimel), "UnitPrice * Quantity"};
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
/ /
- - . ' -
//-
//
. . .
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;
I/
//- SqlCommand OataAdapter DataSet
//
SqlOataAdapter oDA = new SqlDataAdapter(oSelCmd);
oDA.FillCoDs, "OrderDetail");
//- DataTable
//
'_
//- 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)");
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");
132
Microsoft ADO.NET
//- , $1000
ADO.NET-
, ADO.NET.
- DataSet DataTable,
ISerializable.
, ADO.NET,
XML-.
.NET- , ,
ADO.NET .
34
Microsoft 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, . , -
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
XmlWritettode mode)
. . .
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
{
OataTable dt = CreateTefflpTable(dv);
WriteDataTable(dt, outputFile, aode);
DataTable , , DataView.
, . , XML
WriteDataTable.
j_4Q
Microsoft ADO,NET
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
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);
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
{
Microsoft ADO.NET
144
. 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];
145
146
Microsoft ADO.NET
JSerializable
, DataTable ISerializable.
. ? ISemlizable, .
DataTable
,
, .
, ISerializable
ADO.NET.
BinDataTable ( ) , ,
ESerializatele]
class BinDataTable : DataTable, ISerializable {
GetObjectData , DataTable, ;
. : BinDataTable. , , MSDN Magazine .
.
, : DataTable GhostDataTableSerializer.
Load.
(colNames colTypes) , DataRow ,
.
ADO.NET-
147
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
//
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.
Pc. 8.
. . .
.-
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/
.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
.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
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
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
Try
'
.NET
163
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
IDENTITY INSERT
, , , : IDENTITY SQL- INSERT?
, ,
, . SQL Server,
IDENTITY, SQL- , ;
SELECT @@IDENTITY
SQL-, :
INSERT
, . INSERT , :
INSERT INTO Products (ProductName) VALUES ('Chalk')
SELECT ^IDENTITY
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
, , . , .
-, ,
(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
, . ,
.
, .
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
, 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
.
. 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,
f.sHonth
CROSS JOIN , . , ,
CROSS JOIN, WHERE, DISTINCT GROUP BY, ,
178
(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-*
18G
. , ,
, . ,
, , ,
-, ,
. ,
.
, ,
DTS (Data Transformation Services), SQL Server 2000.
. ,
, (workflowdriven). , DTS .
DTS- (DTS package) , , , .
(steps)
(tasks), . , , . , ,
. DTS Designer,
.
VBScript JScript , , DTS-. , :
ADO-, ,
(recordsets) ;
, -;
, , DTS ActiveX-;
DTS.
-
, 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
. . 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.
, char 75 .
. .
183
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
. .
. 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
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. . .
. 6.
BookSales
-,/. -.d
. 7.
186
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 = ' '
187
, 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
):
4.1
]S .*rs Con^anl
V^.iB^.Adiv^-.rn
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.
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'"
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
, :
myRecordset.Open mySQLCmdText, myConn
, , :
Set ExecuteSQL = myHecordset
ADO,
.
FormatRecordset
ADO HTML- ( ).
, . .
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
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") =
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
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
.
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
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
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
1
SQL Server
SQLServer.Connect strServer, strlogin, strPassword
End If
,
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
errHandler:
HsgBox Err.Number & " " & Err.Description & " <" & _
Err.Source & " " & Err.LastDUError & ")", _
vbQKOnly, "SQL Server Service Manager"
nd Sub
199
200
Registry Configuration
Registry , , ,
master . , SQL
Server.
Configuration ConfigValue.
40 ,
sp_configure. , - . ,
:
Dim cv As SOLDMO.ConfigValue
With SQLServer.Configuration
.ShowAdvancedOptions = True
,
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
Recordset
For collnitex = 0 To UBoijnd(cols)
rs.Fields.Append RTrim$(cols(colIndex)), adVarCtiar,
cfres.ColurflnMaxLength(colIndex + 1)
Next
. . .
. . 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
. 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
SQL Server
205
. 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
. 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
* SQL Server
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
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
. ,
. 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
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
. 10.
, ..,
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
, , :
. 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
,
, .
. (
) .
- , ,
. 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-
-, .
216
aotryni
s KpSH.BHI
[
$*1
iSKSener
. 1.
XML
Web-
, , Web, . Northwind, SQL Server. , .
Web- ,
login.asp (. 2). Employee ID (1-9)
Log In. Employee Detail ( -
Web
217
),
, (. 3).
http://myserver/
Address'!
http;//rnyserver/lagin, asp
. 2.
http://niyserver/empdetai
Edit
Employee Information:
Ms. Nancy Davolio
Sales ^Representative
Create New Order
Here is a list
Order ID
11077;,
071
\ 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
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
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-. .
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
, ,
.
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.
222
SPNarae . , . ,
. , ,
.
SPNanie ;
( ) , .
Parameters cAdapter, .
Parameters ( )
cParameters. .
cAdapter , CallSP:
Public Function CallSP(ReturnType As ReturnDataEnum) As String
daParameters ,
, daRecords
. ,
.
cParameter ,
. cParameter
Parameters cAdapter. Parameters . , EmployeelD:
oAdapter. Parameters. Item("EntployeeID"). Value = lEmployeelD
, , SPName cAdapter,
.
cParameters
cParameter.
Web
223
:
strSPName ( ),
m_objParmCol ( cParameters cAdapter),
ReturnType ( ReturnDataEnum)
.
XML-, , ,
XML-. DataAccess.vbp,
Visual Basic spda.dll.
, cAccessor, : GetDataXML ParameterXML.
224
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
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>
, 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
, 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< ,
^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
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
,
, -
Web
. , ,
XML,
. , , .
XML, .
, spdatest.exe. . 7. Northwind_SQL. , , , ,
Stored Procedure Name.
. , , . , , . :
Customer ListCustomers;
. 7.
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, .
ADO-. :
' , cmd Dim
' ADOOB.Command
' Set. ,
234
. -, - , , , . ,
. , Parameter, . XML- ,
.
.
(, ).
SQL Server ,
1.
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.
236
DLL +, .
1.
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.
2. spdaad.dll, ,
RegSvr32.exe. DLL ,
, DLL, , DCOM.
DLL +, ,
DLL , MSI
Installer .
-.
spdamid.dll .
1. MiddleTier.
2. spdamid.dll, ,
RegSvr32.exe.
Web
23?
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
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
Windows-, . SQL Server CE 2.0 , , ,
, , , .
, Windows CE.
, Pocket PC () Handheld PC (HPC).
Bluetooth 802.11, .
Windows CE . . ,
, .
. , -
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)
()
, ,
, ,
( , 16-32 ).
242
. ,
. , .
, . 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
243
. 1. ;
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
. . .
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;"
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, -
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
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
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.
248
. 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, ,
, .
SOL Server
Client Agent
SGI Server
IIS
SQL Server CE
service Agent
Hi
out
.out
. 5.
250
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 #.
, , 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
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
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:
::::::::-:::::;::
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
DBSync Replication
.
SQL XML-. SQL Server. Synchronize
(. 9).
. DBSync SQL Server
254
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();
255
+
+ oErr.Message);
+ oErr.NativeError);
+ oErr,Source);
: " -f iNumPer);
'* sSrrPar);
HessageBox.ShQfcKoStr&ld.ToStrifigO,
oStrBld.RemoveCO, ostraid.l
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)};
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
, CF. , - ,
.
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
. , ,
- , , -
.
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
, , , 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.
. 1.
264
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
, . . . 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
.
Transact-SQL, , , . , .
, .
, ,
, (. 4).
, 4.
. , , ,
, ,
.
,
, , , . (notification distributor)
, ,
,
,
, .
(. 5).
269
,
:
.'. I 1
** 1 &
1 & I ; I
. 5.
, (threads).
, ,
. ,
, ,
, , (digest notification). , , (aggregator),
, ( ). , , .
, (content formatter), ( , ,
) , .
, (locale), ,
, , .
. , , .
SMTP;
270
. ,
, .
(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
,
IBuySpy . : . ADO Visual Basic
for Applications (VBA), - , . 2.
-
, VBA-. :
277
: Value Parameter
Variant, ModulelD GetAnnouncements Integer.
,
GetAnnouncements, . - , (disconnected recordset)
Command.
, .
, Visual Basic
SQLDMO .
XML- ,
XSLT-.
278
- 3.
AnnouncementsDB.GetAnnouncements
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;
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
{
280
PortalDatabase.GetAnnouncements [System.Data.DataSet]
System.Data.SqlClient.SqlConnection connection
System.Int32 moduleld
SqICommand
}
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#
( )
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
Tinylnt
Uniqueldentifier
System.Byte
float
System.DateTime
short
decimal
string
DateTime
byte
System. Guid
Single
System. Guid
Date
Short
Decimal
String
Date
Byte
System, Guid
, . .
. 1.
()
SqIDbType
System
C#
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.
, 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
-
,
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)
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
. 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)
{ ... }
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
.
, , (direction) SqlParameter. ,
, . #
( ), ( ref) (output only) (
out), ParameterDirection.Input, ParameterDirection.InputOutput ParameterDirection.Output. Visual Basic .NET , ParameterDirection.Input (
291
Title
tHoreLlRk
@MobileMo relink
ExpireOate
^Description
nvarchar(IQQ),
nvarcHar(150),
nvarchar{150),
nvarchar(15Q), .
OateTime,
nvarchar(20QO),
int OUTPUT
AS
(
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;
. 11.
Class Sample
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)"
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
object,
ooject)
Il_006f:
//000022:
//000023:
End Sub
IL_0070:
II 0071:
ret
NULL-
, NULL-.
NULL- , -
int # Integer Visual Basic .NET.
System.Data.SqlTypes. , Pubs :
CREATE PROCEDURE [GetEmployeesByJob](rjob_id SMALLINT = NULL) AS
SELECT *
FROM [employee]
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);
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
. , ,
SQL- (. 14), #- , . ,
. , ( , ).
, .
. 14.
SQt- #-
set noeount on
300
. 14.
SQL- ...
()
froffl
dtjQ.syscolufftns
where
c.id = oid
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
. 14.
front
SQt- ...
301
()
dbo.syscolumns
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
[256
Results ( Text
. 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
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'
. , , 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");
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
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.
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
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.
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
' , ,
' 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 {
).
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
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
.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
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
. 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
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">
___,._
. , .
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
. . .
Web
355
. 10. ()
. ComroandText - sProcKame
End With
Set oRs * CreateQbject("ADQDB.Recordset")
With oRs
. 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
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
%>
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
. 2. XML
ADO XML;
363
, , ,
DataManager.
DataManager
DataManager C_JDataManager.
ExecuteSQL SQL-. ExecuteSQL
, SQL, .
ExecuteSQL :
sSQL SQL-, ;
sINIAppName -, DataManager;
sINIFullPath -;
iDataReturnType , .
ExecuteSQL SetConnectionParameters (. 3),
INI-, -,
.
364
. 3.
SetConnectkmParameters
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)
. . .
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
. . .
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")
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
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, ,
.
,
Visual Basic 6.0. HTML- Web,
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
'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
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
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
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(}
,
, . TextWriter.Synchronized .
Spider -,
SQL Server . , ,
Microsoft Access. :
Imports System.Data
Imports System.Data.OleDb
Imports System.Data.SqlClient
,
:
380
drGetReadOnly
' DataReader
Public Function drGetReadGnly(ByVal sSQL As String) As OleDbDataReader
Try
1:.
2:
3:
4:
5:
. 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 ()
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
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
. 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 (). . .
, OpenConnection:
.NET
38?
, :
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
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
.NET
, 1.
DBStuffADONET.vb
()
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
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 .
. 3.
ADO.NET
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
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
(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