Tuesday 24 March 2009

Implementing Fragment caching in ASP.NET 2.0

Caching in ASP.Net world means to store whole rendered html page or data e.g dataset or a part of page such as controls in server's memory for specific period of time and that cached items would be accessed for short period of time without executing code to process same data or page again. Whole idea behind this is to minimize the execution of code to do same task on consecutive clicks by one or more users increase performance.
However one should be careful in selecting caching techniques as it is not always an option for all kind of web applications e.g Displaying Real Pricing or showing Real time Tennis,Cricket match score.

What is fragment caching?
to store a part of page in memory rather than whole page for a specified period of time.Fragment caching is done by using User controls.

Here is Steps for implementing Fragement caching.

  1. Create a web site(or open a website you already created)
  2. Right click on project and select Add new Item from pop-up menu.
  3. Select WebUserControl from Templates.



In fragment caching , output directive is used in user control .ascx file.It should not be placed in main page(page which host user control).Set the duration for outputcache to 20 seconds.


<%@ Control Language="C#" AutoEventWireup="true" CodeFile="CachedContent.ascx.cs" Inherits="CachedContent" %>

<%@ OutputCache Duration ="20" VaryByParam="None" %>

<div id="outputdiv" style="clear: none; display: block; left: 50px; visibility: visible; width: 752px; position: relative; top: 50px; height: 100px; background-color: powderblue;">

cached Time

<asp:Label id="head1" runat="server" Font-Bold="True" Font-Names="Tahoma" Font-Size="XX-Large"><%# DateTime.Now.ToLongTimeString() %>asp:Label>

div>

On page load of user control , use this code.

head1.DataBind();

on user control hosting page(main page) place this code on declarative part of the page



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="OutputcacheTest.aspx.cs" Inherits="OutputcacheTest" %>

<%@ Register Src="CachedContent.ascx" TagName="CachedContent" TagPrefix="uc1" %>


then place this code after form tag in same page.

<div id="H2" style="clear: none; display: block; left: 34px; visibility: visible; width: 752px; position: relative; top: 30px; height: 100px; background-color: gainsboro;">

Non cache Time

<h1 id="H1_1" runat="server">

<%# DateTime.Now.ToLongTimeString() %>

h1>

div>

<asp:Button ID="gettime" runat ="server" style="clear: none; display: block; left: 271px; visibility: visible; position: relative; top: 269px; background-color: gainsboro;" Height="47px" Text="Get time" Width="177px" OnClick="gettime_Click" />

<uc1:CachedContent ID="CachedContent1" runat="server" />


on page load of main page write down tis code.



using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

public partial class OutputcacheTest : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

System.Web.UI.HtmlControls.HtmlGenericControl header2 = new HtmlGenericControl();

header2 = (System.Web.UI.HtmlControls.HtmlGenericControl)Page.FindControl("H1_1");

header2.DataBind();

}

protected void gettime_Click(object sender, EventArgs e)

{

}

}


I placed header tag and bind it with current datetime on page while I also placed User control which displays current datetime with declarative Output cache.

when I execute main page ,I see new datetime for the code i placed on main page each time refresh the page(page is posted back to server), however, user control time didnt change it retrives the rendered html from memory until specified period is elapsed.






Monday 16 March 2009

Code for creating PieChart in ASP.NET 2.0

GDI+ is great innovation in .NET and it is not limited to desktop applications , you can also use it in ASP.net pages.Here in example code is used to draw a pie chart in asp.net web page using GDI+ Classes of drawings.

Import all Drawings name spaces.


using System.Drawing.Drawing2D;

using System.Drawing;

using System.Drawing.Design;

using System.Drawing.Imaging;

using System.Drawing.Text;

Since to determine the angle of each sector in pie chart we follow following math formula

x°=value of Item A/Total value of all items * 360°


Place a listbox and a button on page. fill listbox with some items





float angletosweep=0;

float totalangle=0;

int _TotalvalueOfAllItems = 0;

for (int index = 0;
index &lt; ListBox1.Items.Count; index++)

{

_TotalvalueOfAllItems += Convert.ToInt32(ListBox1.Items[index].Text.Trim());

}

Bitmap _InMemoryBitmap = new Bitmap(200, 200);

Graphics g = Graphics.FromImage(_InMemoryBitmap);

Pen _pen = new Pen(Color.Indigo);

