using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.UI;

public partial class ObjectCaching : Page
{
   protected void Page_Load(object sender, EventArgs e)
   {
      CreateGridView();
   }

   private void CreateGridView()
   {
      DataSet dsGrid;
      dsGrid = (DataSet)Cache["GridViewDataSet"];
      if (dsGrid == null)
      {
         dsGrid = GetDataSet();
         //Cache["GridViewDataSet"] = dsGrid;
         Cache.Insert("GridViewDataSet", dsGrid);
         lblMessage.Text = "Dane z bazy danych.";
      }
      else
      {
         lblMessage.Text = "Dane z bufora.";
      }

      gvwCustomers.DataSource = dsGrid.Tables[0];
      gvwCustomers.DataBind();
   }

   private DataSet GetDataSet()
   {
      // Połączenie z bazą danych AdventureWorksLT.
      string connectionString = ConfigurationManager.
         ConnectionStrings["AWLTConnectionString"].ConnectionString;

      // Pobranie rekordów z tabeli Customers.
      string commandString = 
         "SELECT TOP 10 CustomerID, FirstName, LastName, " + 
         "EmailAddress FROM SalesLT.Customer";

      // Tworzenie obiektu Command źródła danych i obiektu DataSet.
      SqlDataAdapter dataAdapter = 
         new SqlDataAdapter(commandString, connectionString);

      DataSet dsData = new DataSet();

      // Wypełnienie danymi ustawionych obiektów.
      dataAdapter.Fill(dsData, "Customers");

      return dsData;
   }


   protected void btnClear_Click(object sender, EventArgs e)
   {
      Cache.Remove("GridViewDataSet");
      CreateGridView();
   }
}
