asp.net lab guide

55
ASP.NET Programming ASP.NET Programming Team Tech Training Technical Training Division Birlasoft Ltd Noida

Upload: pamushiva

Post on 17-Nov-2014

1.916 views

Category:

Documents


7 download

DESCRIPTION

It help ful to do lab

TRANSCRIPT

Page 1: ASP.net Lab Guide

ASP.NET ProgrammingASP.NET Programming

Team Tech Training

Technical Training Division

Birlasoft Ltd

Noida

Page 2: ASP.net Lab Guide

Background.........................................................................................1 Assignments for Day 1 of ASP.Net .............................................................1 Assignment 1: Configuring IIS and Creating Virtual Directory............................. 1 Assignment 2: Using Visual Studio IDE to create First Web Application ................. 4 Assignment 3: Designing a Web page using WEB controls ................................. 7 Assignment 4: How to use Validation Controls .............................................14 Assignment 6: Multivalue Data Binding......................................................20

Assignments for Day 2 of ASP.Net........................................................... 23 Assignment 1: Binding Data to a Repeater Control........................................23 Assignment 2: Data Grid Control .............................................................24 Assignment 3: Formatting Data Grid Control and performing paging...................26 Assignment 4: Demo on Cookies..............................................................31 Assignment 5: Demo on QueryString.........................................................32 Assignment 6: Demo on Session Object .....................................................34 Assignment 7: Demo on Application Object ................................................36 Assignment 1: Output page Caching .........................................................38 Assignment 2: Data Caching ..................................................................40 Assignment 3: Tracing .........................................................................42 Assignment 4: Error Handing..................................................................44 Assignment 5: Security ���� Anonymous users...............................................46 Assignment 6: Security ���� Forms Authentication .........................................49

Page 3: ASP.net Lab Guide

Background This document contains demo programs with step by step lab guide. You can use this lab guide while solving assignments.

Assignments for Day 1 of ASP.Net All the assignments in this section must be completed on Day 1 of your ASP.NET course.

Assignment 1: Configuring IIS and Creating Virtual Directory

Objective: To learn Configure IIS and Create Virtual Directory. Background: Information Services (IIS) 6.0 is a powerful Web Server that provides a highly reliable, manageable, and scalable Web application infrastructure for all versions of Windows Server 2003. A Virtual directory is a friendly name, or alias for a physical directory on your server hard drive. Because an alias is usually shorter in length than the path of the physical directory, it is more convenient for users to type. Step 1: Click on Start � Run � inetmgr or Start � Control Panel � Administrative Tools � Internet Information Services Step 2: The following window is displayed

Step 3: Right click on Default Website ->Properties You can view all Settings .To start with we will not change the default settings.

Page 4: ASP.net Lab Guide

Step 4: To create a Virtual Directory, right click on Default Web Site � New � Virtual directory

Page 5: ASP.net Lab Guide

Step 5: A wizard as shown below will appear. Give name for Virtual Directory in the first step of Wizard.

Step 6: Then click on Next

Step 7: Click browse button present in the to select actual physical directory (where ASP.net files will be stored).

Page 6: ASP.net Lab Guide

Assignment 2: Using Visual Studio IDE to create First Web Application

Objective: To learn Visual studio IDE, to write a Web application and to execute it. Background: The Microsoft Visual Studio 2003 includes a rich variety of professional tools which help us to create Web applications easily and fast. The IDE made up of several windows that help in editing, setting properties, executing and debugging the programs. Step 1: Perform as follows

Step 2: The Microsoft VisulaStudio.Net IDE opens, as shown below

Click Here to Open

Visual Studio IDE

Page 7: ASP.net Lab Guide

Step 3: Select Visual C# projects and ASP.NET web applications and specify the path in location window (you can specify the virtual directory you have created or you can opt for default path. When you opt for default path the actual physical path will be in

c:\ inetpub\wwwroot\your folder name).This will open the Form Design window as shown below:

Page 8: ASP.net Lab Guide

The design environment has following parts:

Sr. No.

Window Name Description

1. Web Form This Form is used for drawing the visual interface of the application.

2. Toolbox window This Window contains the icons representing various visual objects or controls that you can place on Web form.

3. Solution Explorer This window lists all the modules present in the current project.

4. Properties Window This window lists the properties of currently selected object. These properties control the appearance and behavior of the object.

Step 4: Set different properties of Webform.

Step 5: Toolbox contains various controls (HTML and Web Control, Data Controls) that you can add on the form. Step 6: Web Forms will have two views Design View and HTML View. The Design view represents the user interface and HTML view represents ASP.NET syntax for the webpage.

Page 9: ASP.net Lab Guide

Step 7: Every web form will have Code Behind page, where business logic is written. To view Code Behind page double click on web form or View ->Code option in the menu bar . Step 8: Saving your Application: Click on File and select “Save WebForm” option. It first saves all files associated with your application in the folder you have created in the beginning. To run the application click on Debug->Start button .To view individual pages right click on webpage and click on view in browser.

Assignment 3: Designing a Web page using WEB controls

Objective: To understand how to design page using different controls and how to write code. Background: Problem Statement: 1) To display Date and Time in Label control and Page and to demonstrate Page property IsPostback () . 2) To explore different properties of Web Controls. Click on the toolbox icon(see inside circle) or press Ctrl+Alt+X to view tool box as seen in the left side of the below figure

Page 10: ASP.net Lab Guide

Step 1: Open an ASP.NET Web Application Project. (Once a web application is created one web form will be added by default.) Change the name of this page by right clicking on this page in solution explorer and rename it as display_date_time.aspx. See inside ellipse as shown in figure below.

Step 2: Add Label control on the form which was created by default .Change the property ID as lblDateTime .

Page 11: ASP.net Lab Guide

Step 3: Double click on the design window to see a window as shown below

Page 12: ASP.net Lab Guide

Step 4: To run the application press F5 to see the output in IE Figure (A)or right click on the page in solution explorer and click on View in browser see Figure (B). Current time and date will be displayed as shown in Figure(C).

Figure (A)

Page 13: ASP.net Lab Guide

Figure (B)

Figure (C)

Step 4: Now from the tool box add a button control to the form. Change the properties of button ID as btnTime and label as lblTime1. Now write same code for button click event private void btnDateTime_Click (object sender, System.EventArgs e){

/* to display system date and time when button is clicked */

lblDateTime.Text=DateTime.Now.ToString (); }

Page 14: ASP.net Lab Guide

Step 5: To Check for IsPostBack.

Note This will check whether the page is loaded for the first time or not. First time when page is loaded IsPostBack will be false. Once we click on button, page goes to Server, get executed and response comes back to client. At this time, IsPostback will be true.

Now modify the code as shown below in Page_Load event. private void Page_Load(object sender, System.EventArgs e){

/* to display system date and time when page is loaded for the first time */

if (!Page.IsPostBack) lblDateTime.Text=DateTime.Now.ToString (); }

First time page is loaded IsPostBack is false. Label will display date and time .Once the button is clicked IsPostBack is true, now label in Page Load will not display date and time.

Step 1: To understand Response.Write Drag two textbox control, two label controls and one button on the form

Change the text properties and ID.Now write following code for btnSubmit_Click event private void btnSubmit_Click_Click(object sender, System.EventArgs e){ /*Input user name and his designation .After button click display his name on page */

Page 15: ASP.net Lab Guide

Response.Write(" User name is " +txtUserName.Text +"<br>"+"Designation is " +txtDesignation.Text );

}

Step 2: Run the program to see the display as shown

Note: When UserID, Designation are entered to appropriate textboxes and submit button is clicked, page is submitted back to server .Server executes the code with the help of asp.net worker process. Post back event cause the page’s data (view state) back to server. When server receives view state it creates new instance of web form. Fills the data from view state and processes the event that has occurred. When the page is sent back to client we can clearly see that data what we filled in textboxes are retained. (This new feature is available only in ASP.NET).

Step 7: Drag Checkbox control on this form .Write following code for checkbox checked changed event

Page 16: ASP.net Lab Guide

private void chkHello_CheckedChanged(object sender, System.EventArgs e){

/* When check box checked autopostback property must be made true */

if(chkHello.Checked) Response.Write("Hello"); else Response.Write("Bye");

}

Note : Here no event is occurred i.e. page is not sent back to server. Because most of the controls have a property called AutoPostBack .In some controls like Button, this property is set TRUE by default .But for few controls it is false to improve performance, This property is set to TRUE only if it is necessary.

Step 8: Now set the property true for checkbox and verify.

Assignment 4: How to use Validation Controls

Objective: To understand Validation Controls in ASP.NET

Background: The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server. This is an important improvement compared to ASP. It helps the developers to write code faster.

Problem Statement: Design a registration page and submit this to database server after validating this page.

Step 1: Create table members having fields name, age, mailid, username and password in SQL Server.

Step 2: Now add a new page to the application. In solution explorer, right click on project

Add�Webform.

Name the page as Registration.aspx.

Step 3: Next add table to your form. In the menu bar click Table�Insert�Table.

Now specify number of rows as 7 and columns as 2 for the table .Change the background color.

Page 17: ASP.net Lab Guide

Step 3: Place label controls in the first column and textboxes in the second column of all the rows except the last row. In the second column of last row, place Button control. This row must be merged because we have only one control. To merge last row keep the cursor in last row. Select from menu Table�Select�Row. Then select table again from menu and click on Merge cells. Step 4: Now change the text properties of label controls and button control as follows.

Page 18: ASP.net Lab Guide

Step 5: Drag validation Required Field Validator control below name textbox, Range Validator control below age textbox, Regular expression control below emailed textbox, Compare Validator below confirm password textbox. Change error message property of each validation control and give proper error messages.

Step 6: Now set the properties of validation control as follows

Controls Description RequiredFieldvalidator Control to validate as txtName

Range Validator Control to validate as txtAge . Here set MaximumValue 60 and minimumValue 18.Type as integer

RegularExpression Control to validate as txtEmailId and select and specify. Validation expression as Internet email Id

CompareValidator Control to validate as txtConfirm, Control to compare as txtPassword and type as string

Page 19: ASP.net Lab Guide

Step 7. To check validation write following code for button click event.

File name Registration.aspx

private void btnSubmit_Click(object sender, System.EventArgs e){ if(Page.IsValid) { // Connection string

SqlConnection con = new SqlConnection("Data source = Bsls034b; initial catalog = northwind; user id = smith;pwd=manager ");

//Open connection con.Open();

string str="insert into member values(' "+txtName.Text+"',"+txtAge.Text+",'"+txtEmailId.Text+"','"+txtUserName.Text +"','"+txtPassword.Text+"')";

// Command object for executing query SqlCommand cmd=new SqlCommand(str,con); cmd.ExecuteNonQuery (); con.Close();

Response.Write("Data is Inserted Successfully"); } } On successful saving of record to database, you will get the message “Data is inserted successfully”. Step 8: To validate username textbox i.e. username must contain more than 6 characters. Drag custom validator below username textbox . Set property control to validate as txtUserName. Then write following code. On the server side, place your validation code in the ServerValidate event procedure

private void valCustomValidator1_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args){

// find the length of the argument that is passed thro textbox

string str=args.Value ; int len=str.Length; if(len>6) args.IsValid =true; else args.IsValid =false; }

Page 20: ASP.net Lab Guide

Note: The validation controls that are added, validations will be done at Server side. When we perform validation at server side the response to client will be delayed. It is always better to perform validation at client side. To provide client-side validation, specify a validation script in the CustomValidator control’s ClientValidationFunction property.

Step 9: To set the validation at client side we must write validation code in JavaScript. Open Html View .And write the code in script tag. Set the property clientfunction as the CheckUserID of custom control . <script language="javascript"> function CheckUserID(source, args) { if(args.Value.length < 6) args.IsValid = false; } </script> Step 10: Usage of Validation Summary Control This control is used to display validation errors in a central location or display a general validation error description or display lengthy error messages . Drag this control on the form where you want error messages to be displayed. You can set property like display mode, message box etc.

Page 21: ASP.net Lab Guide

Summary of this exercise: This assignment covers

• Different Validation Controls and their implementation

1. Create a web application which accept the product name and quantity of a toy from a customer. After customer has entered the product name and quantity, the application needs to display discounted price of the product (the company is offering 35% discount on all products).The application should allow the customer to select the product name from a list.

2. Create a login page which accepts user name and password from user .Compare this data with member list table from database. If user not existing then prompts him to register .When login is successful display proper welcome message. Perform proper validations in register form and login form.(To register member must provide information’s like firstname,lastname,password,username,tel no,address,city,state, emailed)

Assignment 5: Single Value Data Binding Objective: To understand Simple Data Binding. Background: Data binding helps us to develop applications where controls can be bound to the values stored in the data source.

Syntax for data binding is <%# source %> Problem Statement: Bind an expression with label controls Step 1: Drag two label controls into a new form SimpleDataBinding.aspx. In HTML view and specify Binding expressions . <asp:Label id="lblDateTime" style="Z-INDEX: 102; LEFT: 200px; POSITION: absolute; TOP: 184px" runat="server" Width="200px" Height="40px">

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

</asp:Label>

<asp:Label id="lblSum" style="Z-INDEX: 103; LEFT: 456px; POSITION: absolute; TOP: 184px" runat="server" Width="192px" Height="32px">

<%# "The sum is "+(23+10) %>

</asp:Label> Step 2: Now in Page Load event, bind the data to page or specify control using DataBind() method. private void Page_Load(object sender,System.EventArgs e){

Page 22: ASP.net Lab Guide

Page.DataBind(); }

The output of the page is as shown below

Assignment 6: Multivalue Data Binding

Objective: To learn and understand MutliValue DataBinding. Background: Multi record data binding involves binding server controls to structures, such as ArrayList, DataViewObjects etc. Problem Statement: To bind ArrayList to a DropDownList . Step 1: Open a new form and name this form as multivalueDataBind.aspx. Drag a dropdown list and label control on this form.

Page 23: ASP.net Lab Guide

Step 2: Write the following code in Page Load event private void Page_Load(object sender, System.EventArgs e){ // Create an object of ArrayList ArrayList albooks=new ArrayList(); //Add Books into this collection albooks.Add("Gone with The Wind"); albooks.Add("Visual Basic BlackBook"); albooks.Add("C# Complete Reference"); //set arraylist as dropdownlist datasource and bind it drpBooks.DataSource =books; drpBooks.DataBind(); } DataSource property specifies datasource for the control and DataBind method binds the data. Step 3: View the page in browser, the page will appear as shown below

Page 24: ASP.net Lab Guide

7) Create a web application which accept the product name and quantity of a toy from a customer. After customer has entered the product name and quantity, the application needs to display discounted price of the product (the company is offering 35% discount on all products).The application should allow the customer to select the product name from a list. 8) Create a login page which accepts user name and password from user .Compare this data with member list table from database. If user not existing then prompts him to register .When login is successful display proper welcome message. Perform proper validations in register form and login form.(To register member must provide information’s like firstname,lastname,password,username,tel no,address,city,state, emailed)

Page 25: ASP.net Lab Guide

Assignments for Day 2 of ASP.Net

Assignment 1: Binding Data to a Repeater Control

Objective: To understand the use of Repeater Control in ASP.NET Problem Statement: Populate Repeater Control with data from members table. Show column data in different templates. Background: The Repeater control is a very generic, well defined almost entirely by its templates. It iterates over the bound data, rendering its ItemTemplate once for each item in the DataSource collection. Useful when we want complete control over how data from a data source is rendered. Step 1: Add a webform and name it as Repeaterdemo.aspx. Add one panel control to the form. Here, panel acts as a container for repeater. Drag a repeater control into this panel.

Page 26: ASP.net Lab Guide

Step 2: Next, we have to bind the data source to repeater control in page load event. private void Page_Load(object sender, System.EventArgs e){

SqlConnection con = new SqlConnection("Data source = your-system-name\\infosys; initial catalog = northwind; user id = smith;pwd= admin");

con.Open(); SqlDataAdapter da=new SqlDataAdapter("select name,EmailId,UserName from member",con);

DataSet ds=new DataSet(); da.Fill(ds,"Members"); repMember.DataSource =ds; repMember.DataBind();

} Step 3: Now view the page in browser.

Assignment 2: Data Grid Control

Objective: To learn and understand the use of Data Grid control. Problem Statement: Populate dropdown list with category name from category table. Now populate data grid with product details for selected category name in the dropdown list. Step 1: Drag Dropdown list, Datagrid on a new form .Design the screen the following screen

Step 2: Next populate dropdown list with category name from category list on page load .Dropdownlist has properties like DataTextField and DataValueField. We can set these properties with appropriate columns from category table. To populate and bind the data we have to write following code in pageload event

Page 27: ASP.net Lab Guide

private void Page_Load(object sender, System.EventArgs e){ //Create dataadpater object SqlDataAdapter da=new SqlDataAdapter("SELECT * FROM Categories",con); //Create dataset DataSet ds=new DataSet(); //Fill dataset da.Fill(ds,"categories"); // set ds as datasource for dropdownlist drpCategory.DataSource =ds; //set datatextfield and value field drpCategory.DataTextField="categoryname"; drpCategory.DataValueField ="categoryid"; // bind the data when page is loaded drpCategory.DataBind(); } Step 3: Now view the page in browser, the page appears as shown below

Step 4: To fetch data from products for selected name in dropdownlist.

Set Autopostback property of dropdownlist to true. Write following code in DropDownList1_SelectedIndexChanged event.

private void drpcategory_SelectedIndexChanged (object sender, System.EventArgs e){

SqlDataAdapter da=new SqlDataAdapter("SELECT * FROM products where categoryid="+drpCategory.SelectedValue ,con);

DataSet ds=new DataSet(); da.Fill(ds,"products"); grdProducts.DataSource =ds; grdProducts.DataBind(); }

Page 28: ASP.net Lab Guide

Step 3: Now view the page in browser, the page looks as shown below

Note: Now when we select an item in dropdown list data grid displays same product list. This is because every time page is posted back, new page instance is created and page load event populates dropdown with items again and again. The selected item is lost. We can avoid it by populating dropdown list only when page is loaded for the first time. This can be done by adding following code to page load while binding the data. // bind the data when page is loaded for the first time if(!Page.IsPostBack) if(!Page.IsPostBack)

Assignment 3: Formatting Data Grid Control and performing paging

Objective: How to format and add templates to datagrid control. Problem Statement: Populate datagrid with products, format them and then perform paging. Step 1: Add a new form in the application and name it as DataGridPaging.aspx.Now right click on datagrid control and select Autoformat. A window appears which provides different formats for displaying each row of datagrid.

Page 29: ASP.net Lab Guide

Step 2: After selecting format Data Grid looks as shown above. Now to set datagrid to few columns, to provide paging, to add templates and buttons, we have to again right click on datagrid and select Property Builder. Property Builder provides following options to be chosen from.

Note: There are different tabs in Property Builder. Using General tab we can set data source for data grid. We can use columns tab for binding only few columns from the data source. We can use format tab for providing different colors, paging has options to set how many rows we would like to display at a time, where should we place page options etc and fonts and template tab is used for providing templates.

Page 30: ASP.net Lab Guide

Step 3: Select columns tab. Uncheck the option create columns automatically .Click on bound

column. Click on “>” button, add required numbers of columns you would like to display in datagrid. For each column specify header text and data field. Let us bind productId, productName ,Unitprice columns to datagrid .

Step 4: Now view the page in browser, the page looks as shown below

Step 5: Now if we look into the rows displayed, we can not see all the rows at a time. We can provide page by page display of rows by using paging option. Right click on datagrid Property Builder� Paging

Page 31: ASP.net Lab Guide

Step 6: After setting paging properties add event for paging and write following code private void grdProducts_PageIndexChanged(object source, System.Web.UI.WebControls.DataGridPageChangedEventArgs e){ //When we chnage page index bind datagrid with next page data grdProducts.CurrentPageIndex =e.NewPageIndex; grdProducts.DataBind(); }

Page 32: ASP.net Lab Guide
Page 33: ASP.net Lab Guide

Assignment 4: Demo on Cookies

Objective: To learn importance of cookies. Problem Statement: Create a simple home page and a page which will display members list .First time when we browse this application, home page and then members page must be displayed .Next time when we browse application should take us directly to members page. Background: Cookies provide a useful means in Web applications to store user-specific information. For example, when a user visits your site, you can use cookies to store user preferences or other information. When the user visits your Web site another time, the application can retrieve the information it stored earlier. At this time we can direct client directly to next page. Step 1: Add a webform and name it as cookiedemo.aspx This will be our home page. Design the page as shown below.

Step 2: We have to store cookie in client system, when one browses this page for the first

time and if checkbox is checked. The cookie is added using Response.Cookie.add() method. We can set expiration time for this cookie. To add Cookie write following code.

private void chkConfirm_CheckedChanged(object sender, System.EventArgs e){ //Create Cookie object with Showpage as name of the cookie HttpCookie myCookie=new HttpCookie("showpage");

Page 34: ASP.net Lab Guide

//Now if checkbox is checked then store cookie value as yes if(chkConfirm.Checked) myCookie.Value ="yes"; //and store in client hard disk for 20 secs myCookie.Expires=DateTime.Now.AddSeconds(20); Response.Cookies.Add(myCookie);

}

Note: The path where cookie stored is C:\Documents and Settings\your-infosys-login-id\Cookies and the server name will be local host. Step 3: Now let us see how to get cookie information from client system and if it is stored with value yes then we must send client directly to next page.

private void Page_Load(object sender, System.EventArgs e) { if(!Page.IsPostBack ) {

HttpCookie myCookie=Request.Cookies["showpage"]; if(myCookie!=null) if(myCookie.Value.Equals("yes")) Response.Redirect("Repeater.aspx"); }

}

Assignment 5: Demo on QueryString

Objective: To learn importance of Query String Problem Statement: Send user name and his designation to next page through query string .In the next page give welcome message Background: Query strings are a way to pack information into a link. Then we retrieve that information on the page that was linked to. A regular URL to a page is like this page.aspx. The URL with a query string might look like this page.aspx?id=1. Step 1: Add a web form and name it as QuerystringDemo.aspx and one more page which can receive this information.(Welcome.aspx). Step 2: Now design the form having two text boxes and two labels .and a button .On Button click redirect to next page along with query string like this .Write following code to button click event.

Page 35: ASP.net Lab Guide

private void Button1_Click(object sender, System.EventArgs e){ //Along with Page name(url)send contents of both textboxes Response.Redirect("welcome.aspx?id1="+txtUserName.Text +"&id2="+txtDesg.Text); }

Step 3: When click this button page is redirected to welcome page .Along with this page the data from two textboxes are sent through URL. URL looks like this

http://localhost/VirtualDirectoryName/welcome.aspx?id1=Smithl&id2=Manager

In welcome page retrieve this data using Request.QueryString[“id”] private void Page_Load(object sender, System.EventArgs e){ //On page load retrieve the data using request .query string

lblUserName.Text= "We Welcome "+Request.QueryString["id1"]+"<br>Your designation in this comapany is " +Request.QueryString["id2"];

} Step 4: When page is redirected to welcome, page looks like this.

Page 36: ASP.net Lab Guide

Assignment 6: Demo on Session Object

Objective: To learn about Session state and how user session information are maintained. Problem Statement: To Demonstrate How to maintain user session information and different ways to store them. Background: A session is defined as the period of time that a unique user interacts with a Web application. Programmatically, session state is nothing more than memory in the shape of a dictionary or hash table, e.g. key-value pairs, which can be set and read for the duration of a user's session .In Asp.net session management is Process independent, It support for server farm configurations. Step 1: Design a screen with user name and password and button next to navigate to next screen. When we navigate to next page we have to take username and password there and display them. We can store user information in session objects during button click. private void btnLogin_Click(object sender, System.EventArgs e){ Session["uid"]=txtUserName.Text; Session["pwd"]=txtPassword.Text; Response.Redirect("welcome.aspx"); }

Page 37: ASP.net Lab Guide

Step 2: Now to retrieve them in next page we have to use these session objects again. private void Page_Load(object sender, System.EventArgs e){ //On page load display data in a label box

lblSession.text =" Welcome " +Session["uid"]+"<br> Your password is "+Session["pwd"];

lblSession.Text +="Session Id is " +Session.SessionID ; }

The session information is stored in the server and every user will be given unique id. This id will be stored in client system in the form of cookie .These cookies are deleted as soon as session ends . Here session state exists in the process that hosts application, thus the actions that affect the process also affect session state. When the process is recycled or fails, session state is lost.ASP.NET provides Out-Process session state management. This can be done in two ways State server and SqlServer. Step 4: To demonstrate session management using State Server. To set the session management to state server open web.config file .Change Session State mode to StateServer. <sessionState mode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="datasource=127.0.0.1;Trusted_Connection=yes" cookieless="false" timeout="20" />

Page 38: ASP.net Lab Guide

Step 5: After this we must start asp.net state service in the machine where we are going to store state information. Start�Control Panel�Administrative Tools�Services�Asp.Net State Service Right click and start the service. Step 6: Now execute the same page. This time session management is done thro State Server.

Note:Session Management thru SQLServer. The SQL Server mode option is similar to that of the Windows NT Service, except that the information persists to SQL Server rather than being stored in memory. .Net framework provides file InstallPersistSqlState.sql which provides script for creating tables that can store session informations.We have to run that script in query analyzer .This will produce two tables and stored procedures.

The path of this file is : C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322 and File name is InstallPersistSqlState.sql Step 8: Make required changes in web.config file as follows <sessionState mode="SQLServer"

sqlConnectionString="data source=your-system-name\infosys;user id=your-sqlserver-userid;password=your-sqlserverpwd"

cookieless="false" timeout="20" />

Assignment 7: Demo on Application Object

Objective: To learn about Application Object. Problem Statement: To Count the number of users visited this site or application. Background: Provides access to application-wide methods and events for all sessions. Also provides access to an application-wide cache you can use to store information. Step 1: Design a new webform like below.

Note To store application wide variables we use Global.asax file. This file will be loaded once in a life time of an application. This file is placed in root folder of our web application.

Step 2: Open Global.asax and we can see this file has events like application start, session start etc.

Page 39: ASP.net Lab Guide

Step 3: Initialize application count to zero in application start event .For every session increment this counter by one. protected void Application_Start (Object sender, EventArgs e){ Application ["VisitCount"] =0; } protected void Session_Start(Object sender, EventArgs e){

Int iCount; iCount=Convert.ToInt32(Application["VisitCount"]);

iCount++; Application["VisitCount"]=iCount; } Step 4: And on page load event of home page or any default page retriev this data.Whenever any client visit this site he/she gets visit count. private void Page_Load(object sender, System.EventArgs e){

lblVisistCount =" You are "+Application ["VisitCount"] +” person to Visit this page";

}

Page 40: ASP.net Lab Guide

8.Create a web application which displays category names and their ids. Each row containing category details should display a Know More button. When customer clicks on this button ,the description for the selected category must be displayed.(Use Repeater control, Use category table from north wind database)

Assignment 5: Output page Caching

Objective: To learn about Page Output caching Problem Statement: Demonstrate Page Out put Caching Background: ASP.NET holds page in memory so that it can be delivered again efficiently. This is known as output caching .For enabling output caching you need to mark the page with OutputCache directive as follows:

<%@ OutputCache Duration="60" %>

Step 1: Add one more webform into this application and name it as CacheDemo.Now drag one label control .To check whether we are getting new page or cached page set label control to recent time.

Step 2: Open HTML view and include cache directive.

Page 41: ASP.net Lab Guide

Step 3: When we view this page in browser for 10 secs the page will be cached and kept and user gets this page. We can observe this by clicking the mouse. Every post back (for 10 secs) Time displayed will be same.

private void btnCache_Click(object sender, System.EventArgs e) { lblDate.Text =" The Time Now is " + DateTime.Now.ToLongTimeString ();

}

Page 42: ASP.net Lab Guide

Step 4 : Multiple versions of page can be cached by using property varybyparam. Specifying VaryByParam to "none" means only one cache page. Specifying VaryByParam to "*" means that multiple cache page

For the above page add varybyparam and give value through a textbox. Add one more page and place text box and button in this page. Send textbox value through query string while navigating thru button provide query string along with URL.When we navigate from this page to cached page we must get different versions pages depends on data sent thro query string. private void btnNext_Click(object sender, System.EventArgs e){

Response.Redirect("Cachedemo.aspx?id="+txtName.Text); }

Data Caching

Objective: To learn about Data caching Problem Statement: Fill data set with data from products table .cache this data using different ways available in Asp.net

– Manual – Absolute expiration time – Sliding expiration time – Dependencies (on files, directories, or other cache entries)

Background: Data caching, which we can use to programmatically store arbitrary objects, such as data sets, to server memory so that our application can save the time and resources it takes to recreate them.

Page 43: ASP.net Lab Guide

Step 1: Add one more webpage into this application. Add two buttons ,datagrid ,label control into this page .Design this screen as follows.

Step 2: Write a code to fetch data from database and store in cache object. Next time when page is posted back the data is populated to datagrid from cached object.

Step 3: Using above method we can store data in cache manually .To remove cached object we can use remove method . private void btnRemove_Click(object sender, System.EventArgs e){ // Remove data from cache Cache.Remove("objDs"); lblData.Text="data removed"; } Step 4:Absolute expiration method can be used to store the data in cache. Here time interval is fixed ,so that after fixed time duration data will be removed from cache. When inserted expiry time must be provided like : //Absolute expiration Cache.Insert("objDs",ds,null,DateTime.Now.AddSeconds(10),TimeSpan.Zero); Step 5: We can also provide sliding expiration time like below // sliding time span Cache.Insert("objDs",ds,null,DateTime.MaxValue,TimeSpan.FromSeconds(10));

Page 44: ASP.net Lab Guide

Step 6 : We can achive datacahing even thro file dependency.Here cache will be refreshed if we make any changes to file test.txt. //Using file dependency CacheDependency d =new CacheDependency(Server.MapPath("test.txt")); Cache.Insert("objDs",ds,d);

Assignment 2: Tracing

Objective: To learn about Tracing mechanism in ASP.NET. Problem Statement: Demonstrate Tracing in ASP.NET. Background: Provides a way to get both system and custom trace diagnostic messages to display in the HTTP page output. The Trace class exposes two overloaded methods and two properties. The two methods, Warn () and Write (), and two public properties IsEnabled and Trace Mode. Step 1: We can set trace at page level or application level. To set this true in page level open html view of any page and set an attribute trace=true. <%@ Page language="c#" Codebehind="DataCacheDemo.aspx.cs" AutoEventWireup="false" Inherits = "DotnetJuneSc2day2.DataCacheDemo" Trace=true%> Step 2: To demonstrate trace write following code in a new webform. In page load and button click, write following code

Trace.Write method writes trace information in normal text color where as if we use

Trace.Warn the message is displayed in red color. private void Page_Load(object sender, System.EventArgs e){

//Trace. write will display what is happening when page is loaded

Trace.Write("In page load ","Loading the page now"); } private void Button1_Click(object sender, System.EventArgs e){

//Trace. write will display what is happening when button clicked

Trace.Warn("In Button Event", "This event is fired and page is post ed back ");

} Step 3: When we view the page in Browser we get trace information along with the page.

Page 45: ASP.net Lab Guide

Step 4: We can even set trace application level .This can be done in web.config file. <trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime" localOnly="true" />

Step 5: Trace.axd is an Http Handler (An Http Handler is a coding option that allows us to handle request/responses at the most basic level). We can directly view trace information in browser using this handler. Give URL like below

http://localhost/VirtualDirectoryName/Trace.axd

Page 46: ASP.net Lab Guide

Assignment 3: Error Handing

Objective: To learn about Error handling mechanism in ASP.NET. Problem Statement: Demonstrate Error handling in ASP.NET. Background: .NET Common Language Runtime provides a unified exception architecture Runtime errors done using exceptions.ASP.NET also provides declarative application custom error handling. Automatically redirect users to error page when unhandled exceptions occur. Prevents ugly error messages from being sent to users. Step 1: Add three forms to this application. Give appropriate names to these pages(Homepage.aspx, Errorpage.aspx,NoPage.aspx).Now In homepage.aspx drag label and button .For displaying messages drag label in other pages too. In web.config file make these settings

<customErrors mode="On" defaultRedirect="GeneralError.aspx"> <error statusCode="404" redirect="NoPageError.aspx"></error>

</customErrors>

• Mode attribute is either set to On or RemoteOnly . • On : Error messages will be displayed in client and well as server where application is

running

Page 47: ASP.net Lab Guide

• RemoteOnly : Error messages will be displayed only at client location

Error attribute specifies the error status number and page to be redirected when such error occurs .We can see error status number in IIS settings.

When we click on next button if at all given page is not found the page will be redirected to error page and display proper messages .so that user will be very clearly informed that he has entered wrong page.

Next

Page 48: ASP.net Lab Guide

Assignment 4: Security � Anonymous users

Objective: To learn how Security is implemented in ASP.NET. Problem Statement: Demonstrate implementing security using anonymous users.

Background: Anonymous access is the way most public Web sites work—sites containing public information allow anyone to see that information, so they don’t authenticate users. ASP.NET Web applications provide anonymous access to resources on the server by impersonation. Impersonation is the process of assigning a user account to an unknown user.

This is the common access method for most Web sites. No logon is required, and you secure restricted resources using NTFS file permissions. By default, the anonymous access account is named IUSER_machinename. You use that account to control anonymous users’ access to resources on the server.

To see or change the access privileges to the anonymous access account, use the Windows Computer Management snap-in as described in the following steps:

Step 1: From the Start menu, choose Administrative Tools, and then choose Computer Management to run the Computer Management console.

Step 2: From the list on the left, choose Local Users and Groups, and then select the Users folder to display the list of authorized users for this computer.

Page 49: ASP.net Lab Guide

Step 3: From the user list on the right, double-click the anonymous user account named IUSR_computername. The Computer Management console displays the account’s properties as shown below.

Step 4: For any ASP.NET application this are default settings. We can check this in IIS settings. From the start menu choose Start ���� administartivetools ���� IntenetInformationServices. We will get all the web applications developed . Right click on any one webapplication.Click on properties .You can see the screen as shown below.

Page 50: ASP.net Lab Guide

Step 5: Now click on Directory Security tab.

Step6: Click on edit tab here .Now we can see a screen where Anonymous User is clicked by default.

Page 51: ASP.net Lab Guide

Assignment 5: Security � Forms Authentication

Objective: To learn how Security is implemented in ASP.NET. Problem Statement: Demonstrate implementing security using Forms Authentication.

Background: Forms authentication automatically displays a designated Web form to collect user name and password information. User information is stored in the application’s Web.config file or in a separate user database. The advantage of Forms authentication is that users do not have to be member of a domain-based network to have access to your application. Another advantage is that many Web applications—particularly commercial sites where customers order products—want to have access to user information. Forms authentication makes these types of applications easier to create.

Step1: Add a new form and name this form as Login.aspx.To set the authentication to Form Login we have to change authentication in web.config into Forms.Open web.config file and provide authentication mode ,form name and url ,provide credentials like user name and password.

<authentication mode="Forms"> <forms name="Login" loginUrl="Login.aspx"> <credentials passwordFormat="Clear"> <user name="smith"

Page 52: ASP.net Lab Guide

password="manager"></user> <user name="Smith" password="manager"></user> </credentials> </forms> </authentication>

Element Attribute Description

<authentication> mode Set to Forms to enable Forms authentication.

<forms> name Use to set the name of the cookie in which to store the user’s credential. The default is auth.aspx. .

loginUrl Use to set the name of the Web form to display if the user has not already been authenticated. If omitted, the default is Default.aspx.

protection Use to set how ASP.NET protects the authentication cookie stored on the user’s machine. The default is All, which performs encryption and data validation. Other possible settings are Encryption, Validation, and None.

timeout Use to set the number of minutes the authentication cookie persists on the user’s machine. The default is 30, indicating 30 minutes. ASP.NET renews the cookie automatically if it receives a request from the user and more than half of the allotted time has expired.

path Use to set the path used to store the cookie on the user’s machine. The default is a backslash (\).

<credentials> passwordFormat Use to set the algorithm used to encrypt the user’s password. The default is SHA1. Other possible settings are MD5 and Clear (which prevents encryption).

<users> name Use to set the name of the user.

password Use to set the password for the user.

Page 53: ASP.net Lab Guide

Step 2: Design your login form like below.

Step 3: For authenticating the form import namespace System.Web.Security.Write following code for button click.

private void BtnLogin_Click(object sender, System.EventArgs e){ //Authenticate username/password from <credentials>.

if(FormsAuthentication.Authenticate(txtUserName,txtPassword)) FormsAuthentication.RedirectFromLoginPage(txtUserName.Text,true);

Else { // Otherwise, clear the password.

txtPassword.Text=""; // If try is more than 3 , display "Access Denied" page.

if (System.Convert.ToInt32(ViewState["Tries"]) > 3) Response.Redirect("Denied.htm"); else // Otherwise, increment number of tries.

ViewState["Tries"] = System.Convert.ToInt32(ViewState["Tries"])+ 1;

} }

Page 54: ASP.net Lab Guide

Note: The FormsAuthentication class’s Authenticate method checks the user name and password against the user list found in the <credentials> element of

Web.config. The FormsAuthentication class’s RedirectFromLoginPage method displays the application’s start page. If the logon fields appear on the application’s start page, one should disable them or otherwise indicate a successful logon.One can encrypt password using encryption algorithms like SHA1 or MD5.To encrypt password use Class FormsAuthentication.

Step 4: Add one more button to login form and name it as BtnEncrypt.And write a code to encrypt the password and store it in password textbox. private void btnEncrypt_Click(object sender, System.EventArgs e){ //Encrypt password using SHA1 algorithum

txtPassword.Text=FormsAuthentication.HashPasswordForStoringInConfigFile (txtPassword.Text,"SHA1");

}

Note: Now password Textbox displays encrypted password(Remember not set password textbox property as password)

Step 5: Now open web.config file and set passwordFormat as SHA1 and store encrypted password. <authentication mode="Forms"> <forms name="Login" loginUrl="Login.aspx"> <credentials passwordFormat="SHA1">

<user name="Smith" password="1BDA18F74011EAEA119FF9AB870E07E4DC49F097"></user>

Page 55: ASP.net Lab Guide

<user name="Smith" password="F341CCE43621332AB8CF3A92FEF526FEE0225C9E"></user>

</credentials> </forms>

</authentication>

Note: Use the FormsAuthentication class to sign out when the user has finished with the application or when you want to remove the authentication cookie from his or her machine.

Step 6: The following code ends the user’s access to an application and requires him or her to sign back in to regain access:

private void btnSignOut_Click(object sender, System.EventArgs e){ // Remove authentication cookie. FormsAuthentication.SignOut();

// Redirect back to login screen Response.Redirect("Login.aspx");

}

1. Continuation with assignment no 2 of day1 .Use form login and store password in

encrypted form in the database using SHA1 algorithm.