using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

using System.Data.Common;
using System.Web.Configuration;
using System.Xml;
using System.Data.SqlClient;

public partial class ProviderIndependence : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

      try
      {
         // retrieve database connection and provider name
         ConnectionStringSettings setting = WebConfigurationManager.ConnectionStrings["Books"];
         string connString = setting.ConnectionString;
         string invariantName = setting.ProviderName;

         // verify that this provider name is supported
         DataTable providers = DbProviderFactories.GetFactoryClasses();
         DataRow[] foundArray = providers.Select("InvariantName='"+invariantName+"'");
         if (foundArray.Length == 0)
         {
            throw new Exception("Data Provider " + invariantName + " not found");
         }

         // get appropriate provider factory
         DbProviderFactory factory = DbProviderFactories.GetFactory(invariantName);

         // set up and open connection
         DbConnection conn = factory.CreateConnection();
         conn.ConnectionString = connString;

         // set up select command
         string sql = " SELECT * FROM Authors";
         DbCommand cmd = factory.CreateCommand();
         cmd.CommandText = sql;
         cmd.Connection = conn;

         DbDataAdapter adapter = factory.CreateDataAdapter();
         adapter.SelectCommand = cmd;

         DataSet ds = new DataSet();
         adapter.Fill(ds, "AuthorsTable");

         // use filled DataSet
         grdAuthors.DataSource = ds.Tables["AuthorsTable"].DefaultView;
         grdAuthors.DataBind();
      }
      catch (Exception ex)
      {
         // process exception
         labMsg.Text = "Error occurred accessing the database";
         labMsg.Text += "<br/>" + ex.Message;
      }
   }

   public XmlReader GetXml(DbCommand cmd)
   {
      if (cmd is SqlCommand)
      {
         SqlCommand sqlCmd = (SqlCommand)cmd;
         return sqlCmd.ExecuteXmlReader();
      }
      else
         return null;
   }
}
