CodeKicks.com
Focus on Microsoft Technologies - Tutorials, Articles, Code Samples.

Saturday, September 02, 2006

Data Caching Sample Code in ASP.NET

Object obj = (Object)Cache["key"];Object obj = (Object)Cache["key"];if (obj == null) {  // Generate a new object and insert it into the cache}// Use your object <%@ Page Language="C#" %>   <%@ Import Namespace="System.Data" %> <script runat="server">private string _filename = "mydata.xml";private void Page_Load(Object src, EventArgs args) {  DataSet ds = (DataSet)Cache["mydata"];  if (ds == null) {    ds.ReadXml(Server.MapPath(_filename));    Cache.Insert("mydata", ds,      new CacheDependency(Server.MapPath(_filename)),      DateTime.Now.AddHours(12), NoSlidingExpiration);  }  myDataGrid.DataSource = ds;  myDataGrid.DataBind();}Cache.Insert("mydata", ds,  new CacheDependency(Server.MapPath(_filename)),  DateTime.Now.AddHours(12), NoSlidingExpiration);<body><asp:DataGrid id="myDataGrid" runat="server"  AutoGenerateColumns="true"  ShowHeader="true"  AllowPaging="true"  PageSize="25"  Font-Name="Verdana"  Font-Size="10pt">  <HeaderStyle Font-Bold="true"/></asp:DataGrid></body>myDataGrid.DataSource = ds;myDataGrid.DataBind();<%@ Page Language="C#" %>   <%@ Import Namespace="System.Data" %>   <%@ Import Namespace="System.Data.SqlClient" %> <script runat="server">// If used frequently, store these strings in your Web.config// and use ConfigurationSettings.AppSettings["key"] to get them out.// If you do this, make sure these are constant strings!private const string connstr = "Data Source=sqlserver1;Initial Catalog=Web";private const string cmdstr = "SELECT Title,URL FROM TOC";private void Page_Load(Object src, EventArgs args) {  DataSet ds = (DataSet)Cache["mydata"];  if (ds == null) {    // Connect to the SQL Server and get our data using a DataAdapter    SqlConnection conn = new SQlConnection(connstr);    SqlCommand cmd = new SqlCommand(cmdstr, conn);    SqlDataAdapter adapter = new SqlDataAdapter(cmd);    // Create a new DataTable and fill it    DataTable dt = new DataTable("Item");    adapter.Fill(dt);    // Now add our DataTable to a DataSet instance and add to cache    ds = new DataSet("TOC");    ds.Tables.Add(dt);    Cache.Insert("mydata", ds, null, DataTime.Now.AddHours(1), NoSlidingExpiration);  }  // Bind our data  myRepeater.DataSource = ds;  myRepeater.DataBind();}<body><asp:Repeater id="myRepeater" runat="server" Visible="true"><ItemTemplate><dd><a href="<%# DataBinder.Eval(Container, "Item.URL") %>"><%# DataBinder.Eval(Container, "Item.Title") %></a></dd></ItemTemplate></asp:Repeater></body>DataTable dt = new DataTable("Item");

Post a Comment