Archive

Archive for May, 2013

How to implement Cache mechanism in ASP.Net/C# using simple example OR What is Output Caching and Fragment Caching in ASP.Net/C#

May 30, 2013 7 comments

What is Caching in ASP.NET AND How can get access to cache object?

ASP.NET Caching is used to build high-performance, scalable ASP.NET web applications by storing responses in memory. On subsequent requests, the page code is not executed and the cached output is used to serve the request. The Cache object is defined in the ‘System.Web.Caching’ namespace. You can get a reference to

the Cache object by using the Cache property of the HttpContext class in the ‘System.Web’

namespace or by using the Cache property of the Page object.

 

What are dependencies in cache and types of dependencies?

When you add an item to the cache, you can define dependency relationships that can force that

item to be removed from the cache under specific activities of dependencies. Example if the

cache object is dependent on file and when the file data changes you want the cache object to be

update. Following are the supported dependency:-

File dependency: – Allows you to invalidate a specific cache item when a disk

based file or files change.

Time-based expiration: – Allows you to invalidate a specific cache item depending

on predefined time.

Key dependency:- Allows you to invalidate a specific cache item depending when

another cached item changes.

 

What are different types of caching using cache object of ASP.NET?

You can use two types of output caching to cache information that is to be transmitted to and

displayed in a Web browser:

Page Output Caching

Page output caching adds the response of page to cache object. Later when

page is requested page is displayed from cache rather than creating the

page object and displaying it. Page output caching is good if the site is

fairly static.

Page Fragment Caching If parts of the page are changing, you can wrap the static sections as user

controls and cache the user controls using page fragment caching.

 

How will implement Page Output Caching?

Output cache functionality is achieved by using “OutputCache” attribute on ASP.NET page

header. Below is the syntax

<%@ OutputCache Duration="20" Location="Server" VaryByParam="state"VaryByCustom="minorversion" VaryByHeader="Accept-Language"%>
  • VaryByParam: – Caches different version depending on input parameters send

through HTTP POST/GET.

  • VaryByHeader: – Caches different version depending on the contents of the page

header.

  • VaryByCustom: –Lets you customize the way the cache handles page variations

by declaring the attribute and overriding the GetVaryByCustomString handler.

  • VaryByControl: –Caches different versions of a user control based on the value of

properties of ASP objects in the control.

 

Simple Example for Implementing Output Caching in ASP.Net/C#

Here we are going to demonstrate a very simple example for implementing ASP.Net Output Cache mechanism. In the below ASPX page we included Output Cache tage with duration of 20Sec. So the page will be cached for the next 20 Secs. After 20 Seconds, it will again loaded from the server.

 

Using Duration option

<%@ OutputCache Duration="20" VaryByParam="none" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="OutputCaching.aspx.cs" Inherits="FragmentCaching.OutputCaching" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
   <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Post Back"  />
        <p>
            The page will be cached 20seconds, and then you can                   click Button to update datetime.
        </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByControl option

<%@ OutputCache Duration="2000" VaryByControl="ddlOption" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>OutPut Cache Using VaryByControl Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:DropDownList ID="ddlOption" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlOption_SelectedIndexChanged"><asp:ListItem Selected="True">Option One</asp:ListItem>            <asp:ListItem>Option Two</asp:ListItem>
            <asp:ListItem>Option Three</asp:ListItem>
        </asp:DropDownList>
        <p>
            The page will be rendered from cache basing on the selected item of DropDownList.
            The different item has corresponding cache.
    </p>
    </div>
    </form>
</body>
</html>

 

Using VaryByCustom

<%@ OutputCache Duration="2000" VaryByCustom="browser" VaryByParam="none" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>OutPut Cache Using VaryByCustom Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>        <br />
        <br />
        <asp:Button ID="btnPostBack" runat="server" Text="Submit" />
        <p>
            The page will be rendered from cache basing            on the version of browser, such as IE and FireFox.
        </p>
    </div>
    </form>
</body>
</html> 

Using VaryByParam

<%@ OutputCache Duration="2000" VaryByParam="productID" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="myHeader" runat="server">
    <title>OutPut Cache Using VaryByParam Option</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="lblResult" runat="server"></asp:Label>
        <p>
            The page will be rendered from cache until the value of QueryString named "productID" is changed or Duration is expiration.        </p>
    </div>
    </form>
</body>
</html>

 

How will implement Page Fragment Caching?

 

FragmentCaching.aspx:

Fragment caching is useful when you need to cache only a subset of a page. Navigation bars, header, and footers are good candidates for fragment caching. Here we are creating a ASPX page with two usercontrols inside it. We can control the caching of each usercontrols using fragment option as follows.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="FragmentCaching.aspx.cs" Inherits="ExperimentLab.FragmentCaching" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl1" Src="FragmentCtrl1.ascx" %>
<%@ Register TagPrefix="uc1" TagName="FragmentCtrl2" Src="FragmentCtrl2.ascx" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <p>
            WebForm Time:
            <asp:Label ID="Time" runat="server" ForeColor="Blue"></asp:Label>
        </p>
        <p>
            <uc1:FragmentCtrl1 ID="FragmentCtrl11" runat="server"></uc1:FragmentCtrl1>
        </p>
        <p>
            <uc1:FragmentCtrl2 ID="FragmentCtrl21" runat="server"></uc1:FragmentCtrl2>
        </p>
    </div>
    </form>
</body>
</html>

 

CodeBehind

protected void Page_Load(object sender, EventArgs e)        
{           
Time.Text = "WebFormTime: " + DateTime.Now.TimeOfDay.ToString();  }

FragmentCtrl1.ascx:

<%@ OutputCache Duration="40" VaryByParam="none"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl1.ascx.cs" Inherits="ExperimentLab.FragmentCtrl1" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>

 

CodeBehind :

protected void Page_Load(object sender, EventArgs e)        
{            
CacheEntryTime.Text = "FragmentCtrl1: " + DateTime.Now.TimeOfDay.ToString();       
}

 

FragmentCtrl2.ascx:

<%@ OutputCache Duration="60" VaryByParam="none" VaryByControl="MyRadioButtonList"%>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="FragmentCtrl2.ascx.cs" Inherits="ExperimentLab.FragmentCtrl2" %>
<asp:Label ID="CacheEntryTime" runat="server"></asp:Label>
<p>
    <asp:RadioButtonList ID="MyRadioButtonList" runat="server">        <asp:ListItem Selected="True">Yes</asp:ListItem>
        <asp:ListItem>No</asp:ListItem>
        <asp:ListItem>Maybe</asp:ListItem>
    </asp:RadioButtonList>
</p>
<p>
    <asp:Button ID="Button1" runat="server" Text="Submit" />
</p>

 

Code Behind :

protected void Page_Load(object sender, EventArgs e)        
{           
CacheEntryTime.Text = "FragmentCtrl2: " + DateTime.Now.TimeOfDay.ToString();       
}

How to implement CAPTCHA image validation in ASP.Net/C# OR CAPTCHA image validator Sample in ASP.Net/C#

May 6, 2013 2 comments

                                   DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

What is CAPTCHA and why we are using CAPTCHA

A CAPTCHA  is a type of challenge-response test used in computing as an attempt to ensure that the response is generated by a human being. The process usually involves a computer asking a user to complete a simple test which the computer is able to grade. These tests are designed to be easy for a computer to generate but difficult for a computer to solve, but again easy for a human. If a correct solution is received, it can be presumed to have been entered by a human. A common type of CAPTCHA requires the user to type letters and/or digits from a distorted image that appears on the screen. Such tests are commonly used to prevent unwanted internet bots from accessing websites, since a normal human can easily read a CAPTCHA, while the bot cannot process the image letters and therefore, cannot answer properly, or at all.

How to implement CAPTCHA validation/CAPTCHA verification in ASP.Net/C#

CAPTCHA image can be generated using ASP.Net codes and we can validate the code that user enter with the code in the CAPTCHA image. Here we are going to do a sample application that demonstrates how to create a CAPTCHA image using C# codes and how we can validate the user inputs with the CPATCH code. We are having two aspx pages and one class .cs file in the sample application.

A very simple application sample for CPTCHA validation

In the page load, first of all we are creating a 6 digit random number and stored in the session. By using this random number we creates a image suing System.Drawing package by giving some width,height,font family and alignment of the numbers, So the user can able to view the codes in the CAPTCHA image but it is difficult to read using system.

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

Below is the Class that we used for creating a CAPTCHA image with random number

using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Drawing.Text;

namespace CaptchaImage
{
       /// <summary>
       /// Summary description for CaptchaImage.
       /// </summary>
       public class CaptchaImage
       {
              // Public properties (all read-only).
              public string Text
              {
                     get { return this.text; }
              }
              public Bitmap Image
              {
                     get { return this.image; }
              }
              public int Width
              {
                     get { return this.width; }
              }
              public int Height
              {
                     get { return this.height; }
              }

              // Internal properties.
              private string text;
              private int width;
              private int height;
              private string familyName;
              private Bitmap image;

              // For generating random numbers.
              private Random random = new Random();

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width and height.
              // ====================================================================
              public CaptchaImage(string s, int width, int height)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.GenerateImage();
              }

