You are on page 1of 16

http://asp.net-tutorials.

com/state/viewstate/

COOKIE
using System; using System.Data; using System.Web;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(Request.Cookies["BackgroundColor"] != null) { ColorSelector.SelectedValue = Request.Cookies["BackgroundColor"].Value; BodyTag.Style["background-color"] = ColorSelector.SelectedValue; } }

protected void ColorSelector_IndexChanged(object sender, EventArgs e) { BodyTag.Style["background-color"] = ColorSelector.SelectedValue; HttpCookie cookie = new HttpCookie("BackgroundColor"); cookie.Value = ColorSelector.SelectedValue; cookie.Expires = DateTime.Now.AddHours(1); Response.SetCookie(cookie); } }

SESSION
using System; using System.Data; using System.Web;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(Session["BackgroundColor"] != null) { ColorSelector.SelectedValue = Session["BackgroundColor"].ToString(); BodyTag.Style["background-color"] = ColorSelector.SelectedValue; } }

protected void ColorSelector_IndexChanged(object sender, EventArgs e) { BodyTag.Style["background-color"] = ColorSelector.SelectedValue; Session["BackgroundColor"] = ColorSelector.SelectedValue; } }

VIEW STATE
<%@ Page Language="C#" AutoEventWireup="true" Inherits="_Default" %> CodeFile="Default.aspx.cs" <!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>ViewState</title> </head> <body> <form id="form1" runat="server"> <asp:TextBox runat="server" id="NameField" /> <asp:Button runat="server" id="SubmitForm" onclick="SubmitForm_Click" text="Submit & set name" /> <asp:Button runat="server" id="RefreshPage" text="Just submit" /> <br /><br /> Name retrieved from ViewState: <asp:Label runat="server" id="NameLabel" /> </form> </body> </html>

And the CodeBehind:


using System; using System.Data; using System.Web;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if(ViewState["NameOfUser"] != null) NameLabel.Text = ViewState["NameOfUser"].ToString(); else NameLabel.Text = "Not set yet..."; }

protected void SubmitForm_Click(object sender, EventArgs e) { ViewState["NameOfUser"] = NameField.Text; NameLabel.Text = NameField.Text; } }

SENDING EMAILS
Sending e-mails with ASP.NET is pretty straight forward. The .NET framework comes with an entire namespace for handling e-mails, the System.Net.Mail namespace. In the following examples, we will use two classes from this namespace: The MailMessage class, for the actual e-mail, and the SmtpClient class, for sending the e-mail. As you may be aware, mails are sent through an SMTP server, and to send mails with the .NET framework, you will need access to an SMTP server. If you're testing things locally, the company that supplies your with Internet access, will usually have an SMTP server that you can use, and if you wish to use one of these examples on your actual website, the company that hosts your website will usually have an SMTP server that you can use. Go through the support pages to find the actual address - it's usually something along the lines of smtp.your-isp.com or mail.your-isp.com. Once you have an accessible SMTP server, we're ready to send our very first e-mail. For the first example, all you need is an empty page, with the following code in the CodeBehind:

protected void Page_Load(object sender, EventArgs e) { try { MailMessage mailMessage = new MailMessage(); mailMessage.To.Add("your.own@mail-address.com"); mailMessage.From = new MailAddress("another@mail-address.com"); mailMessage.Subject = "ASP.NET e-mail test"; mailMessage.Body = "Hello world,\n\nThis is an ASP.NET test e-mail!"; SmtpClient smtpClient = new SmtpClient("smtp.your-isp.com"); smtpClient.Send(mailMessage); Response.Write("E-mail sent!");

} catch(Exception ex) { Response.Write("Could not send the e-mail - error: " + ex.Message); } }

That's actually all you need to send an e-mail. We create a new MailMessage instance, add a new receiver, set the "From" address and the subject, and then we write a simple test message for the body of the e-mail. After that, we create a new instance of the SmtpClient, with the host address of the SMTP server that you may use as a parameter, and then we use the SmtpClient instance to shoot the e-mail out into cyberspace. The entire thing is surrounded by a try..catch block, just in case something goes wrong. This was just a very basic example, but there are a lot of other options. Here is a short list with interesting ideas: You can attach one or several files, simply by adding them to the Attachments collection. In this example, we attach a file called "image.jpg", located in the root of the ASP.NET website: mailMessage.Attachments.Add(new Attachment(Server.MapPath("~/image.jpg"))); You can send to more than one person at the same time, simply by adding another e-mail address to the "To" collection, like this: mailMessage.To.Add("your.own@mail-address.com"); mailMessage.To.Add("another@mail-address.com"); You can set a name for the sender - otherwise, only the e-mail address will be shown in the "From" column of the receivers e-mail client. For instance, like this: mailMessage.From = new MailAddress("me@mail-address.com", "My Name"); You can send HTML e-mails, instead of the default plaintext mails, to use more complicated layouts. Here is a simple example: mailMessage.IsBodyHtml = true; mailMessage.Body = "Hello <b>world!</b>";

