Enumerating Data Sources


Some data providers now give you the ability to enumerate a list of data sources. For the SQL Server provider, this is a list of available SQL servers. Each data provider will return a DataTable containing different information about the available data sources.

The code in Listing 19.4 shows sample code to determine whether a data provider supports the ability to enumerate data sources and how to examine that list of data sources.

Listing 19.4. Enumerating Data Sources

using System; using System.Data; using System.Data.Common; using System.Collections.Generic; using System.Text; namespace EnumDS { class Program { static void Main(string[] args) {     DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SqlClient");     DbConnection conn = factory.CreateConnection();     conn.ConnectionString = "data source=localhost; initial catalog=SampleDB; Integrated Security=SSPI;";     conn.Open();     if (factory.CanCreateDataSourceEnumerator)     {         DbDataSourceEnumerator dsEnum = factory.CreateDataSourceEnumerator();         DataTable sources = dsEnum.GetDataSources();         foreach (DataRow dataSource in sources.Rows)         {             Console.WriteLine(dataSource["ServerName"]);         }     }     Console.ReadLine(); } } } 

The preceding code takes a few seconds to start, as the GetdataSources() method is fairly lengthy. After it completes, however, you will have a fully populated DataTable containing a list of data sources available for the given data provider (in this case, System.Data.SqlClient).



Microsoft Visual C# 2005 Unleashed
Microsoft Visual C# 2005 Unleashed
ISBN: 0672327767
EAN: 2147483647
Year: 2004
Pages: 298

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net