Tuesday, September 28, 2010

Data Caching with Dataset

In the below example we are going to see that how we can apply Data caching on a Dataset object
Step 1. Create a web form DataCachingPage.aspx
Source View


Note : Replace ! with < and * with >
!%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataCachingPage.aspx.cs" Inherits="DataCachingPage" %*

!!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*
!script language="javascript" src="JScript.js" *

!/script*
!/head*
!body*
!form id="form1" runat="server"*
!div style="height: 274px; width: 362px"*

!asp:GridView ID="grvDataCaching" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Height="257px" Width="337px"*
!/asp:GridView*
!br /*
!input id="Submit1" type="submit" value="Open Window" onclick ="startMethod()" /*
!/div*
!/form*
!/body*
!/html*
Code View
using System.Web.Caching;

public partial class DataCachingPage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//In the Below scenerion we are using Output Caching
//Step: 1 Fill a Dataset Object with a Locally bulid XM File.

FillDataSet fds = new FillDataSet() { file_Path=@"C:\Documents and Settings\BS26691\Desktop\Test.xml"};
grvDataCaching.DataSource = fds.returnDataSet();
grvDataCaching.DataBind();

//Add the created Dataset into the Cache Object

/*------------ Description of Supplied parameters.---------
1. "Dataset"=Key Name of Cache object.
2. fds.returnDataSet()=Value which is kept inside the Cache object
3. new CacheDependency(fds.file_Path)=Object of CacheDependency Class
* This Parameter is set only in those scenerion where we want to Update our cache object
* specific to a file or Resource.
* In the below scenerion if XMl File is Changed
* than Cache Object will be Updated Accordingly
* If there is no CacheDependency than set it as Null
4. DateTime.MaxValue=Absolute Expiration
* IF we want that our cache will be expired after certain ammount of time
* Than we use this type of Expiration
* e.g Weather ForCasting where we are sure for data to be cached for a whole day.
* if we are not setting this than we need to set it as DateTime.MaxValue
5. TimeSpan.FromMinutes(20)=Slidding Expiration Time
* in the above scenerio the Cache object will be expired after 20 second of its access.
* That means it will not be expired after 20 second
* If Cache is accessed in last 19th second the it is going to persist for next 21 seconds.
* if we are not setting this than we need to set it as TimeSpan.Zero
------------------------------------------------------------------------------
* Note: AT A SINGLE TIME ONLY ONE PARAMETR NEED TO BE SET AMONG 4 AND 5
* BOTH PARAMETER CAN'T BE SET SIMULTANEOUSLY
------------------------------------------------------------------------------
*/

Cache.Insert("Dataset", fds.returnDataSet(), new CacheDependency(fds.file_Path), DateTime.MaxValue, TimeSpan.FromMinutes(20));

}
}

Step 2. Create a Page POP_UP_window.aspx
Source View
Note : replace ! with <>

!%@ Page Language="C#" AutoEventWireup="true" CodeFile="POP_UP window.aspx.cs" Inherits="POP_UP_window" %*
!!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*
!script language="javascript" src="JScript.js" *

!/script*
!style type="text/css"*
#Submit1 {
width: 121px;
}
!/style*
!/head*
!body*
!form id="form1" runat="server"*
!div*
Transported Data.
!br /*
!br /*
!br /*
!asp:GridView ID="grvDataCaching" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" Height="224px" Width="367px"
AllowPaging="True"*
!RowStyle BackColor="#EFF3FB" /*
!/asp:GridView*
!br /*
!/div*
!p*
!/p*
!input id="Button2" type="Exit" value="button" OnClick="CloseMethod()" /*

!/form*

!/body*
!/html*
Code View :
public partial class POP_UP_window : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{

//Retrive DataSet Value From Cache Object
DataSet ds = Cache["Dataset"] as DataSet ;

// Always Check for Null reference before accessing the Cache object.
if (ds == null)
{

//If Cache is Blank than fill the dataset with local Test xml file
FillDataSet fds = new FillDataSet() { file_Path = @"C:\Documents and Settings\BS26691\Desktop\Test.xml" };
// Add Dataset Object to Cache
Cache.Insert("Dataset", fds.returnDataSet());
}
//Fill your GridView with Cache Object
DataSet dset = Cache["Dataset"] as DataSet;
grvDataCaching.DataSource = dset;
grvDataCaching.DataBind();

}

}
Step 3. Create Class FillDataSet
public class FillDataSet
{
public string file_Path { get; set; }

public FillDataSet()
{
}
public DataSet returnDataSet()
{
DataSet ds = new DataSet();
ds.ReadXml(file_Path);
return ds;
}

}

Step 4. Create a File JScript.js

//This Function is called by a HTMl button
function startMethod() {
alert("After This Event POP-UP window will be Open.");
/*
"http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx" Repalce this Path with exact Page Path
*/

