Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Blogs | Beginners
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
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.

Total page views :  8025
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor

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). 


Login to add your contents and source code to 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.
SQL and .NET performance profiling in one place
Investigate SQL and .NET code side-by-side with ANTS Performance Profiler 6, so you can see which is causing the problem without switching tools.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
60 FREE UI Controls from DevExpress
Register for your FREE copy on over 60 free presentation controls from DevExpress - Absolutely Free-of-Charge without any royalties or distribution costs. Visit Devexpress.com/60 today. Free controls include advanced lists box, dropdown calendar, rich text edit, spin edit, tab control and so much more!

DevExpress engineers feature rich presentation controls and reporting tools for WinForms, ASP.NET, WPF, and Silverlight. Our technologies help you build your best, see complex software with greater clarity and deliver compelling business solutions for Windows and the web in the shortest possible time.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010
Visualize your workspace with new multiple monitor support, powerful Web development, new SharePoint support with tons of templates and Web parts, and more accurate targeting of any version of the .NET Framework. Get set to unleash your creativity.
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.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Read the Top 10 Books for Microsoft Developers, 15 Days FREE
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
Try Safari Books Online - 15 Days FREE + 15% Off for 1 Year
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
ASP.Net 4 Hosting is here
Become a Sponsor
 Comments
ANTS Performance Profiler 6.0
 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2010.8.14
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.