I've ben messing with some ado.net code to load master page dynamically from database. Naturally I wanted to cache the masterpage file name so the database is not called every time the page is called.
I created a dataset, a datatable and datareader. When I step through the code in the debugger, they all do exactly the same thing.??? I don't get it. I thought using a reader to cache data was forbidden because it would leave the connection open. I think I'm not uderstanding this correctly. Could someone please explain why the following code is bad?
1. When the MasterPage name is not in the cache, the code goes and retrieves it from the database.
2. When the page is visited and the MasterPage name is in the cache, the code gets it from the cache and moves on.
3. I don't understant why this is supposed to be wrong. Can some one explain? Thank you.
protected void Page_PreInit(object sender, EventArgs e)
{
if (Cache["cachedMaster"] == null)
{
GetMasterPage();
}
else
{
string loadMasterFromCache = Cache["cachedMaster"].ToString();
this.MasterPageFile = loadMasterFromCache;
}
} try
{
SqlConnection conn;
SqlCommand cmd;
string cmdString = "SELECT masterPage FROM MasterPages WHERE (masterEnabled = 1) AND (masterCategoryName = 'Blog')";
conn = new SqlConnection(ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString);
cmd = new SqlCommand(cmdString, conn);
conn.Open();
SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SingleResult);
if (myReader.Read())
{
string masterPageFileName = myReader["masterPage"] as string;
Cache.Insert("cachedMaster", masterPageFileName, null, DateTime.Now.AddSeconds(300), System.Web.Caching.Cache.NoSlidingExpiration);
}
myReader.Close();
conn.Close();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}