mywindow = window.open("http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx", "mywindow", "location=1,status=1,scrollbars=1");
mywindow.moveTo(10, 5);

}
// This method will Close the Open POP-UP window.
function CloseMethod() {
alert("Do You Want to Close This Window");
/*
"http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx" Repalce this Path with exact Page Path
*/
if (window.open("http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx", "mywindow", "location=1,status=1,scrollbars=1,width=500,height=500")) {
window.close();
}
}

Note : Set the DataCachingPage.aspx As Start Page

Data Caching

using System.Web.Caching;

Step 1. Cretae a Class DataCachingPage
Source View
Note : replace ! with < and * with >

!%@ Page Language="C#" AutoEventWireup="true" CodeFile="DataCachingPage.aspx.cs" Inherits="DataCachingPage" %*

!!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*
!script language="javascript" src="JScript.js" *

!/script*
!/head*
!body*
!form id="form1" runat="server"*
!div style="height: 274px; width: 362px"*

!asp:GridView ID="grvDataCaching" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="None" Height="257px" Width="337px"*
!/asp:GridView*
!br /*
!input id="Submit1" type="submit" value="Open Window" onclick ="startMethod()" /*
!/div*
!/form*
!/body*
!/html

.CS File.
protected void Page_Load(object sender, EventArgs e)
{
//In the Below scenerion we are using Output Caching
//Step: 1 Fill a Dataset Object with a Locally bulid XM File.
FillDataSet fds = new FillDataSet() { file_Path=@"C:\Documents and Settings\BS26691\Desktop\Test.xml"};
grvDataCaching.DataSource = fds.returnDataSet();
grvDataCaching.DataBind();
//Add the created Dataset into the Cache Object

/*------------ Description of Supplied parameters.---------
1. "Dataset"=Key Name of Cache object.
2. fds.returnDataSet()=Value which is kept inside the Cache object
3. new CacheDependency(fds.file_Path)=Object of CacheDependency Class
* This Parameter is set only in those scenerion where we want to Update our cache object
* specific to a file or Resource.
* In the below scenerion if XMl File is Changed
* than Cache Object will be Updated Accordingly
* If there is no CacheDependency than set it as Null
4. DateTime.MaxValue=Absolute Expiration
* IF we want that our cache will be expired after certain ammount of time
* Than we use this type of Expiration
* e.g Weather ForCasting where we are sure for data to be cached for a whole day.
* if we are not setting this than we need to set it as DateTime.MaxValue
5. TimeSpan.FromMinutes(20)=Slidding Expiration Time
* in the above scenerio the Cache object will be expired after 20 second of its access.
* That means it will not be expired after 20 second
* If Cache is accessed in last 19th second the it is going to persist for next 21 seconds.
* if we are not setting this than we need to set it as TimeSpan.Zero
------------------------------------------------------------------------------
* Note: AT A SINGLE TIME ONLY ONE PARAMETR NEED TO BE SET AMONG 4 AND 5
* BOTH PARAMETER CAN'T BE SET SIMULTANEOUSLY
------------------------------------------------------------------------------
*/

Cache.Insert("Dataset", fds.returnDataSet(), new CacheDependency(fds.file_Path), DateTime.MaxValue, TimeSpan.FromMinutes(20));

}

Step 2. Create a Class POP_UP window.aspx
Source View
Note : replace ! with < and * with >

!%@ Page Language="C#" AutoEventWireup="true" CodeFile="POP_UP window.aspx.cs" Inherits="POP_UP_window" %*
!!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*
!script language="javascript" src="JScript.js" *

