Professional Documents
Culture Documents
NET Programming
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 7: Click browse button present in the to select actual physical directory (where ASP.net
files will be stored).
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.
Sr.
Window Name Description
No.
This Form is used for drawing the visual interface of the
1. Web Form
application.
This Window contains the icons representing various visual
2. Toolbox window
objects or controls that you can place on Web form.
This window lists all the modules present in the current
3. Solution Explorer
project.
This window lists the properties of currently selected
4. Properties Window object. These properties control the appearance and
behavior of the object.
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.
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.
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
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 .
Step 3: Double click on the design window to see a window as shown below
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)
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 ();
}
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.
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.
Change the text properties and ID.Now write following code for btnSubmit_Click event
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
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.
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
AddWebform.
Step 3: Next add table to your form. In the menu bar click TableInsertTable.
Now specify number of rows as 7 and columns as 2 for the table .Change the background
color.
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 TableSelectRow.
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.
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.
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
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
}
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>
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.
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)
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 %>
Step 1: Drag two label controls into a new form SimpleDataBinding.aspx. In HTML view and
specify Binding expressions .
</asp:Label>
</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.DataBind();
}
Background: Multi record data binding involves binding server controls to structures, such as
ArrayList, DataViewObjects etc.
Step 1: Open a new form and name this form as multivalueDataBind.aspx. Drag a dropdown
list and label control on this form.
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();
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
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)
Assignments for Day 2 of 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.
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
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
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)
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.
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.
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
Step 6: After setting paging properties add event for paging and write following code
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.
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.
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.
Response.Redirect("Repeater.aspx");
}
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.
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.
http://localhost/VirtualDirectoryName/welcome.aspx?id1=Smithl&id2=Manager
//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"];
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.
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" />
Step 5: After this we must start asp.net state service in the machine where we are going to
store state information.
Step 6: Now execute the same page. This time session management is done thro State Server.
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 2: Open Global.asax and we can see this file has events like application start, session
start etc.
Step 3: Initialize application count to zero in application start event .For every session
increment this counter by one.
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.
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:
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.
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.
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.
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
);
Cache.Insert("objDs",ds,null,DateTime.MaxValue,TimeSpan.FromSeconds(10
));
Step 6 : We can achive datacahing even thro file dependency.Here cache will be refreshed if
we make any changes to file test.txt.
Assignment 2: Tracing
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.
Trace.Write method writes trace information in normal text color where as if we use
Trace.Warn the message is displayed in red color.
Step 3: When we view the page in Browser we get trace information along with the page.
Step 4: We can even set trace application level .This can be done in web.config file.
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.
http://localhost/VirtualDirectoryName/Trace.axd
Assignment 3: Error Handing
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.
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.
Next
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.
Assignment 4: Security 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.
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.
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.
Assignment 5: Security Forms Authentication
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.
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;
}
}
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.HashPasswordForSt
oringInConfigFile (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>
<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:
1. Continuation with assignment no 2 of day1 .Use form login and store password in