Blue Theme Orange Theme Green Theme Red Theme
 
6 Months Free & No Setup Fees ASP.NET Hosting!
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » ASP.NET and Web » Performance Improvement in ASP.NET using Caching with VB.NET

Performance Improvement in ASP.NET using Caching with VB.NET

ASP.NET provides caching at several levels for you to leverage and improve the responsiveness of your application by storing the page output or application data across HTTP requests and reuse it. This allows the web server to take advantage of processing the request without recreating the information and thus saving time and resources.

Page Views : 9494
Downloads : 0
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Team Foundation Server Hosting
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The challenge in building high-performance, scalable Web applications is the ability to store items, whether data objects, pages, or parts of a page, in memory the initial time they are requested. You can store these items on the Web server or other software in the request stream, such as the proxy server or browser. This allows you to avoid recreating information that satisfied a previous request, particularly information that demands significant processor time or other resources.

ASP.NET provides caching at several levels for you to leverage and improve the responsiveness of your application by storing the page output or application data across HTTP requests and reuse it. This allows the web server to take advantage of processing the request without recreating the information and thus saving time and resources.

Caching Opportunities in ASP.NET web pages.

ASP.Net supports both page (or portion of a page) caching and also caching data from a backend data source and storing these individual objects in memory.

To achieve this following features are provided in ASP.NET

  • Page output caching
  • Page fragment caching
  • Data caching

Page Output Caching.

Dynamically generated .aspx pages can be cached for efficiency instead of re-generating each .aspx page for identical requests, the pages are cached.

Page Output caching can be achieved in the following 3 ways.

1) This can be achieved by specifying the @OutputCache directive at the top of the ASP.Net page. It controls the caching duration (in seconds).

<%@ OutputCache Duration="3600" VaryByParam="none" %>
<html>
<script language="VB" runat="server">
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase
.Load
'Put user code to initialize the page here
msg.Text = DateTime.Now.ToString()
End
Sub
</script>
<body>
<h3>Output Cache example</font></h3>
<p>Last generated on: <asp:label id="msg" runat="server"/></p>
</body>
</html>

2) Programmatically you can achieve this using the HttpCachePolicy sealed class which can be accessed from the HttpResponse.Cache property of the Page.Response property.

HttpCachePolicy class.

Public NotInheritable Class
HttpCachePolicy
Public VaryByHeaders As
HttpCacheVaryByHeaders
Public VaryByParams As
HttpCacheVaryByParams
public void AppendCacheExtension(String
extension)
public
void SetCacheability(HttpCacheability cacheability)
public void SetExpires(DateTime date
)
public void SetLastModified(DateTime date
)
public
void SetMaxAge(TimeSpan delta)
public
void SetNoServerCaching()
public void SetSlidingExpiration(Boolean
slide)
End
Class

Modifying a page's caching policy programmatically.

<html>
<script language="VB" runat="server">
Private Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)Response.Cache.SetExpires(DateTime.Now.AddSeconds(360))Response.Cache.SetCacheability(HttpCacheability.Public)Response.Cache.SetSlidingExpiration(True
)
msg.Text = DateTime.Now.ToString()
End
Sub
</script>
<body>
<h3>Output Cache example</font></h3>
<p>Last generated on: <asp:label id="msg" runat="server"/></p>
</body>
</html>

3) Caching of GET requests with query strings or POST requests with bodies controlled by VaryByParam property. It determines how many versions of the page are cached. Specifying it to "none" means that only GET requests with NO query strings or POST requests with NO body will hit the cache. Specifying VaryByParam to "*" means that as many different querystring or POST body requests are received
will be cached.

The following table gives you a brief idea of the VaryByParam values.

VaryByParam Description
none One version of page cached (only raw GET).
* n versions of page cached based on query string and/or POST body.
V1 n versions of page cached based on value of V1 variable in query string or POST body.
V1;V2 n versions of page cached based on value of V1 and V2 variables in query string or POST body.

<%@ OutputCache Duration="60" VaryByParam="none" %>
<%@ OutputCache Duration="60" VaryByParam="*" %>
<%@ OutputCache Duration="60" VaryByParam="name;age" %>

The first time the page is requested, the response is generated and added to the cache. If the page is requested within 60 seconds with the same values for name and age, then the cached version is used.

For Information:

Other cache varying options.

The OutputCache directive supports several other cache varying options

  • VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.).

  • VaryByControl - for user controls, maintain separate cache entry for properties of a user control.

  • VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplication derived class.

Page Fragment Caching.

Parts of the ASP.Net page which are to be cached are encapsulated in Web Forms User Controls.

MyUserControl.ascx.

<%@ OutputCache Duration="60" VaryByParam="none" %>
<%@ Control Language=VB %>
<script runat=server>
Protected Sub Page_Load(ByVal src As Object, ByVal e As
EventArgs)
m_Date.Text = "Control generated at " & DateTime.Now.ToString()
End
Sub
</script>
<asp:Label id=m_Date runat=server />