You can use the CC and BCC fields, just like in regular e-mail messages, like this: mailMessage.CC.Add("me@mail-address.com"); mailMessage.Bcc.Add("me2@mailaddress.com"); You can set the priority of an e-mail, like this: mailMessage.Priority = MailPriority.High;

FILEUPLOAD CONTROL
With ASP.NET, accepting file uploads from users has become extremely easy. With the FileUpload control, it can be done with a small amount of code lines, as you will see in the following example. However, please notice that there are security concerns to to consider when accepting files from users! Here is the markup required:
<form id="form1" runat="server"> <asp:FileUpload id="FileUploadControl" runat="server" /> <asp:Button runat="server" id="UploadButton" text="Upload" onclick="UploadButton_Click" /> <br /><br /> <asp:Label runat="server" id="StatusLabel" text="Upload status: " /> </form>

And here is the CodeBehind code required to handle the upload:


protected void UploadButton_Click(object sender, EventArgs e) { if(FileUploadControl.HasFile) { try { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/") + filename); StatusLabel.Text = "Upload status: File uploaded!"; } catch(Exception ex) {

StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }

As you can see, it's all relatively simple. Once the UploadButton is clicked, we check to see if a file has been specified in the upload control. If it has, we use the FileUpload controls SaveAs method to save the file. We use the root of our project (we use the MapPath method to get this) as well as the name part of the path which the user specified. If everything goes okay, we notify the user by setting the Text property of the StatusLabel - if not, an exception will be thrown, and we notify the user as well. This example will get the job done, but as you can see, nothing is checked. The user can upload any kind of file, and the size of the file is only limited by the server configuration. A more robust example could look like this:
protected void UploadButton_Click(object sender, EventArgs e) { if(FileUploadControl.HasFile) { try { if(FileUploadControl.PostedFile.ContentType == "image/jpeg") { if(FileUploadControl.PostedFile.ContentLength < 102400) { string filename = Path.GetFileName(FileUploadControl.FileName); FileUploadControl.SaveAs(Server.MapPath("~/") + filename); StatusLabel.Text = "Upload status: File uploaded!"; } else

StatusLabel.Text = "Upload status: The file has to be less than 100 kb!"; } else StatusLabel.Text = "Upload status: Only JPEG files are accepted!"; } catch(Exception ex) { StatusLabel.Text = "Upload status: The file could not be uploaded. The following error occured: " + ex.Message; } } }

Here we use the two properties, ContentLength and ContentType, to do some basic checking of the file which the user is trying to upload. The status messages should clearly indicate what they are all about, and you can change them to fit your needs.

Handling Session for Login and Logout


//for SignIn protected void btnSignIn_Click(object sender, System.EventArgs e) { try {

f = new homePage(); DataSet dbSet = f.loadDatabase(Server.MapPath(strDatabase), "SELECT * FROM members WHERE username ='" + txtUsername.Text + "'"); // new DataSet(); bool boolSuccess = false;

if (dbSet != null) { foreach (DataRow dbRow in dbSet.Tables[0].Rows) { if (Convert.ToString(dbRow["pass"])) == txtPassword.Text) { liMessage.Text = "Login Successfully "; // Logged in? Session["LoggedIn"] = true; Session.Timeout = 60; // User info Session["User_Name"] = dbRow["username"]; Session["UserID"] = dbRow["usrid"]; Session["User_Email"] = dbRow["mail"]; Session["User_Info"] = dbRow["usrdescription"]; Session["admin"] = dbRow["admin"]; Session["su"] = dbRow["superuser"]; Session["User_SignupDate"] = dbRow["signupdate"]; Session["User_LastIP"] = dbRow["ipaddr"]; Session["User_LastLogin"] = dbRow["lastlogindate"]; boolSuccess = true; }

} }

dbSet.Dispose();

} catch { liMessage.Text = "There was an error while accessing the database. Please try agian later."; } } // for signOut protected void btnSignOut_Click(object sender, System.EventArgs e) { Session.Abandon(); Response.Redirect("../"); }

