Search This Blog

Thursday, May 14, 2009

Caching in Asp.Net

ASP.NET supports two important forms of caching: Page (including sub-page) caching, and Data caching.

Page caching allows the server to store a copy of the output of a dynamic page, and to use this to respond to requests instead of running the dynamic code again. Sub-page caching does the same thing, but for parts of pages.

Data caching allows a web application to store commonly used objects so that they are available for use across all pages in the site. While it was possible to do this kind of thing in ASP, using the Application object, it’s a whole lot better in ASP.NET.

Page Caching :

Two types of page caching is there

a) Page Fragment Caching OR Partial Page Caching

b) Page Output Caching

Page Output Caching:

When we say that the output of a web page is cached, we imply that the web page output is stored in the cache memory. Whenever a new page request is made, the ASP.NET Cache Engine is activated. It checks whether there is a corresponding cache entry for this page. If one is found, it is known as a Cache hit, else, we say that a cache miss has occurred. If there is a cache hit, i.e., if the ASP.NET Cache engine finds a corresponding cache entry for this page, the page is rendered from the cache, otherwise, the page being requested is rendered dynamically.

Page Output caching can be specified in any of the two ways

1. By declaration

<%@ OutputCache Duration="no of seconds"
Location="Any | Client | Downstream | Server | None"
VaryByControl="control"
VaryByCustom="browser |customstring"
VaryByHeader="headers"
VaryByParam="parameter" %>


Where the Cached Data Stored?

when some makes a request from a website there are two types of cache that may satisfy the request without reaching the original server.

The first is the personal cache maintained by the user’s web browser (a ‘browser cache’).

The second is a shared cache present on the network between the user’s browser and the origin server (a ‘proxy cache’).

The page output cache maintained by ASP.NET on the web server is a further type of cache, but when you specify page caching - by setting the Location parameter - you can also make use of these first two sorts of caches.

The values of the OutputCacheLocation is given below.

Any [default]The page can be cached on any of: the browser; the proxy server; the web server.
ClientThe page is to be cached on the browser.
ClientThe page can be cached on the browser or a proxy server.
NoneThe page is not to be cached.
ServerThe page is to be cached on the web server.
ServerAndClientThe page can be cached on the browser or on the server.

when caching occurs elsewhere rather than on the server, treate manipulation of the HTTP 1.1 headers that deal with caching.

reference for details :‘Standard Caching over the Internet’ .

Cache Duration :

Pages remain in the cache for some length of time, determined by the Duration parameter. The value is set in seconds.

As we shall see later, if the page caching is set programmatically, rather than declaratively, one can also set a ‘Sliding Expiration’ value which increases the cache duration every time a page is requested.

OR

2. By Program

Response.Cache.SetCacheability (HttpCacheability.Server);

It is also possible to set the OutputCache on all the pages in an ASP.NET application programmatically in the Global.asax page. Refer to the code snippet that follows:--

void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.Server);
}

Page Fragment Caching :

It allows specific portions of the web page to be cached rather than caching the entire web page and is useful in situations where a particular web page can contain both static and dynamic content.

Data Caching :

will be comming soon



Conclusion

Caching is a great tool that can be used to boost the performance web applications.



Cookies in Asp.Net

Cookies

A Cookie is a small text file that the browser creates and stores on the hard drive of client machine. Cookie just one or more pieces of information stored as text strings. A Web server sends client a cookie and the browser stores it. The browser then returns the cookie to the server the next time the page is referenced. The most common use of a cookie is to store information about the User and preferences the user makes.

I order to create a cookie you have 2 variable must be defined as they are the cookie name and the duration of the cookie before it expired

How To Create Cookies In Asp.net & Get Cookie Value

protected void Page_Load(object sender, System.EventArgs e)
{
HttpCookie myCookie= new HttpCookie("Address");
myCookie["Country"] = "India";
myCookie["City"] = "Kolkata";
myCookie["Name"] = "Subhamay";
myCookie.Expires = DateTime.Now.AddDays(2);
Response.Cookies.Add(myCookie);
Label1.Text = "I have Created My own Cookie successfully!";

HttpCookie cookie = Request.Cookies["Address"];

if (cookie != null)
{
string country = cookie["Country"];
string city = cookie["City"];
string name = cookie["Name"];

}
}