Client.aspx.

<%@ Page Language=VB %>
<%@ Register TagPrefix="DM" TagName="UserFrag"Src="MyUserControl.ascx" %>
<html>
<script runat=server>protected void Page_Load(Object src, EventArgs e)
 m_PageDate.Text = "Page generated at " & DateTime.Now.ToString()
</script>
<body>
<DM:UserFrag runat=server /><br>
<asp:Label id=m_PageDate runat=server />
</body>
</html>

Data Caching.

In simple terms data caching is storing data in memory for quick access. Typically information that is costly to obtain (in terms of performance) is stored in the cache. One of the more common items stored in a cache in a Web application environment is commonly displayed database values; by caching such information, rather than relying on repeated database calls, the demand on the Web server and database server's system resources are decreased and the Web application's scalability increased.

ASP.NET provides a full-featured cache engine that can be used by pages to store data across HTTP requests.

A small example of storing the value obtained from the database is given below.

<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html>
<script language="VB" runat="server">
Protected Sub Page_Load(ByVal src As Object, ByVal e As
EventArgs)
Dim dv As DataView = CType
(Cache.Get("EmployeesDataView"), DataView)
If dv Is Nothing
Then
' wasn't there
Dim conn As SqlConnection = New
SqlConnection("server=localhost;uid=sa;pwd=;database=Test")
Dim da As SqlDataAdapter = New SqlDataAdapter("select * from Employees", conn)Dim ds As DataSet = New
DataSet()
da.Fill(ds, "Employees")
dv = ds.Tables("Employees").DefaultView
Cache.Insert("EmployeesDataView", dv)
conn.Close()
Else
Response.Write("<h2>Loaded employees from data cache!</h2>")
End
If
lb1.DataSource = dv
lb1.DataTextField = "Name"
lb1.DataValueField = "Age"
DataBind()
End
Sub
</script>
<body>
<asp:ListBox id="lb1" runat=server />
</body>
</html>

Cache entry attributes.

When adding cache entries, several attributes can be specified

Dependencies (on files, directories, or other cache entries)
Absolute expiration time
Sliding expiration time
Relative priority
Rate of priority decay
Callback function for removal notification
public void Insert(String key, Object
value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemPriority priority, CacheItemRemovedCallback onRemoveCallback)

The different parameters which the Insert method accepts is given below.
 Parameters
 

Parameters

key The cache key used to reference the object.
value The object to be inserted in the cache.
dependencies The file or cache key dependencies for the item. When any dependency changes, the object becomes invalid and is removed from the cache. If there are no dependencies, this parameter contains a null reference.
absoluteExpiration The time at which the inserted object expires and is removed from the cache.
slidingExpiration The interval between the time the inserted object was last accessed and when that object expires. If this value is the equivalent of 20 minutes, the object will expire and be removed from the cache 20 minutes after it was last accessed.
priority The cost of the object relative to other items stored in the cache, as expressed by the CacheItemPriority enumeration. This value is used by the cache when it evicts objects; objects with a lower cost are removed from the cache before objects with a higher cost.
onRemoveCallback A delegate that, if provided, will be called when an object is removed from the cache. You can use this to notify applications when their objects are deleted from the cache.


Removing objects from the cache.

  • Objects can be explicitly taken out of the cache by calling Remove
  • Cache can remove item implicitly for a variety of reasons
      * Data expiration
      * Memory consumption
  • Low priority data removed first
  • Values marked with Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, or CacheItemPriorityDecay.Never are never removed
  • Can register for removal notification, including reason

Using removal notification callback.

<script language=VB runat=server>
Public Sub
Application_OnStart()
Dim sr As System.IO.StreamReader = New
System.IO.StreamReader("pi.txt")
Dim pi As String
= sr.ReadToEnd()
Context.Cache.Add("pi", pi,
Nothing,Cache.NoAbsoluteExpiration,New TimeSpan(0, 5, 0),CacheItemPriorityDecay.Never,New CacheItemReomovedCallback(Me.OnRemove))End
Sub
Public
Sub OnRemove(ByVal key As String, ByVal val As Object, ByVal r As
CacheItemRemovedReason)
' respond to cache removal here
End
Sub

</script>

Disadvantages of Caching.

Although the caching support can be really helpful in a lot of scenarios, it has some major disadvantages:

  • With cached pages that display results retrieved from a database the cache can be inconsistent, i.e. not reflecting the latest changes applied to a database.

Conclusion.

Caching dramatically improves the performance of a web site, but it has disadvantages as well. The user should take care of the parameter values for expiration policy.

NOTE: THIS ARTICLE IS CONVERTED FROM C# TO VB.NET USING A CONVERSION TOOL. ORIGINAL ARTICLE CAN BE FOUND ON C# CORNER (WWW.C-SHARPCORNER.COM). 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Harikishan Gireesh
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.