Free mag vol1 | Page 880

CHAPTER 21  ADO.NET PART I: THE CONNECTED LAYER Begin by adding a reference to the System.Configuration.dll assembly and importing the System.Configuration namespace. Next, insert an App.config file to the current project and define an empty element. Add a new key-named provider that maps to the namespace name of the data provider you want to obtain (System.Data.SqlClient). Also, define a connection string that represents a connection to the AutoLot database (on the local instance of SQL Server Express).  Note You will learn about connection strings in more detail momentarily; however, if you select your AutoLot database icon within the Server Explorer, you can copy-and-paste the correct connection string from the Connection String property of the Visual Studio Properties window. Now that you have a proper *.config file, you can read in the provider and cnStr values using the ConfigurationManager.AppSettings indexer. The provider value will be passed to DbProviderFactories.GetFactory() to obtain the data provider–specific factory type. You will use the cnStr value to set the ConnectionString property of the DbConnection-derived type. Assuming you have imported the System.Data and System.Data.Common namespaces, you can update your Main() method like this: static void Main(string[] args) { Console.WriteLine("***** Fun with Data Provider Factories *****\n"); // Get Connection string/provider from *.config. string dp = ConfigurationManager.AppSettings["provider"]; string cnStr = ConfigurationManager.AppSettings["cnStr"]; // Get the factory provider. DbProviderFactory df = DbProviderFactories.GetFactory(dp); // Now get the connection object. using (DbConnection cn = df.CreateConnection()) { Console.WriteLine("Your connection object is a: {0}", cn.GetType().Name); cn.ConnectionString = cnStr; 826