!/script*
!style type="text/css"*
#Submit1 {
width: 121px;
}
!/style*
!/head*
!body*
!form id="form1" runat="server"*
!div*
Transported Data.
!br /*
!br /*
!br /*
!asp:GridView ID="grvDataCaching" runat="server" CellPadding="4"
ForeColor="#333333" GridLines="None" Height="224px" Width="367px"
AllowPaging="True"*
!RowStyle BackColor="#EFF3FB" /*
!/asp:GridView*
!br /*
!/div*
!p*
!/p*
!input id="Button2" type="Exit" value="button" OnClick="CloseMethod()" /*

!/form*

!/body*
!/html*
.CS File
protected void Page_Load(object sender, EventArgs e)
{

//Retrive DataSet Value From Cache Object
DataSet ds = Cache["Dataset"] as DataSet ;

// Always Check for Null reference before accessing the Cache object.
if (ds == null)
{
//If Cache is Blank than fill the dataset with local Test xml file
FillDataSet fds = new FillDataSet() { file_Path = @"C:\Documents and Settings\BS26691\Desktop\Test.xml" };
// Add Dataset Object to Cache
Cache.Insert("Dataset", fds.returnDataSet());
}
//Fill your GridView with Cache Object
DataSet dset = Cache["Dataset"] as DataSet;
grvDataCaching.DataSource = dset;
grvDataCaching.DataBind();

}

Step 3. Add A Third Class

public class FillDataSet
{
public string file_Path { get; set; }

public FillDataSet()
{
}
public DataSet returnDataSet()
{
DataSet ds = new DataSet();
ds.ReadXml(file_Path);
return ds;
}

}


Step 4.
Add A JScript.js File.
//This Function is called by a HTMl button
function startMethod() {
alert("After This Event POP-UP window will be Open.");
/*
"http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx" Repalce this Path with exact Page Path
*/
mywindow = window.open("http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx", "mywindow", "location=1,status=1,scrollbars=1");
mywindow.moveTo(10, 5);

}
// This method will Close the Open POP-UP window.
function CloseMethod() {
alert("Do You Want to Close This Window");
/*
"http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx" Repalce this Path with exact Page Path
*/
if (window.open("http://localhost:4909/DataCaching%2027_1.0/POP_UP%20window.aspx", "mywindow", "location=1,status=1,scrollbars=1,width=500,height=500")) {
window.close();
}
}

Sunday, September 26, 2010

Caching with Cache Object

//Use the below NameSpace for caching.
//In .NET data caching is main done using two classes in System.Web.Caching namespace namely "Cache" and "CacheDependency".

using System.Web.Caching;

string value="";
//Add and item to cache: To add an object in cache following syntax is used
//Explanation: Using the below syntax we can store the item in the cache.
//This entry will have no dependencies on it.
//Dependencies like it will not expire unless the cache engine removes it.

Cache["key"] = value;
//Explanation: The above syntax is used to retrieve the value form cache
value = (string)Cache.Get("key");
//Explanation: Above statement will remove the key cached object from cache
Cache.Remove("key");

Out Put Caching in .net

Caching is the way of improving performance of web Application.
Note : Please replace ! with >
and * with >
before running the below code
In .net we can cache whole page (i.e. Output caching), part of page (i.e. fragment caching) and data cache.
1. whole page (i.e. Output caching):
!%@ OutputCache Duration="20" VaryByParam="none" %*
Description: Single copy of Page will be cached for 20 seconds.
Note: doesn’t support for the dynamic pages that vary their output based on the query string.
Since page will be cached for the upcoming 20 seconds,and output page will remain same for 20 seconds regardless the varying url.
e.g
www.dummyUrl.com?Studentid=1
if we apply caching on the above page for 20 seconds than
on changing ?Studentid=2 will return previous page only
www.dummyUrl.com?Studentid=2 goes to www.dummyUrl.com?Studentid=1

Caching with Specific Query String Parameters:
!%@ OutputCache Duration="20" VaryByParam="*" %*


It will cache all the query string based pages
Note: in this case unwanted query string based pages will be cached

!%@OutputCacheDuration="20 VaryByParam="Projectid;ProjectName” %*
It will cache only those pages which are having Projectid and ProjectName in Query string.

2. part of page (i.e. fragment caching):
In this case, you identify just the content you want to cache, wrap that in a dedicated User Control and cache just the output from that control.
Step 1. Create a User Control say “FragmentCtrl1.ascx”.
Source view:
!%@ Control Language="C#" AutoEventWireup="true" CodeFile="FragmentCtrl1.ascx.cs" Inherits="FragmentCtrl1" %*
!%@ OutputCache Duration="20" VaryByParam="none" VaryByControl="MyRadioButtonList"%*

!asp:Label ID="CacheEntryTime" runat="server" Font-Bold="True"*!/asp:Label*

!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*

