121Chapter 8 Establishing External Connections After completing this chapter, you will be able to: ■ ■ Understand the components that make up connection strings ■ ■ Write code that conne
Trang 1116 Microsoft ADO NET 4 Step by Step
Generating XML from a DataSet: Visual Basic
1 Open the “Chapter 7 VB” project from the installed samples folder The project includes
one Windows.Forms class named Serialization.
2 Open the source code view for the Serialization form Locate the ActGenerate_Click
function This routine produces the XML content from a sample DataSet containing two tables: Customer and Order.
3 Just after the “Set the XML namespace” comment, add the following statements:
SampleDataSet.Tables("Customer").Namespace = TableNamespace.Text.Trim
SampleDataSet.Tables("Customer").Prefix = TablePrefix.Text.Trim
SampleDataSet.Tables("Order").Namespace = TableNamespace.Text.Trim
SampleDataSet.Tables("Order").Prefix = TablePrefix.Text.Trim
This code sets the namespace and prefix values for both of the sample tables
Note As mentioned in the chapter discussion, you can also define namespace and prefix
val-ues within each DataColumn Although it is not included in the sample code, consider adding
code that will loop through all columns in each of the two tables and add the user-specified namespace and prefix values.
4 Just after the “Indicate the relationship type” comment, add the following line:
SampleDataSet.Relations(0).Nested = NestChildRecords.Checked
This statement determines whether the order rows for each customer record are
con-tained within the <Customer> tag (True) or whether all <Order> tags appear after and
at the same level as all the <Customer> tags in the XML (False).
5 Just after the “Build a memory stream to hold the results” comment, add the following
code:
holdBuffer = New MemoryStream(8192)
SampleDataSet.WriteXml(holdBuffer,
CType(OutputWriteMode.SelectedItem, XmlWriteMode))
These lines perform the actual XML generation, sending the results to a stream, in this
case a MemoryStream instance The remaining code in the event handler moves the
XML content from the stream to an on-form text box
Trang 2Chapter 7 Saving and Restoring Data 117
6 Run the program Use the fields in the upper-right corner of the form to alter the XML
content and then click Generate to produce the XML As an example, set the XML
Write Mode to IgnoreSchema; select the Nest Child Records check box; change the Mapping for Child.ID to Attribute; change the Mapping for Child.CustomerID, Child OrderDate, Child.Subtotal, and Child.TaxRate to Hidden; and finally change the Mapping for Child.Total to SimpleContent Click Generate The XML will contain a
simple set of customer records, each containing one or more <Order> tags with an ID
attribute, and with the order total set as the element content
Summary
This chapter introduced the XML-specific features built into ADO.NET classes These features exist primarily to assist in serializing static XML content for disk-based storage or for transfer
to other applications that expect ADO.NET-generated XML content The XML produced by these classes can define its own schema using embedded or external XSD and can build
hier-archical XML elements based on the relationships in the original DataSet.
There are other ways to bring ADO.NET data and XML together in your applications LINQ, a major language feature in both Visual Basic and C#, includes data-querying features for both ADO.NET and XML, features that can work in tandem Chapters 17 through 20 in this book discuss various LINQ-related technologies Although “LINQ to XML” is not specifically exam-ined in this book, the general LINQ concepts outlexam-ined in those chapters are similar to those used when writing LINQ queries for XML data
Trang 3118 Microsoft ADO NET 4 Step by Step
Chapter 7 Quick Reference
Export a DataSet to a file as XML Create a DataSet instance.
Add all relevant DataTable, DataRelation, and content objects Call the WriteXml method of the DataSet, passing it the file name
as an argument.
Import file-based XML into a new DataSet Create a new DataSet instance.
Call the ReadXml method of the DataSet, passing it the file name
as an argument.
Generate hierarchical parent-child data Create a DataSet instance.
Add the relevant DataTable objects.
Add a DataRelation instance that links the tables.
Set the DataRelation.Nested property to True.
Call DataSet.WriteXml to generate the XML content.
Store a DataColumn as an XML-based
attribute
Set the DataColumn.ColumnMapping property to MappingType.
Attribute.
Trang 4Microsoft ADO NET 4 Step by Step
Part II
Connecting to External Data
Sources
Trang 6121
Chapter 8
Establishing External Connections
After completing this chapter, you will be able to:
■
■ Understand the components that make up connection strings
■
■ Write code that connects to an external data source
■
■ Identify the different data providers included in ADO.NET
The first seven chapters of this book demonstrated many ADO.NET features that let you work with data in a fully disconnected way However, there are very few programs that depend on data created solely within the application itself Most programs, especially those in a business environment, depend on content stored in a database or other source external to the ap-plication This chapter examines ADO.NET data providers, the connection object, and other related features that make interactions between the Framework and data sources possible
The examples in this chapter and in those that follow use the StepSample database
men-tioned in the book’s Introduction If you haven’t yet installed that database, return to the Introduction and follow the steps listed there to prepare the sample SQL Server data You might also want to review the “Connecting to External Data” section on page 8 of Chapter 1, for details on connecting to databases using Visual Studio’s data access tools
Using Connection Strings
The ADO.NET library provides generic access to many different external data platforms These data sources include both local files in standardized formats and remote relational databases from a variety of vendors To access these data stores, your application must tell ADO.NET how to locate the resources, tell which data format to expect, and supply the
se-curity credentials required for access You communicate this information through connection
strings: formatted text strings that document the relevant connection values.
A connection string contains multiple semicolon-delimited elements Each element ex-presses a key-value pair that identifies one of the needed connection components or other relevant configuration settings The connection string syntax looks like this:
key1=value1;key2=value2;key3=value3
Trang 7Typical elements include the file-based or network-based location of the database, the user
ID and password needed to access the data source, the timeout value used to limit the dura-tion of excepdura-tionally long-running queries, and other values needed to establish the con-nection and its configuration The specific keys you must include depend on the target data platform or file format, the configuration of the data source, and the customizable features your application requires This section focuses on the more common elements needed to communicate with a SQL Server database For full details on other SQL Server elements, or
on the elements needed by other platforms, see the “Connection String Syntax (ADO.NET)” page in the Visual Studio online help
Note One popular web site, http://www.connectionstrings.com, includes sample connection
strings for all major database platforms, as well as for some relatively unknown data sources It also documents some of the more esoteric connection string keys that might be required for specific configurations It is an independent site that is not sponsored or officially supported by Microsoft But when you are struggling to construct a connection string for a complex or under-documented data environment, it is an invaluable resource.
SQL Server Connection Strings
In the “Creating a Data Source Using the Connection Wizard” example on page 8 in Chapter
1, step 12 briefly mentioned the connection string generated by the Data Source Connection Wizard When creating the data source on the wizard’s Choose Your Data Connection panel, the configured string appears in the Connection String field
Trang 8Chapter 8 Establishing External Connections 123
When following the steps in Chapter 1 on my own system, that connection string contained three key-value pairs
Data Source=(local)\SQLEXPRESS;Initial Catalog=StepSample;
Integrated Security=True
The wizard might create a slightly different string on your system This particular connection string establishes a connection to a SQL Server 2008 Express Edition database engine The three keys provide the information ADO.NET needs to establish the connection
■
■ The Data Source key indicates which server to access In this case, the (local)\
SQLEXPRESS value refers to the SQL Server 2008 Express Edition installation on the
local workstation
■
■ The Initial Catalog key tells the connection which database within the hosted database engine to use as the default In this sample string, StepSample is the name of the default
database catalog to use You must have the appropriate security credentials to access this database
■
■ The Integrated Security key with a value of True tells ADO.NET to use your existing
Microsoft Windows security credentials to access the database
So far, you’ve seen the typical basic format of a SQL Server 2008 connection string when using your Microsoft Windows security credentials; however, a few additional keys are com-monly included in SQL Server connection strings
■
■ As shown above, the Data Source key indicates the source database engine The special value of “(local)” tells ADO.NET to access the SQL Server instance running on the local workstation More commonly, (local) will be replaced with the name of the server that
hosts the database
■
■ If you prefer to use SQL Server’s own security system, set the Integrated Security key to
False (or you can just omit it from the connection string; False is the default value) Then
add two additional keys: User ID (with its value set of the SQL Server user name) and
Password (with its value set to the password of the specified user).
■
■ The Application Name key is optional though useful A user with appropriate security
access can obtain from the SQL Server database engine a list of all connected users, a
list that includes this Application Name setting If you have users running multiple
ver-sions of multiple applications, setting this value to the name and version number of the connecting application can simplify application use reporting
■
■ The AttachDBFilename key lets you attach a SQL Server Express Edition mdf data file by
referring to its filename
Trang 9124 Microsoft ADO NET 4 Step by Step
■
■ The Connection Timeout key specifies the number of seconds to wait before terminating
long-running queries or updates The default is 15 seconds
■
■ The MultipleActiveResultSets key defaults to False If you set it to True, SQL Server will allow you to have multiple simultaneous SELECT queries open to the database, or will allow you to run INSERT, UPDATE, or DELETE commands even when a SELECT query
is active
■
■ The Encrypt and TrustServerCertificate keys work together to enable encrypted
data-base sessions
Note While you’ve seen the most common connection string keys, be aware that these com-prise only a portion of the keys available with SQL Server connections Some keys also have
synonyms, including the Server synonym that is used in place of the Data Source key See the
“SqlConnection.ConnectionString Property” page in the Visual Studio documentation for addi-tional key values.
OLE DB and ODBC Connection Strings
ADO.NET provides generic access to many data platforms through the older OLE DB and ODBC data access layers The NET classes for this type of access are wrappers that provide a .NET-friendly interface to the underlying data libraries
Connection strings for both OLE DB and ODBC data sources are conceptually identical to their SQL Server counterparts They differ only in the specific keys and values included in each string For example, you can connect to Microsoft Access databases (.mdb files) using the OLE DB interface
Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\MyDataFolder\MyDatabase.mdb;
User Id=admin;Password=
For additional examples or details on the keys needed to connect to OLE DB or ODBC data sources, see the “OleDbConnection.ConnectionString Property” and “OdbcConnection ConnectionString Property” pages in the Visual Studio online help, or reference the docu-mentation for your specific data source platform
Connection String Builders
Building connection string content by hand is never an exciting proposition, and can some-times involve security risks If you allow users to provide portions of the connection string to
Trang 10Chapter 8 Establishing External Connections 125
your application, you open your program up to malicious code injection attacks Consider the following SQL Server connection string:
Source=ServerName;Initial Catalog=SalesData;User ID=xxx;Password=yyy
If a user provides the user ID (xxx) and password (yyy) values, a password that includes its
own semicolon-delimited value can alter the intent of the string
;Password=abc!123;Initial Catalog=master
Because the rightmost element of a connection string takes priority, the user-supplied Initial
Catalog=master element would override the earlier key, directing the user to the master
database
To prevent such attacks and make connection string building a more programmer-friendly
activity, ADO.NET includes connection string builders, platform-specific classes that expose
strongly typed properties associated with the keys normally included in the connection string
The connection string builder class for SQL Server is located at System.Data.SqlClient.
SqlConnectionStringBuilder To use it, create a new instance of the class, set its properties as
needed, and then access the object’s ConnectionString property to obtain the ready-to-use
connection string The following code builds the wizard-generated connection string shown earlier in this chapter:
C#
SqlClient.SqlConnectionStringBuilder builder =
new SqlClient.SqlConnectionStringBuilder();
builder.DataSource = @"(local)\SQLEXPRESS";
builder.InitialCatalog = "StepSample";
builder.IntegratedSecurity = true;
return builder.ConnectionString;
Visual Basic
Dim builder As New SqlClient.SqlConnectionStringBuilder
builder.DataSource = "(local)\SQLEXPRESS"
builder.InitialCatalog = "StepSample"
builder.IntegratedSecurity = True
Return builder.ConnectionString