Tải bản đầy đủ - 0 (trang)
9-4. Store a Database Connection String Securely

9-4. Store a Database Connection String Securely

Tải bản đầy đủ - 0trang

CHAPTER 9 ■ DATABASE ACCESS



assembly can easily be retrieved using a disassembler. The .NET Framework includes a number of

classes and capabilities that make storing and retrieving encrypted connection strings in your

application’s configuration trivial.

Unencrypted connection strings are stored in the machine or application configuration file in the

section in the format shown here:






providerName="System.Data.SqlClient" />





The easiest way to read this connection string is to use the indexed ConnectionStrings property of

the System.Configuration.ConfigurationManager class. Specifying the name of the connection string you

want as the property index will return a System.Configuration.ConnectionStringSettings object. The

ConnectionStringSettings.ConnectionString property gets the connection string, and the

ConnectionStringSettings.ProviderName property gets the provider name that you can use to create a

data provider factory (see recipe 9-10). This process will work regardless of whether the connection

string has been encrypted or written in plain text.

To write a connection string to the application’s configuration file, you must first obtain a

System.Configuration.Configuration object, which represents the application’s configuration file. The

easiest way to do this is by calling the System.Configuration.ConfigurationManager.

OpenExeConfiguration method. You should then create and configure a new System.Configuration.

ConnectionStringSettings object to represent the stored connection string. You should provide a name,

connection string, and data provider name for storage. Add the ConnectionStringSettings object to

Configuration’s ConnectionStringsSection collection, available through the Configuration.

ConnectionStrings property. Finally, save the updated file by calling the Configuration.Save method.

To encrypt the connection strings section of the configuration file, before saving the file, you must

configure the ConnectionStringsSection collection. To do this, call the ConnectionStringsSection.

SectionInformation.ProtectSection method and pass it a string containing the name of the protected

configuration provider to use: either RsaProtectedConfigurationProvider or

DPAPIProtectedConfigurationProvider. To disable encryption, call the SectionInformation.Unprotect

method.



■ Note To use the classes from the System.Configuration namespace discussed in this recipe, you must add a

reference to the System.Configuration.dll assembly when you build your application.



The Code

The following example demonstrates the writing of an encrypted connection string to the application’s

configuration file and the subsequent reading and use of that connection string.



434



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



■ Note The configuration file will be created alongside the compiled program in the bin/Release or bin/Debug

directory of the Visual Studio project folder. If you have downloaded the source code that accompanies this book,

the configuration tile will be called Recipe09-04.exe.Config.



using System;

using System.Configuration;

using System.Data.SqlClient;

namespace Apress.VisualCSharpRecipes.Chapter09

{

class Recipe09_04

{

private static void WriteEncryptedConnectionStringSection(

string name, string constring, string provider)

{

// Get the configuration file for the current application. Specify

// the ConfigurationUserLevel.None argument so that we get the

// configuration settings that apply to all users.

Configuration config = ConfigurationManager.OpenExeConfiguration(

ConfigurationUserLevel.None);

// Get the connectionStrings section from the configuration file.

ConnectionStringsSection section = config.ConnectionStrings;

// If the connectionString section does not exist, create it.

if (section == null)

{

section = new ConnectionStringsSection();

config.Sections.Add("connectionSettings", section);

}

//

//

//

if

{



If it is not already encrypted, configure the connectionStrings

section to be encrypted using the standard RSA Proected

Configuration Provider.

(!section.SectionInformation.IsProtected)

// Remove this statement to write the connection string in clear

// text for the purpose of testing.

section.SectionInformation.ProtectSection(

"RsaProtectedConfigurationProvider");



}

// Create a new connection string element and add it to the

// connection string configuration section.

ConnectionStringSettings cs =

new ConnectionStringSettings(name, constring, provider);

section.ConnectionStrings.Add(cs);



435



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



// Force the connection string section to be saved.

section.SectionInformation.ForceSave = true;

// Save the updated configuration file.

config.Save(ConfigurationSaveMode.Full);

}

public static void Main(string[] args)

{

// The connection string information to be written to the

// configuration file.

string conName = "ConnectionString1";

string conString = @"Data Source=.\sqlexpress;" +

"Database=Northwind;Integrated Security=SSPI;" +

"Min Pool Size=5;Max Pool Size=15;Connection Reset=True;" +

"Connection Lifetime=600;";

string providerName = "System.Data.SqlClient";

// Write the new connection string to the application's

// configuration file.

WriteEncryptedConnectionStringSection(conName, conString, providerName);

// Read the encrypted connection string settings from the

// application's configuration file.

ConnectionStringSettings cs2 =

ConfigurationManager.ConnectionStrings["ConnectionString1"];

// Use the connection string to create a new SQL Server connection.

using (SqlConnection con = new SqlConnection(cs2.ConnectionString))

{

// Issue database commands/queries . . .

}

// Wait to continue.

Console.WriteLine(Environment.NewLine);

Console.WriteLine("Main method complete. Press Enter.");

Console.ReadLine();

}

}

}



9-5. Execute a SQL Command or Stored Procedure

Problem

You need to execute a SQL command or stored procedure on a database.



436



www.it-ebooks.info



CHAPTER 9 ■ DATABASE ACCESS



Solution

Create a command object appropriate to the type of database you intend to use. All command objects

implement the System.Data.IDbCommand interface. Configure the command object by setting its

CommandType and CommandText properties. Execute the command using the ExecuteNonQuery,

ExecuteReader, or ExecuteScalar method, depending on the type of command and its expected results.



How It Works

The IDbCommand interface represents a database command, and each data provider includes a unique

implementation. Here is the list of IDbCommand implementations for the five standard data providers:





System.Data.Odbc.OdbcCommand







System.Data.OleDb.OleDbCommand







System.Data.OracleClient.OracleCommand







System.Data.SqlServerCe.SqlCeCommand







System.Data.SqlClient.SqlCommand



To execute a command against a database, you must have an open connection (discussed in recipe

9-1) and a properly configured command object appropriate to the type of database you are accessing.

You can create command objects directly using a constructor, but a simpler approach is to use the

CreateCommand factory method of a connection object. The CreateCommand method returns a command

object of the correct type for the data provider and configures it with basic information obtained from

the connection you used to create the command. Before executing the command, you must configure

the properties described in Table 9-3, which are common to all command implementations.

Table 9-3. Common Command Object Properties



Property



Description



CommandText



A string containing the text of the SQL command to execute or the name of a stored

procedure. The content of the CommandText property must be compatible with the

value you specify in the CommandType property.



CommandTimeout



An int that specifies the number of seconds to wait for the command to return before

timing out and raising an exception. Defaults to 30 seconds.



CommandType



A value of the System.Data.CommandType enumeration that specifies the type of

command represented by the command object. For most data providers, valid values

are StoredProcedure, when you want to execute a stored procedure; and Text, when

you want to execute a SQL text command. If you are using the OLE DB data provider,

you can specify TableDirect when you want to return the entire contents of one or

more tables; refer to the .NET Framework SDK documentation for more details.

Defaults to Text.



437



www.it-ebooks.info



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

9-4. Store a Database Connection String Securely

Tải bản đầy đủ ngay(0 tr)

×