Every ASP.NET application needs to manage the state management technique because of the state less nature of HTTP Protocol. In ASP.NET we have state management techniques like Application State, Session state and View state. Today we are going to discuss Session state management in ASP.NET and new features of ASP.NET 4.0 Session State.

These are the differences between Session & Viewstate in .Net web applictions: 1) Viewstate is particular to a control/page whereas session is for the whole application. You can access the session data stored in page A in page B but viewstate does not behave so. 2) ViewState is maintained at client side whereas session is maintained at server side 3) Since viewstate is maintained at client, it does not have a concept of expiry but session will expire after the stipulated time 4) You can enable/disable view state for specific controls but you can't do that for session.

1)Viewstate will be stored as encrypted value in the client page itself, where as session will not be stored anywhere other than memory. 2)Since session uses memory more and if you wants to load lot of data in session you will be adding extra load on server. 3)Eventhough viewstate values are encrypted still that can be hacked 4)We cant compare this two both has pro and cons so based on the scenario we have to use session or viewstate. 5) One more thing "Cache" is there which will also stores data but that is not page specific or user specific it is a general one of the head ache is we need to clean up the cache properly. 6)if we doesnt need the viewstate in a particular page we can disable that at page level so page will render very fast.

We know that Session variable is used to store the value in one page and use it in other page within that particular session. Here is some examples of using the Session variable for storing the value in different formats. Like 1. Storing a normal variable in Session. 2. Storing the class in the Session. 3. Storing the Collection of string in Session as StringCollection. Storing variable in Session 1. Take 2 pages Login.aspx and welcome.aspx 2. Add 2 label(text= enter uid and Enter Password) 2 textbox(id = txt_uid and txt_password) 1 button(id= but_submit) 3. Write below code on Button click event: protected void but_submit_Click(object sender, EventArgs e) { sqlconn.Open(); SqlDataAdapter da = new SqlDataAdapter(("select UserID,Pass_word from users where UserID = '" + txt_uid.Text + "' and Pass_word = '" + txt_password.Text + "' "), sqlconn); DataSet ds = new DataSet(); da.Fill(ds, "temp1"); if (ds.Tables["temp1"].Rows.Count > 0) { //store usedid in the session as variable Session["userid"] = ds.Tables["temp1"].Rows[0]["UserID"]; Response.Redirect("welcome.aspx");

} else

{ Response.Redirect("login.aspx"); }

4. On welcome page write the below code: protected void Page_Load(object sender, EventArgs e) { Label1.Text = "Welcome " + Session["userid"].ToString(); } Storing Class In A Session 1. Create a class Employee.Write the below code inside it: // define 2 public members eid and ename and a empty constructor. public class Emp { public int eid; public string ename; public Emp() { } }

2. Design a page having 2 labels(text= Enter empid and Enter empname) 2 textbox(id = txt_empid and txt_empname) 1 button(id =but_submit) 3. Write below code on button click event: protected void but_submit_Click(object sender, EventArgs e) { Emp e1 = new Emp(); e1.eid = Convert .ToInt32 (txt_empid.Text); e1.ename = txt_empname.Text; // store the employee class in Session Session["employee"] = e1; Response.Redirect("welcome.aspx"); }

4. Write the below code on the welcome page Pageload event: protected void Page_Load(object sender, EventArgs e) { Emp em = (Emp )Session["employee"]; Response.Write("Employee Details Are : "); Response.Write(" Emp Id :" + em.eid.ToString()); Response.Write(" Emp Name :" + em.ename.ToString()); }

Storing StringCollection in Session In this we store the value of listbox in the Session as collection and then on ther page we display it inside listbox. 1. Take 2 page source.aspx and destination.aspx 2. Take 1 button(id = but_submit) and 1 listbox(id=listbox1) in source page and 1 listbox(listbox2) in destination page. 3. Add below code on button click of source page: protected void Button1_Click(object sender, EventArgs e) { StringCollection States = new StringCollection(); foreach (ListItem i in listbox1.Items ) { //Stores all the items in the listbox to the "State" collection. States.Add(i.ToString()); Session["Stateslist"] = States; }

4. On destination pageload event add the below code: protected void Page_Load(object sender, EventArgs e) {

ListBox1.Items.Clear(); if (Session ["Statelist"] != null ) { //copis all the data in session to the state stringcollection. StringCollection State = (StringCollection )Session["Statelist"]; foreach (string i in State ) { ListBox1.Items.Add(i); } } }

You might also like