!asp:Button ID="Button1" runat="server" Text="Submit" /*

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

Step 2. Create a User Control say “FragmentCaching.aspx”.
Source view:
!%@ Page Language="C#" AutoEventWireup="true" CodeFile="FragmentCaching.aspx.cs" Inherits="FragmentCaching" %*

!%@ Register TagPrefix="uc1" TagName="FragmentCtrl1" Src="FragmentCtrl1.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*
!asp:Label ID="Time" runat="server" Font-Bold="True"*!/asp:Label*
!/p*

!p*
!uc1:FragmentCtrl1 id="FragmentCtrl1" runat="server"*
!/uc1:FragmentCtrl1*
!/p*

!/div*
!/form*
!/body*
!/html*

FragmentCaching.asppx.cs File:

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

Thursday, September 23, 2010

Nested Master Pages in .net 3.5

Note: Replace ! with <>

Step:1

File--*New--*website--*ASP.net website--*Solution explorer

Right Click on Project--*Add New Item---*Master Page
(Name=Parent_MasterPage.master,select CheckBox "place Code in Seperate File",Unselect CheckBox "Select Master Page")
Source view:
Remove all content from form tag and paste the below source view:
Note: Replace ! with <
and * with >
!div*
!h4*Parent master Page!/h4*
!br /*
!asp:Image ID="Image1" runat="server"
DescriptionUrl="~/Images/trial header.bmp" Height="122px"
ImageUrl="~/Images/trial header.bmp" Width="905px" /*
!p* !/p*
!asp:ContentPlaceHolder id="Parent_ContentPlaceHolder" runat="server"*
!/asp:ContentPlaceHolder*
!b*Footer of Parent Master Page:!/b*
mailto*copy Right Act 1984
!/div*

Step:2
Cretation of Master page 2nd.

Right Click on Project--*Add New Item---*Master Page(Name=Child_MasterPage.master,select CheckBox "place Code in Seperate File",select CheckBox "Select Master Page")


Source view
:
Note: Replace ! with <
and * with >
!%* Master Language="C#" MasterPageFile="~/Parent_MasterPage.master" %*
!asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"*
!/asp:Content*
!asp:Content ID="Content2" ContentPlaceHolderID="Parent_ContentPlaceHolder" Runat="Server"*
!asp:Panel ID="Panel1" BackColor="AliceBlue" runat="server"*
!b*Child Master Page!/b*
!br /*
!asp:Image ID="Image1" runat="server" Height="125px" ImageUrl="~/Images/mid_big.gif" Width="787px" /*
!br /*
!asp:ContentPlaceHolder ID="Child_CP1" runat="server" *
!/asp:ContentPlaceHolder*
!b*Footer of Child Master Page:!/b*
mailto*copy Right Act 2001
!/asp:Panel*
!/asp:Content*
Step:3

Right Click on Project--*Add New Item---*Web Form(Name=Default2.aspx,select CheckBox "place Code in Seperate File",select CheckBox "Select Master Page")
Click on Add button:
Among both master pages ,Select Child_MasterPage.master

Replace the Source view of Default2.aspx with this:
Note: Replace ! with <
and * with >
!%* Page Title="" Language="C#" MasterPageFile="~/Child_MasterPage.master" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %*
!asp:Content ID="Content1" ContentPlaceHolderID="Child_CP1" Runat="Server"*
This is Content page derived from a Nested master Page:
U can Put ur Controls here.
!asp:Image ID="Image1" runat="server" Height="385px"
ImageUrl="~/Images/innerpage1_dataentry.jpg" Width="635px" /*
!/asp:Content*

Set Default2.aspx as start page and run the application.
Note: Please give a valid image url as per ur convenient.

Wednesday, September 22, 2010

Event Sequence oF Master & Content Pages.

Master and Content Page Event Sequence.

1. Content Page: Page_PreInit event.
2. Master page : Page_Init event
3. Content Page :Page_Init event
4. Content Page : Page_Load event
6. Master Page : Page_Load event
7. Content Page: Page_PreRender event
8. Master Page : Page_PreRender event
9. Master Page: Page_UnLoad event
10. Content Page: Page_UnLoad event

Sample Code :
Step 1.Create a Master Page say Parent_MasterPage and write the below code on Code behind file(.cs file )
Parent_MasterPage.cs
public partial class Parent_MasterPage : System.Web.UI.MasterPage
{

protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Master_Page_Load;" );
}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Master_Page_Init;" );
}
protected void Page_PreInit(object sender, EventArgs e)
{
Response.Write("Master_Page_PreInit;" );
}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Response.Write("Master_Page_UnLoad");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write("Master_Page_PreRender ;" );
}
protected void Page_Render(object sender, EventArgs e)
{
Response.Write("Master_Page_Render ;" );
}
}
Step 2.Create a Content Page say Default.aspx and write the below code on Code behind file(.cs file )
Default.cs
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//Code writtent for accessing the Control of Master page in Content pages
Label lbl = new Label();
lbl = (Label)Master.FindControl("Label1");
lbl.Text = "Lable Control of Master page is accessed in Content page and its value get changed.";

Response.Write( "Content_Page_Load;" );

}
protected void Page_Init(object sender, EventArgs e)
{
Response.Write("Content_Page_Init;");
}
protected void Page_PreInit(object sender, EventArgs e)
{

Response.Write("Content_Page_PreInit;" );

}
protected void Page_UnLoad(object sender, EventArgs e)
{
//Response.Write("Content_Page_UnLoad");
}
protected void Page_PreRender(object sender, EventArgs e)
{
Response.Write( "Content_Page_PreRender;");

}
protected void Page_Render(object sender, EventArgs e)
{
Response.Write ( "Content_Page_Render;" );

}
}