Rectangle _rectangle = new Rectangle(20, 20, 100,
100);

SolidBrush _brush = new
SolidBrush(Color.Indigo);

for(int
item=0;item<ListBox1.Items.Count;item++)

{

angletosweep = 360 *(Convert.ToInt32(ListBox1.Items[item].Text)) /
(_TotalvalueOfAllItems);

g.FillPie(new SolidBrush(ColorCodes(item)), _rectangle, totalangle,
angletosweep);

//some code omitted.


}

_InMemoryBitmap.Save(Response.OutputStream, ImageFormat.Jpeg);

g.Dispose();

_InMemoryBitmap.Dispose();

}

private Color
ColorCodes(int item)

{

Color[] _colorcodes = new Color[] { Color.Green, Color.Yellow ,
Color.LightCoral, Color.Turquoise , Color.Tomato ,
Color.Tan };

return _colorcodes[item];

}


call this page from another page and place the url into img tag of calling page.

Monday 9 March 2009

Adding a Sitemap to ASP.Net application

It is always a good practice to implement some navigation system for a website that has more than one web page.ASP.net implements various navigation controls including
Sitemappath ,TreeView,Menu.All these three controls use SiteMapDataSource which fetchs data from either xml file called web.sitemap through xmlSiteMapProvider or from database through custom sitemap provider.

Implement a Sitemap with Web.sitemap

On project->Right Click->select Add New Item.

Select Sitemap from the template and Click Add



Add aspx pages paths to sitemapnode node in web.sitemap file



<?xml
version="1.0" encoding="utf-8"
?>



<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0">


<siteMapNode title="Home" description="Home" url ="~/default.aspx"
>


<siteMapNode title="Register"
description="
Register New
User
" url ="~/Register.aspx"
/>


</siteMapNode>


</siteMap>


Place a SitemapDataSource,SitemapPath,TreeView Controls on Master page.Set name property of SitemapDatasource.


Sitemapdatasource is


<asp:SiteMapDataSource ID="dtmap" runat ="server" />




Add
Sitemappath

<asp:SiteMapPath ID="SiteMapPath1" runat="server" Font-Names="Verdana" Font-Size="Small"


PathSeparator=" >" >


<PathSeparatorStyle Font-Bold="True" ForeColor="#507CD1" />


<CurrentNodeStyle ForeColor="#333333" />


<NodeStyle Font-Bold="True" ForeColor="#284E98" />


<RootNodeStyle Font-Bold="True" ForeColor="#507CD1" />



</asp:SiteMapPath>



Add tree view and set its datasource to sitemapdatasource.

<asp:TreeView ID="TreeView1" runat="server" DataSourceID="dtmap" ImageSet="Arrows"

ShowLines="True">

<ParentNodeStyle Font-Bold="False" />

<HoverNodeStyle Font-Underline="True" ForeColor="#5555DD" />

<SelectedNodeStyle Font-Underline="True" ForeColor="#5555DD" HorizontalPadding="0px"

VerticalPadding="0px" />

<NodeStyle Font-Names="Tahoma" Font-Size="10pt" ForeColor="Black" HorizontalPadding="5px"

NodeSpacing="0px" VerticalPadding="0px" />

</asp:TreeView>






Monday 2 March 2009

Model View Controller MVC in ASP.NET 2.0

Model View Controller MVC is a design pattern that is practiced in asp.net particularly to separate Data Access layer,Business Logic layer and presenatation layer.In MVC , Model is data ,Data access classes, Controller is business logic classes and View is classes,control, pages that represent data to view in differnt ways.It is Controller who pass and get data netween View and Model.

In Viiusual Studio 2008, Microsoft has implemented MVC pattern.There is MVC templates in Viusal studio 2008 with .NET 3.5.However There is no way to implement thsese tempales in ASP.net 2.0 and visual studio 2005.To Implement MVC in .Net 2.0 and Visual studio 2005, we need to create our own classes.
The Logic is pretty simple.
  • Create classes that implement data access code.(e.g inserting,updating,deleting data using ado.net classes).That will be our Model
  • Create classes that acts as middle layer between presentation layer and Model.(e.g sending and receing reselts between data Access classes and asp.net aspx page) thta will be our Controller.
  • Create Page,user Control(.ascx),Datalist controls that display data.That will be our View.