Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
132
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Connection Strings

A large proportion of applications need to persist data, and the obvious candidate for enterprise software is a relational database. The .NET Framework provides support for working with SQL Server, Oracle, ODBC, and OLE DB databases. To connect to any of these databases you need to specify a connection string that determines the location, the database, authentication information, and other connection parameters. This chapter explains how to create and store connection strings. In addition, you’ll learn about encrypting and working with connection strings in code.

Data Source Configuration Wizard

Connection strings are similar to XML in that although they can be read, it is neither an enjoyable experience nor recommended to work with them directly. Because connection strings are strings, it is easy to introduce errors, misspell words, or even omit a parameter. Unlike XML, which can easily be validated against a schema, connection strings are harder to validate. The Data Source Configuration Wizard built into Visual Studio 2005 enables you to specify database connections without having to manually edit the connection string itself.

You can invoke the Data Source Configuration Wizard in a number of ways, as you will experience when you start working with any of the data controls in either the Windows form or web form designers. For the purposes of illustrating the wizard, follow these steps to add a new data source to an existing Windows Forms application. You’ll connect to the sample AdventureWorks database, which you will need to download from the Microsoft web site (www.microsoft.com).

Chapter 27

1.From the Data menu within Visual Studio 2005, select Add New Data Source, which opens the Data Source Configuration Wizard.

2.Selecting Database enables you to determine the database connection to use. If a connection already exists, you can select it from the drop-down and the associated connection string will appear in the lower portion of the window, as shown in Figure 27-1.

Figure 27-1

In this case, the connection string is stored in the application settings file (indicated by MySettings next to the connection name) and is used to connect to the AdventureWorks database on the sqlexpress database server on machine nickibm.

Later in this chapter you’ll look at the properties of a SQL Server connection string in more detail.

3.Click the New Connection button to open the Add Connection dialog in which you can specify the properties of the connection string. Figure 27-2 shows the dialog as it would appear for a SQL Server database connection.

Notice in Figure 27-2 that only the basic connection properties (such as server name, database name, and authentication information) are presented.

4.Click the Advanced button to open the Advanced Properties window, shown in Figure 27-3, where you can configure all properties for a SQL Server connection. At the bottom of this window is the connection string being constructed. The default values are omitted from the connection string. Once a value is set, it appears in the connection string and in bold in the Properties window.

358

Connection Strings

Figure 27-2

Figure 27-3

359

Chapter 27

5.Click OK to return to the Add Connection window, where you can change the type of data source by clicking the Change button. This opens the Change Data Source dialog, shown in Figure 27-4.

Figure 27-4

The list on the left contains all the data sources currently registered in the machine.config file. For a given data source, such as Microsoft SQL Server, there may be multiple data providers — in this case, the SQL Server and OLE DB providers.

Selecting an alternative data source-data provider combination will result in a different Add Connection dialog, displaying parameters that are relevant to that database connection. In most cases it is necessary to open the Advanced properties window to configure the connection itself.

6.After specifying the data source and connection settings using the Add Connection dialog, return to the Data Source Configuration Wizard. If you are creating a new connection, you will be given the option to save the connection string in the application configuration file, as shown in Figure 27-5. Unless you can guarantee that the location of the database, the authentication mode, or any other connection property will not change at a later stage, it is a good idea to store the connection string in the configuration file.

Figure 27-5

360

Connection Strings

If you don’t save the connection string to the configuration file, it is explicitly assigned to the connection object you are creating, which makes reuse difficult. Alternatively, saving the connection string in the configuration file means that other connection objects can access the same string. If the database connection changes at a later stage, you can easily update it in a single location.

When you save the connection string to the configuration file, it is added to the connectionStrings configuration section, as illustrated in the following snippet from an app.config file (the same section can exist in a web.config file for a web application):

<?xml version=”1.0” encoding=”utf-8” ?> <configuration>

<appSettings /> <connectionStrings>

<add name=”AdventureWorksConnectionString”

connectionString=”Data Source=nickibm\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True”

providerName=”System.Data.SqlClient” /> </connectionStrings>

</configuration>

The connectionStrings section of a configuration file uses the standard element collection pattern, which allows multiple connection strings to be specified and then referenced in code. For example, the preceding connection string can be accessed in code as follows:

Private Sub OpenConnectionClick(ByVal sender As System.Object, _ ByVal e As System.EventArgs) _

Handles BtnOpenConnection.Click

Dim sqlCon As New SqlClient.SqlConnection

sqlCon.ConnectionString = ConfigurationManager.ConnectionStrings _ (“AdventureWorksConnectionString”).ConnectionString

sqlCon.Open() End Sub

A nice artifact of working with the Data Source Connection Wizard is that it also adds strongly typed support for accessing the connection string from within your code. This means that you can access the connection string using the following strongly typed methods, rather than call them using a string constant:

C#

Properties.Settings.Default.AdventureWorksCS;

VB.NET

My.Settings.AdventureWorksConnectionString

The other advantage of saving the connection string in the configuration file is that when you are editing the project settings, the connection strings are listed alongside other settings for the project. Not only can you modify the connection string directly; you also have a shortcut to the Data Source Connection Wizard, which enables you to adjust the connection properties without fear of corrupting the connection string.

361

Chapter 27

SQL Ser ver Format

In order to concentrate on the connections themselves, the remainder of the Data Source Configuration Wizard is covered in a later chapter. Probably the most familiar data provider is the SQL Server database provider, so the following table details some of the common connection properties you may need to specify to connect to your database server:

Connection Property

Description

 

 

Asynchronous Processing

Determines whether the connection will support asyn-

 

chronous database calls. Most applications try to deliver a

 

responsive user interface, so it is important for it not to freeze

 

when retrieving data. In the past this could only be achieved

 

by doing the data processing in a separate thread from the

 

user interface. The data access methods, such as Exe-

 

cuteNonQuery, now support calls using the Begin and End

 

asynchronous pattern. For example, BeginExecuteNon-

 

Query will return immediately so the user interface does not

 

block while the data access is performed.

AttachDBFilename

New to SQL Server 2005, you can work with databases that

 

aren’t permanently attached to a SQL Server instance. This

 

property is a path reference to the primary database file that

 

contains the database. Specifying AttachDBFilename effec-

 

tively attaches and detaches the database when required.

Connect Timeout

Determines the maximum length of time that the Open

 

method will block when attempting to connect to the

 

database. This should not be confused with the Timeout

 

property on the SQLCommand class, which determines the

 

timeout for a given command to execute.

Data Source

The host name or IP address of the instance of SQL Server

 

that the connection will be accessing. In cases where multiple

 

instances exist on a given machine, or where SQL Server has

 

been assigned an instance name other than the default

 

instance, this needs to be specified as part of the Data Source

 

field, e.g., 192.168.205.223\InstanceName.

Initial Catalog

Specifies the name of the database to connect to.

Integrated Security

If Integrated Security is used, the Windows credentials

 

of the current user will be used to connect to the database

 

server. To provide user ID and password, this property must

 

be set to false. Also be aware that when working with

 

ASP.NET using Windows authentication without imperson-

 

ation, if Integrated Security is enabled, then the authenti-

 

cated web user’s credentials will be used to access the

 

database server.

 

 

362

 

 

Connection Strings

 

 

 

 

Connection Property

Description

 

 

 

 

MultipleActiveResultSets

Allows multiple result sets to be returned across a given

 

 

connection. For example, a single database command might

 

 

contain two SELECT statements. If the MultipleActive

 

 

ResultSets property is enabled, the results of both SELECT

 

 

statements will be returned and can be used to populate a

 

 

dataset. This property is only compatible with SQL Server

 

 

2005.

 

Password

Used for the SQL Server user account used to access the

 

 

database server

 

User ID

Specifies the SQL Server account used to access the database

 

 

server. Mixed-mode authentication for the SQL Server must

 

 

be enabled, and the Integrated Security property must

 

 

be set to false.

 

 

 

Each connection string property must be specified as it appears in the preceding table, but they can be in any order in the connection string. A semicolon is used to separate each property. An example connection string might be as follows:

Data Source=nickibm\sqlexpress;Initial Catalog=AdventureWorks;Integrated

Security=True;MultipleActiveResultSets=True

In-Code Construction

Although the Data Source Connection Wizard in Visual Studio 2005 provides a convenient tool for writing connection strings, it is often necessary to build one dynamically — a feat easily done with the SqlConnectionStringBuilder class. In fact, there are also string builder classes for Oracle, ODBC, and OLE DB, and they all derive from the generic DBConnectionStringBuilder class, which exposes the

ConnectionString property.

This example demonstrates creating a connection builder object, based on an existing connection string, changing the authentication mode to use the user ID and password provided by the user before assigning the new connection string to the connection object. In addition, the example demonstrates the use of the MultipleActiveResultSets property to retrieve multiple tables from the database using a single command object:

Private Sub LoadDataClick(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles Button1.Click ‘Update the connection string based on user settings

Dim sqlbuilder As New SqlClient.SqlConnectionStringBuilder _ (My.Settings.AdventureWorksConnectionString)

If Not Me.TxtUserId.Text = “” Then sqlbuilder.IntegratedSecurity = False sqlbuilder.UserID = Me.TxtUserId.Text sqlbuilder.Password = Me.TxtPassword.Text

End If

363

Chapter 27

sqlbuilder.MultipleActiveResultSets = True

‘Create the connection based on the updated connection string Dim sqlCon As New SqlClient.SqlConnection sqlCon.ConnectionString = sqlbuilder.ConnectionString

‘Set the command and create the dataset to load the data into

Dim sqlcmd As New SqlClient.SqlCommand(“SELECT * FROM Person.Contact;” & _ “select * from Person.ContactType”, _ sqlCon)

Dim ds As New DataSet

Dim rds As New SqlClient.SqlDataAdapter(sqlcmd)

‘Open connection, retrieve data, and close connection sqlCon.Open()

rds.Fill(ds)

sqlCon.Close() End Sub

The important thing to note about this code sample is that the MultipleActiveResultSets property is enabled, which means that multiple Select statements can be specified in the SqlCommand object. The SqlCommand object is then used by the SqlDataAdapter object to fill the DataSet. The DataSet object will contain two data tables, each populated by one of the Select statements.

Encr ypting Connection Strings

Although best practices state that you should use windows authentication and integrated security wherever possible, this is not always the case; sometimes you have to resort to specifying a user ID and password in a connection string. It is recommended that this information not be hard-coded into your application, as it can easily be extracted from the assembly. As such, this information needs to be either specified by the users each time they use the system, or added to the connection string in the configuration file. The upshot of this is that you need a mechanism for encrypting configuration sections. This walkthrough shows you how to encrypt a section of a configuration file for a web application, StagingWebsite, which has a web.config file as follows:

<?xml version=”1.0”?> <configuration>

<connectionStrings>

<add name=”AdventureWorksConnectionString” connectionString=”Data Source=.\sqlexpress;Initial Catalog=AdventureWorks;Integrated Security=True”

providerName=”System.Data.SqlClient” /> </connectionStrings>

<!--

...

--> </configuration>

Using the command prompt, execute the following commands in sequence, replacing UserName with the name of the account that the web application will run as (for example, the AspNet account):

364

Connection Strings

1.

2.

3.

cd\WINDOWS\Microsoft.NET\Framework\v2.0.50727

aspnet_regiis -pa “NetFrameworkConfigurationKey” “UserName”

aspnet_regiis -pe “connectionStrings” -app “/StagingWebsite”

Executing these commands modifies the web.config file as follows:

<?xml version=”1.0”?> <configuration>

<connectionStrings configProtectionProvider=”RsaProtectedConfigurationProvider”> <EncryptedData Type=”http://www.w3.org/2001/04/xmlenc#Element” xmlns=”http://www.w3.org/2001/04/xmlenc#”>

<EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#tripledes-cbc” /> <KeyInfo xmlns=”http://www.w3.org/2000/09/xmldsig#”>

<EncryptedKey xmlns=”http://www.w3.org/2001/04/xmlenc#”> <EncryptionMethod Algorithm=”http://www.w3.org/2001/04/xmlenc#rsa-1_5” /> <KeyInfo xmlns=”http://www.w3.org/2000/09/xmldsig#”>

<KeyName>Rsa Key</KeyName> </KeyInfo>

<CipherData>

<CipherValue>Y4Be/ND8fXTKl3r0CASBK0oaOSvbyijYCVUudf1AuQlpU2HRsTyEpR2sVpxrOukiBhvcGy

Wlv4EM0AB9p3Ms8FgIA3Ou6mGORhxfO9eIUGD+M5tJSe6wn/9op8mFV4W7YQZ4WIqLaAAu7MKVI6KKK/ANI

KpV8l2NdMBT3uPOPi8=</CipherValue>

</CipherData>

</EncryptedKey>

</KeyInfo>

<CipherData>

<CipherValue>BeKnN/kQIMw9rFbck6IwX9NZA6WyOCSQlziWzCLA8Ff/JdA0W/dWIidnjae1vgpS8ghouY

n7BQocjvc0uGsGgXlPfvsLq18//1ArZDgiHVLAXjW6b+eKbE5vaf5ss6psJdCRRB0ab5xaoNAPHH/Db9UKM

ycWVqP0badN+qCQzYyU2cQFvK1S7Rum8VwgZ85Qt+FGExYpG06YqVR9tfWwqZmYwtW8izr7fijvspm/oRK4

Yd+DGBRKuXxD6EN4kFgJUil7ktzOJAwWly4bVpmwzwJT9N6yig54lobhOahZDP05gtkLor/HwD9IKmRvO1j

v</CipherValue>

</CipherData>

</EncryptedData>

</connectionStrings> <!--

...

--> </configuration>

As you can see from this example, the connection string is no longer readable in the configuration file. The commands you executed did two things. Ignoring the first command (because it simply changes the directory so you can access the asp_regiis executable), the second command permits access to the key container NetFrameworkConfigurationKey for the user Nick. This key container is the default container for the RSAProtectedConfigurationProvider, which is specified in the machine.config file. In order for your application to be able to decrypt data from the configuration file, the user that the application is running as must be able to access the key container. To determine the identity of this user, execute the following command:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

365