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

21436115 ASP Net Lab Guide

Embed Size (px)

Citation preview

Page 1: 21436115 ASP Net Lab Guide

ASP.NET Programming

Team Tech Training

Technical Training DivisionBirlasoft Ltd

Noida

Page 2: 21436115 ASP Net Lab Guide

Background......................................................................................... 1Assignments for Day 1 of ASP.Net ............................................................. 1

Assignment 1: Configuring IIS and Creating Virtual Directory............................. 1Assignment 2: Using Visual Studio IDE to create First Web Application ................. 4

Assignment 3: Designing a Web page using WEB controls ................................. 7Assignment 4: How to use Validation Controls .............................................14Assignment 6: Multivalue Data Binding......................................................20Assignments for Day 2 of ASP.Net........................................................... 23Assignment 1: Binding Data to a Repeater Control........................................23

Assignment 2: Data Grid Control .............................................................24Assignment 3: Formatting Data Grid Control and performing paging...................26

Assignment 4: Demo on Cookies..............................................................31Assignment 5: Demo on QueryString.........................................................32Assignment 6: Demo on Session Object .....................................................34Assignment 7: Demo on Application Object ................................................36Assignment 1: Output page Caching .........................................................38Assignment 2: Data Caching ..................................................................40Assignment 3: Tracing .........................................................................42

Assignment 4: Error Handing..................................................................44Assignment 5: Security Anonymous users...............................................46Assignment 6: Security Forms Authentication .........................................49

Page 3: 21436115 ASP Net Lab Guide

BackgroundThis 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 highlyreliable, manageable, and scalable Web application infrastructure for all versions of WindowsServer 2003. A Virtual directory is a friendly name, or alias for a physical directory on yourserver 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 inetmgrorStart Control Panel Administrative Tools Internet Information Services

Step 2: The following window is displayed

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

Page 4: 21436115 ASP Net Lab Guide

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

Page 5: 21436115 ASP Net Lab Guide

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

Step 6: Then click on Next

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

Page 6: 21436115 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 toolswhich help us to create Web applications easily and fast. The IDE made up of several windowsthat help in editing, setting properties, executing and debugging the programs.

Step 1: Perform as follows

Click Here to Open

Visual Studio IDE

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

Page 7: 21436115 ASP Net Lab Guide

Step 3: Select Visual C# projects and ASP.NET web applications and specify the path inlocation window (you can specify the virtual directory you have created or you can opt fordefault 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 asshown below:

Page 8: 21436115 ASP Net Lab Guide

Sr.No.

Window Name Description

1. Web FormThis Form is used for drawing the visual interface of theapplication.

2. Toolbox windowThis Window contains the icons representing various visualobjects or controls that you can place on Web form.

3. Solution ExplorerThis window lists all the modules present in the currentproject.

4. Properties WindowThis window lists the properties of currently selectedobject. These properties control the appearance andbehavior of the object.

The design environment has following parts:

Step 4: Set different properties of Webform.

Step 5: Toolbox contains various controls (HTML and Web Control, Data Controls) that you canadd on the form.

Step 6: Web Forms will have two views Design View and HTML View. The Design viewrepresents the user interface and HTML view represents ASP.NET syntax for the webpage.

Page 9: 21436115 ASP Net Lab Guide

Step 7: Every web form will have Code Behind page, where business logic is written. To viewCode 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 savesall 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 onwebpage 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 propertyIsPostback () .

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 theleft side of the below figure

Page 10: 21436115 ASP Net Lab Guide

Step 1: Open an ASP.NET Web Application Project. (Once a web application is created oneweb form will be added by default.)

Change the name of this page by right clicking on this page in solution explorer and rename itas 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 IDas lblDateTime .

Page 11: 21436115 ASP Net Lab Guide

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

Page 12: 21436115 ASP Net Lab Guide

Step 4: To run the application press F5 to see the output in IE Figure (A)or right click onthe 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: 21436115 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 ofbutton 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 isclicked */

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

Page 14: 21436115 ASP Net Lab Guide

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

Step 5: To Check for IsPostBack.

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 loadedfor 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 thebutton is clicked IsPostBack is true, now label in Page Load will not display date and time.

Step 1: To understand Response.WriteDrag 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: 21436115 ASP Net Lab Guide

Note:When UserID, Designation are entered to appropriate textboxes andsubmit button is clicked, page is submitted back to server .Serverexecutes the code with the help of asp.net worker process.Post back event cause the page’s data (view state) back to server. Whenserver 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 whatwe filled in textboxes are retained.(This new feature is available only in ASP.NET).

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

}

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

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

Page 16: 21436115 ASP Net Lab Guide

Note :Here no event is occurred i.e. page is not sent back to server. Because most ofthe controls have a property called AutoPostBack .In some controls likeButton, this property is set TRUE bydefault .But for few controls it is falseto improve performance, This property is set to TRUE only if it is necessary.

private void chkHello_CheckedChanged(object sender, System.EventArgse){

/* When check box checked autopostback property mustbe made true */if(chkHello.Checked)

Response.Write("Hello");else

Response.Write("Bye");}

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 servercontrols 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 aftervalidating this page.

Step 1: Create table members having fields name, age, mailid, username and password inSQL 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 backgroundcolor.

Page 17: 21436115 ASP Net Lab Guide

Step 3: Place label controls in the first column and textboxes in the second column of all therows 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: 21436115 ASP Net Lab Guide

Controls Description

RequiredFieldvalidator Control to validate as txtName

Range ValidatorControl to validate as txtAge . Here set MaximumValue60 and minimumValue 18.Type as integer

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

CompareValidatorControl to validate as txtConfirm, Control to compare astxtPassword and type as string

Step 5: Drag validation Required Field Validator control below name textbox, RangeValidator 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

Page 19: 21436115 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 stringSqlConnection con = new SqlConnection("Data source =Bsls034b; initial catalog = northwind; user id =smith;pwd=manager ");//Open connectioncon.Open();string str="insert into member values('"+txtName.Text+"',"+txtAge.Text+",'"+txtEmailId.Text+"','"+txtUserName.Text +"','"+txtPassword.Text+"')";// Command object for executing querySqlCommand 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 insertedsuccessfully”.

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 throtextbox

string str=args.Value ;int len=str.Length;if(len>6)

args.IsValid =true;else

args.IsValid =false;

}

Page 20: 21436115 ASP Net Lab Guide

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

Step 9: To set the validation at client side we must write validation code in JavaScript. OpenHtml 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 generalvalidation error description or display lengthy error messages .

Drag this control on the form where you want error messages to be displayed. You can setproperty like display mode, message box etc.

Page 21: 21436115 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 toyfrom a customer. After customer has entered the product name and quantity, the

application needs to display discounted price of the product (the company isoffering 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 promptshim to register .When login is successful display proper welcome message. Performproper validations in register form and login form.(To register member mustprovide 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 tothe 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 andspecify 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: 21436115 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 asArrayList, 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 dropdownlist and label control on this form.

Page 23: 21436115 ASP Net Lab Guide

Step 2: Write the following code in Page Load eventprivate void Page_Load(object sender, System.EventArgs e){

// Create an object of ArrayListArrayList albooks=new ArrayList();

//Add Books into this collectionalbooks.Add("Gone with The Wind");albooks.Add("Visual Basic BlackBook");albooks.Add("C# Complete Reference");

//set arraylist as dropdownlist datasource and bind itdrpBooks.DataSource =books;drpBooks.DataBind();

}

DataSource property specifies datasource for the control and DataBind method binds thedata.

Step 3: View the page in browser, the page will appear as shown below

Page 24: 21436115 ASP Net Lab Guide

7)Create a web application which accept the product name and quantity of a toyfrom a customer. After customer has entered the product name and quantity, the

application needs to display discounted price of the product (the company isoffering 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 .Comparethis data with member list table from database. If user not existing then prompts

him to register .When login is successful display proper welcome message. Performproper validations in register form and login form.(To register member mustprovide information’s like firstname,lastname,password,username,tel

no,address,city,state, emailed)

Page 25: 21436115 ASP Net Lab Guide

Assignments for Day 2 of ASP.Net

Assignment 1: Binding Data to a Repeater ControlObjective: To understand the use of Repeater Control in ASP.NET

Problem Statement: Populate Repeater Control with data from members table. Show columndata in different templates.

Background: The Repeater control is a very generic, well defined almost entirely by itstemplates. 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 datasource 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: 21436115 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("selectname,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. Nowpopulate 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: 21436115 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 datasetDataSet ds=new DataSet();//Fill datasetda.Fill(ds,"categories");// set ds as datasource for dropdownlistdrpCategory.DataSource =ds;//set datatextfield and value fielddrpCategory.DataTextField="categoryname";drpCategory.DataValueField ="categoryid";// bind the data when page is loadeddrpCategory.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 productswhere categoryid="+drpCategory.SelectedValue ,con);

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

}

Page 28: 21436115 ASP Net Lab Guide

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

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

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 clickon datagrid control and select Autoformat. A window appears which provides different

formats for displaying each row of datagrid.

Page 29: 21436115 ASP Net Lab Guide

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

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

from.

Page 30: 21436115 ASP Net Lab Guide

Step 3: Select columns tab. Uncheck the option create columns automatically .Click on boundcolumn. 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 canprovide page by page display of rows by using paging option. Right click on datagrid Property

Builder Paging

Page 31: 21436115 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: 21436115 ASP Net Lab Guide
Page 33: 21436115 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 bedisplayed .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-specificinformation. For example, when a user visits your site, you can use cookies to store userpreferences or other information. When the user visits your Web site another time, theapplication 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. Designthe page as shown below.

Step 2: We have to store cookie in client system, when one browses this page for the firsttime 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.EventArgse){//Create Cookie object with Showpage as name of the cookie

HttpCookie myCookie=new HttpCookie("showpage");

Page 34: 21436115 ASP Net Lab Guide

//Now if checkbox is checked then store cookie value as yesif(chkConfirm.Checked)

myCookie.Value ="yes";//and store in client hard disk for 20 secsmyCookie.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 belocal host.

Step 3: Now let us see how to get cookie information from client system and if it is storedwith 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 .Inthe next page give welcome message

Background: Query strings are a way to pack information into a link. Then we retrieve thatinformation 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 canreceive this information.(Welcome.aspx).

Step 2: Now design the form having two text boxes and two labels .and a button .On Buttonclick redirect to next page along with query string like this .Write following code to button

click event.

Page 35: 21436115 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 thedata 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 stringlblUserName.Text= "We Welcome"+Request.QueryString["id1"]+"<br>Your designation in thiscomapany is " +Request.QueryString["id2"];

}

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

Page 36: 21436115 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 differentways to store them.

Background: A session is defined as the period of time that a unique user interacts with aWeb application. Programmatically, session state is nothing more than memory in the shapeof 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 forserver farm configurations.

Step 1: Design a screen with user name and password and button next to navigate to nextscreen. 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: 21436115 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 boxlblSession.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 idwill 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 theprocess 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 waysState server and SqlServer.

Step 4: To demonstrate session management using State Server. To set the sessionmanagement to state server open web.config file .Change Session State mode to StateServer.

<sessionStatemode="StateServer" stateConnectionString="tcpip=127.0.0.1:42424"sqlConnectionString="datasource=127.0.0.1;Trusted_Connection=yes"cookieless="false" timeout="20" />

Page 38: 21436115 ASP Net Lab Guide

Note:Session Management thru SQLServer. The SQL Server mode option issimilar to that of the Windows NT Service, except that the informationpersists to SQL Server rather than being stored in memory. .Net frameworkprovides file InstallPersistSqlState.sql which provides script for creatingtables that can store session informations.We have to run that script in queryanalyzer .This will produce two tables and stored procedures.

Step 5: After this we must start asp.net state service in the machine where we are going tostore 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.

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. Alsoprovides 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 alife 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, sessionstart etc.

Page 39: 21436115 ASP Net Lab Guide

Step 3: Initialize application count to zero in application start event .For every sessionincrement 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.Wheneverany 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: 21436115 ASP Net Lab Guide

8.Create a web application which displays category names and their ids. Each rowcontaining category details should display a Know More button. When customerclicks on this button ,the description for the selected category must bedisplayed.(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. Thisis 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 onelabel 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: 21436115 ASP Net Lab Guide

Step 3: When we view this page in browser for 10 secs the page will be cached and kept anduser 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: 21436115 ASP Net Lab Guide

Step 4 : Multiple versions of page can be cached by using property varybyparam. SpecifyingVaryByParam 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 stringalong 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 usingdifferent 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: 21436115 ASP Net Lab Guide

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

Step 2: Write a code to fetch data from database and store in cache object. Next time whenpage 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 objectwe 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 timeinterval 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: 21436115 ASP Net Lab Guide

Step 6 : We can achive datacahing even thro file dependency.Here cache will be refreshed ifwe make any changes to file test.txt.

//Using file dependencyCacheDependency 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 todisplay in the HTTP page output. The Trace class exposes two overloaded methods and twoproperties. 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 levelopen 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 useTrace.Warn the message is displayed in red color.

private void Page_Load(object sender, System.EventArgs e){//Trace. write will display what is happening whenpage is loadedTrace.Write("In page load ","Loading the page now");

}

private void Button1_Click(object sender, System.EventArgs e){//Trace. write will display what is happeningwhen button clicked

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

}

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

Page 45: 21436115 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 tohandle 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: 21436115 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 architectureRuntime 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 thesepages(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: 21436115 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 erroroccurs .We can see error status number in IIS settings.

Next

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

entered wrong page.

Page 48: 21436115 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 publicinformation allow anyone to see that information, so they don’t authenticate users. ASP.NETWeb 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 securerestricted resources using NTFS file permissions. By default, the anonymous access account isnamed 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 WindowsComputer Management snap-in as described in the following steps:

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

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

Page 49: 21436115 ASP Net Lab Guide

Step 3: From the user list on the right, double-click the anonymous user account namedIUSR_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 IISsettings. 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 shownbelow.

Page 50: 21436115 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 bydefault.

Page 51: 21436115 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 collectuser 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 thatusers do not have to be member of a domain-based network to have access to yourapplication. Another advantage is that many Web applications—particularly commercial siteswhere customers order products—want to have access to user information. Formsauthentication 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 FormLogin we have to change authentication in web.config into Forms.Open web.config file andprovide 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: 21436115 ASP Net Lab Guide

ElementAttributeDescription<authentication> modeSet to Forms to enable Formsauthentication.<forms>nameUse to set the name of the cookie inwhich to store the user’s credential. Thedefault is auth.aspx. .loginUrlUse to set the name of the Web form todisplay if the user has not already beenauthenticated. If omitted, the default isDefault.aspx.protectionUse to set how ASP.NET protects theauthentication cookie stored on theuser’s machine. The default is All, whichperforms encryption and data validation.Other possible settings are Encryption,Validation, and None.timeoutUse to set the number of minutes theauthentication cookie persists on theuser’s machine. The default is 30,indicating 30 minutes. ASP.NET renewsthe cookie automatically if it receives arequest from the user and more than halfof the allotted time has expired.pathUse to set the path used to store thecookie on the user’s machine. Thedefault is a backslash (\).<credentials>passwordFormat Use to set the algorithm used to encryptthe user’s password. The default is SHA1.Other possible settings are MD5 and Clear(which prevents encryption).<users>nameUse to set the name of the user.passwordUse to set the password for the user.

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

</authentication>

Page 53: 21436115 ASP Net Lab Guide

Step 2: Design your login form like below.

Step 3: For authenticating the form import namespace System.Web.Security.Writefollowing 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: 21436115 ASP Net Lab Guide

Note:The FormsAuthentication class’s Authenticate method checks the user name andpassword against the user list found in the <credentials> element ofWeb.config. The FormsAuthentication class’s RedirectFromLoginPagemethod displays the application’s start page. If the logon fields appear on theapplication’s start page, one should disable them or otherwise indicate asuccessful logon.One can encrypt password using encryption algorithms likeSHA1 or MD5.To encrypt password use Class FormsAuthentication.

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

Step 4: Add one more button to login form and name it as BtnEncrypt.And write a code toencrypt 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");

}

Step 5: Now open web.config file and set passwordFormat as SHA1 and store encryptedpassword.<authentication mode="Forms">

<forms name="Login" loginUrl="Login.aspx"><credentials passwordFormat="SHA1"><user name="Smith"password="1BDA18F74011EAEA119FF9AB870E07E4DC49F097"></user>

Page 55: 21436115 ASP Net Lab Guide

Note: Use the FormsAuthentication class to sign out when the user has finishedwith the application or when you want to remove the authentication cookiefrom his or her machine.

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

</authentication>

Step 6: The following code ends the user’s access to an application and requires him or her tosign 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.