Cookies With Key Value : A Different Approach

Creating New Cookie
HttpCookie myCookie = new HttpCookie("Cars");

add some key value to the cookie

myCookie.Values.Add("muffin", "chocolate");
myCookie.Values.Add("babka", "cinnamon");


add the cookie to cookie collection
Response.Cookies.Add(myCookie);
//how to get the keys and values stored in a cookie:

Response.Write(myCookie.Value.ToString());
The output to using this with the previous created cookie is this: "muffin=chocolate&babka=cinnamon".

Set Life Time Of A cookie

myCookie.Expires = DateTime.Now.AddHours(12); Or

myCookie.Expires = DateTime.Now.AddDays(7);


If Cookie Expires property is not set then cookie will be created for the current

browser instance
Setting the cookie's path

set a path for a cookie so that it will be available only for that path in your website

myCookie.Path = "/mydomain";
Setting the domain for a cookie

myCookie.Domain= "mydomain.mysite.com";

How To Destroy A Cookie

there is no method called delete or destroy ..So you can use

myCookie.Expires = DateTime.Now.AddDays(-1);
For Removing a subkey:

myCookie.Values.Remove("babka");



Tuesday, May 12, 2009

CheckBoxList

Populate CheckBoxList (List Control)

Creates a group of check boxes. Properties and events are identical to other list controls, such as DropDownList

Remove CheckBoxList Item By Item Text:

if (CheckBoxList1.Items.FindByText(itemValue) != null)
{
string itemText = CheckBoxList1.Items.FindByText(itemValue).Text;
ListItem li = new ListItem();
li.Text = itemText;
li.Value = itemValue;
Label1.Text = "Removed Item Is: " + itemText;
CheckBoxList1.Items.Remove(li);
}

Remove CheckBoxList Item By Item Value

if (CheckBoxList1.Items.FindByValue(itemValue) != null)
{
string itemText = CheckBoxList1.Items.FindByValue(itemValue).Text;
ListItem li = new ListItem();
li.Text = itemText;
li.Value = itemValue;
Label1.Text = "Item Found and remove: " + itemText;
CheckBoxList1.Items.Remove(li);
}

Add ListItem with Item Text and Value in CheckBoxList:


protected void Button1_Click(object sender, System.EventArgs e)
{
ListItem li = new ListItem();
li.Text = TextBox1.Text.ToString();
li.Value = TextBox2.Text.ToString();
CheckBoxList1.Items.Add(li);
Label1.Text = "ListItem added in CheckBoxList";

}

Use Theme & Skin In a Checkboxlist

runat="server"
BorderColor="Gray"
BorderWidth="2"
BackColor="White"
ForeColor="Black"
Font-Bold="true"
Font-Italic="true" RepeatColumns="3"
>

Programatically Bind CheckBoxList and Retrive Value with comma separator:

Bind:

chkInterest.DataSource = dataTable1
chkInterest.DataTextField = "Name"
chkInterest.DataValueField = "Id"
chkInterest.DataBind();

Retrieve:

protected void imgSubmit_Click(object sender, ImageClickEventArgs e)
{


string strInterests = "";
string strHobbies = "";


for (int i = 0; i < chkInterest.Items.Count; i++)
{
if (chkInterest.Items[i].Selected)
{
strInterests += chkInterest.Items[i].Text + ",";
}
}

strInterests = strInterests.Trim(new char[] { ',' });


for (int j = 0; j < chkListHobby.Items.Count; j++)
{
if (chkListHobby.Items[j].Selected)
{
strHobbies += chkListHobby.Items[j].Text + ",";
}

}

strHobbies = strHobbies.Trim(new char[] { ',' });


}

Array Class

Creating Arrays

The Array class is abstract, so using constructor array class can not be created.To create an arrays we use the static CreateInstance() method.

By this way type of the elements in advance is not necessary to be known, as the type is passed to the CreateInstance() method as a Type object.


Array MyArray= Array.CreateInstance(typeof(int), 5); //( type of Array,Size of Array)
for (int i = 0; i < 5; i++)
{
MyArray.SetValue(33, i);
}

for (int i = 0; i < 5; i++)
{
Console.WriteLine(MyArray.GetValue(i));
}

Copying Arrays


Arrays are reference types, assigning an array variable to another one it need two varriable referencing to the same array. For copying arrays, the array implements the interface ICloneable. The Clone() method that is defined with this interface creates a shallow copy of the array.

If the array contains reference types, the elements are not copied, just the references

Car[] cars= {
new Car("Car", "Toyota"),
new Person("Bike", "Yahamaha")
};
Car[] CarClone = (Car[])CarClone .Clone();

int[] intArray1 = { 1, 2 };
int[] intArray2 = (int[])intArray1.Clone();

Sorting Arrays


The Array class implements a bubble-sort for sorting the elements in the array. The Sort() method requires the interface IComparable to be implemented by the elements in the array. Simple types such as System.String and System.Int32 implement IComparable, so you can sort elements containing these types.

string[] names = {
"Subhamay",
"Chaki",
"Alok",
"Gautam"
};

Array.Sort(names);

foreach (string name in names)
{
Console.WriteLine(name);
}

If you are using custom classes with the array, you must implement the interface IComparable. This interface defines just one method CompareTo() that must return 0 if the objects to compare are equal, a value smaller than 0 if the instance should go before the object from the parameter, and a value larger than 0 if the instance should go after the object from the parameter.

Monday, May 11, 2009

Array

Simple Arrays

An array is a data structure that contains object/data of same type

Array Declaration

An array is declared by defining the type of the elements inside the array followed by empty brackets and a variable name; for example, an array containing integer elements is declared like this:


int [] sampleArray


Using Reference Types

arrays can be declared of a type of a custom class. Let Us take an example of "Product" class having two constructor an ToString() method


public class Product
{
public Product() //default constructor
{
}

public Product(string name, string description) //parametrized constructor
{
this.name = name;
this.description = description;
}

private string _name;
private string _description;

public string ProductName
{
get { return _name; }
set { _name = value; }
}

public string Description
{
get { return _description; }
set { _description = value; }
}

public override string ToString()
{
return name + " " + description;
}
}

Now Declaring an array of four is similar to declaring an array of int:

Product [] myProduct = new Product[4]

Here memory must be allocated for each array element otherwise a NullReferenceException will be thrown.


Multidimensional Arrays

1-dimension array are indexed by a single integer. A multidimensional array is indexed by two or more integers.

How To Declare Two Dimension Array

int[,] myarray = new int[3, 3];
myarray[0, 0] = 1;
myarray[0, 1] = 2;
myarray[0, 2] = 3;
myarray[1, 0] = 4;
myarray[1, 1] = 5;
myarray[1, 2] = 6;
myarray[2, 0] = 7;
myarray[2, 1] = 8;
myarray[2, 2] = 9;

How To Declare Three Dimension Array


int[,,] threedim = {
{ { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } },
{ { 9, 10 }, { 11, 12 } }
};

Jagged Arrays

A 2-dimensional array has a rectangular size (for example 3 by 3 elements). A jagged array is more flexible in sizing the array. With a jagged array every row can have a different size.

a 2-dimensional array that has 3x3 elements with a jagged array. The jagged array can contains three rows where the first row would have elements, the second row would have elements, and the third would have three elements.

int[][] jagged = new int[3][];
jagged[0] = new int[2] { 1, 2 };
jagged[1] = new int[6] { 3, 4, 5, 6, 7, 8 };
jagged[2] = new int[3] { 9, 10, 11 };

Itaration through for loop

for (int row = 0; row < jagged.Length; row++)
{
for (int element = 0; element < jagged[row].Length; element++)
{
Console.WriteLine("row: {0}, element: {1}, value: {2}",
row, element, jagged[row][element]);
}
}