              // ====================================================================
              // Initializes a new instance of the CaptchaImage class using the
              // specified text, width, height and font family.
              // ====================================================================
              public CaptchaImage(string s, int width, int height, string familyName)
              {
                     this.text = s;
                     this.SetDimensions(width, height);
                     this.SetFamilyName(familyName);
                     this.GenerateImage();
              }

              // ====================================================================
              // This member overrides Object.Finalize.
              // ====================================================================
              ~CaptchaImage()
              {
                     Dispose(false);
              }

              // ====================================================================
              // Releases all resources used by this object.
              // ====================================================================
              public void Dispose()
              {
                     GC.SuppressFinalize(this);
                     this.Dispose(true);
              }

              // ====================================================================
              // Custom Dispose method to clean up unmanaged resources.
              // ====================================================================
              protected virtual void Dispose(bool disposing)
              {
                     if (disposing)
                           // Dispose of the bitmap.
                           this.image.Dispose();
              }

              // ====================================================================
              // Sets the image width and height.
              // ====================================================================
              private void SetDimensions(int width, int height)
              {
                     // Check the width and height.
                     if (width <= 0)
                           throw new ArgumentOutOfRangeException("width", width, "Argument out of range, must be greater than zero.");
                     if (height <= 0)
                           throw new ArgumentOutOfRangeException("height", height, "Argument out of range, must be greater than zero.");
                     this.width = width;
                     this.height = height;
              }

              // ====================================================================
              // Sets the font used for the image text.
              // ====================================================================
              private void SetFamilyName(string familyName)
              {
                     // If the named font is not installed, default to a system font.
                     try
                     {
                           Font font = new Font(this.familyName, 12F);
                           this.familyName = familyName;
                           font.Dispose();
                     }
                     catch (Exception ex)
                     {
                           this.familyName = System.Drawing.FontFamily.GenericSerif.Name;
                     }
              }

              // ====================================================================
              // Creates the bitmap image.
              // ====================================================================
              private void GenerateImage()
              {
                     // Create a new 32-bit bitmap image.
                     Bitmap bitmap = new Bitmap(this.width, this.height, PixelFormat.Format32bppArgb);

                     // Create a graphics object for drawing.
                     Graphics g = Graphics.FromImage(bitmap);
                     g.SmoothingMode = SmoothingMode.AntiAlias;
                     Rectangle rect = new Rectangle(0, 0, this.width, this.height);

                     // Fill in the background.
                     HatchBrush hatchBrush = new HatchBrush(HatchStyle.SmallConfetti, Color.LightGray, Color.White);
                     g.FillRectangle(hatchBrush, rect);

                     // Set up the text font.
                     SizeF size;
                     float fontSize = rect.Height + 1;
                     Font font;
                     // Adjust the font size until the text fits within the image.
                     do
                     {
                           fontSize--;
                           font = new Font(this.familyName, fontSize, FontStyle.Bold);
                           size = g.MeasureString(this.text, font);
                     } while (size.Width > rect.Width);

                     // Set up the text format.
                     StringFormat format = new StringFormat();
                     format.Alignment = StringAlignment.Center;
                     format.LineAlignment = StringAlignment.Center;

                     // Create a path using the text and warp it randomly.
                     GraphicsPath path = new GraphicsPath();
                     path.AddString(this.text, font.FontFamily, (int) font.Style, font.Size, rect, format);
                     float v = 4F;
                     PointF[] points =
                     {
                           new PointF(this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, this.random.Next(rect.Height) / v),
                            new PointF(this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v),
                           new PointF(rect.Width - this.random.Next(rect.Width) / v, rect.Height - this.random.Next(rect.Height) / v)
                     };
                     Matrix matrix = new Matrix();
                     matrix.Translate(0F, 0F);
                     path.Warp(points, rect, matrix, WarpMode.Perspective, 0F);

                     // Draw the text.
                     hatchBrush = new HatchBrush(HatchStyle.LargeConfetti, Color.LightGray, Color.DarkGray);
                     g.FillPath(hatchBrush, path);

                     // Add some random noise.
                     int m = Math.Max(rect.Width, rect.Height);
                     for (int i = 0; i < (int) (rect.Width * rect.Height / 30F); i++)
                     {
                           int x = this.random.Next(rect.Width);
                           int y = this.random.Next(rect.Height);
                           int w = this.random.Next(m / 50);
                           int h = this.random.Next(m / 50);
                           g.FillEllipse(hatchBrush, x, y, w, h);
                     }

                     // Clean up.
                     font.Dispose();
                     hatchBrush.Dispose();
                     g.Dispose();

                     // Set the image.
                     this.image = bitmap;
              }
       }
}

DOWNLOAD SOURCE CODE FOR CAPTCHA IMAGE VALIDATION IN ASP.NET

%d bloggers like this: