Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
42 views

Unit 3 Asp Net

Uploaded by

pagolchagol14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

Unit 3 Asp Net

Uploaded by

pagolchagol14
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

Unit 3: ASP.NET ASP.

NET 1

Unit 3: ASP.NET

File types in ASP.NET


A typical ASP.Net application consists of many items: the web content files (.aspx), source files
(e.g., the .cs files), assemblies (e.g., the .dll files and .exe files), data source files (e.g., .mdb files),
references, icons, user controls and miscellaneous other files and folders. All these files that
make up the website are contained in a Solution.

Typically a project contains the following content files:

• Page file (.aspx)

• User control (.ascx)

• Web service (.asmx)

• Master page (.master)

• Site map (.sitemap)

• Website configuration file (.config)

Exploring ASP.NET 3.5 Web Pages


ASP.NET Web Pages are files with the .aspx extension and contain the code to implement a
Web application. All these Web pages are stored on the IIS virtual directory.

Steps for creating a new ASP.NET Web Application:


1. Click on Start Programs  Microsoft Visual Studio 2008 Microsoft Visual Studio
2008

2. In VS, this is very easy. Open the File menu and select "New Web Site". You will be
presented with the following dialog:

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 2

3. Select "ASP.NET Web Site", if it's not already selected.

4. Enter the name for your new site in the Location box.

5. Then click on OK.

To add a new ASP.NET Web page to a Web site

1. In Solution Explorer, right-click the project name, and then click Add New Item.
2. In the Add New Item dialog box, under Installed Templates, click the language that you
want to work with, and then click Web Form
3. If you want the code for the page to be in a separate file, be sure that the Place code in
separate file check box is selected. If you want to keep the code and markup in the same
file, clear this check box.
4. In the Name box, type a name for the new Web page, and then click Add.

The new ASP.NET Web page is created and displayed in Visual Studio.

Building our first Welcome Page


Listing:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0


Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h1> Welcome to ASP.NET </h1>
</div>
</form>
</body>
</html>

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 3

Building and Running a Project:

The application is run by selecting either Start or Start Without Debugging from the Debug
menu, or by pressing F5 or Ctrl-F5. The program is built i.e. the .exe or the .dll files are
generated by selecting a command from the Build menu.

Code Render Blocks


Code render blocks define the inline code or inline expressions that are executed when a web
page is rendered. This inline code is then executed by the server and the output is displayed on
the output is displayed on the client browser that is requested for the page. The code render
block s are capable of displaying information on the client browser without calling the Write()
method. The code render blocks are represented by <% and %> symbols. The code present
inside these symbols is executed in the top down manner.

Listing:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<%
for (int i = 0; i <= 6; i++)
{
%>
<font size="<%=i%>">Welcome to ASP.NET 4.5</font><br />
<%
}
%>
</div>
</form>
</body>
</html>

ASP.NET Coding Models


Generally , a web form consists of controls, such as Label, Button, Hyperlink, and business logic.
You can use ASP.NET coding techniques to manage theses controls and business logic. ASP.NET
coding technique refers to the methodologies used for writing code in a Web application.

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 4

ASP.NET provides two types of coding techniques, Single- file model and Code-Behind page
model.

Single file Page model


In the single-file page model, the functionality of a Web application and the HTML markup are
implemented in the same file. The programming code is written in a script block and that
contains the attribute runat=”server” to mark it as code that ASP.NET should execute. Now lets
understand the single-file page model through an application named SinglePageModel.aspx

Listing:

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
void Buton1_Click(Object sender, EventArgs e)
{
Label1.Text = "Clicked at" + DateTime.Now.ToString();
}
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server"></asp:Label>
<asp:Button ID="Button1" runat="server" OnClick ="Button1_Click"
Text="Click Me!" />
</div>
</form>
</body>
</html>

Code-Behind Page Model


In the code-behind page model, there are two seprate files, Default.aspx and Default.aspx.cs(
for C# applications). The Default.aspx file is used for ASP.NET presentation tags and the
Default.aspx.cs file is used to implement the programming logic of a Web Application. These two
files are then linked together to run the Web Application.

The code-behind file uses the partial class rather than the main class and it does not inherit the
.aspx file, where as both the files are combined together during compilation to implementation
the complete application.

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 5

Now lets understand the code-behind model through an application named as


CodeBehindExample. Aspx

Listing

CodeBehindExample.aspx

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="CodeBehindExample.aspx.cs" Inherits="CodeBehindExample" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="Label1" runat="server"></asp:Label>


<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Click Me!" />

</div>
</form>
</body>
</html>

CodeBehindExample.aspx.cs

using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class CodeBehindExample : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Clicked at " + DateTime.Now.ToString();

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 6

}
}

Understanding ASP.NET Page Directives


ASP.Net directives are instructions to specify optional settings, such as registering a custom
control and page language. These settings describe how the web forms (.aspx) or user controls
(.ascx) pages are processed by the .Net framework.

The syntax for declaring a directive is:

<%@ directive_name attribute=value [attribute=value] %>

The Page Directive


The Page directive defines the attributes specific to the page file for the page parser and the
compiler.

The basic syntax for a Page directive is:

<%@ Page Language="C#" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" Trace="true" %>

The Control Directive


The Control directive is used with the user controls and appears in the user control (.ascx) files.
The basic syntax for a sample Control directive is:
<%@ Control Language="C#" EnableViewState="false" %>

The attributes of the Page and Control directive are:

Attributes Description

AutoEventWireup the Boolean value that enables or disables Page events that are
being automatically bound to methods; for example, Page_Load

CodeFile name of the code behind file

Inherits the name of the code behind or other class

Language programming language for code

Src file name of the code behind class

Trace enables or disables tracing

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 7

The Import Directive

The Import directive imports a namespace into a web page, user control pate of application. If
the Import directive is specified in the global.asax, then it will apply to the entire application. If it
is in a page of user control page, then it would apply to that page or control. The basic syntax
for an Import directive is:

<%@ Import namespace="System.Drawing" %>

The Implements Directive


The Implement directive indicates that the web page, master page or user control page must
implement the specified .Net framework interface.The basic syntax for an Implements directive
is:

<%@ Implements Interface="interface_name" %>

The Register Directive


The Register derivative is used for registering the custom server controls and user controls.The
basic syntax for a sample Register directive is:

<%@ Register Src="~/footer.ascx" TagName="footer"


TagPrefix="Tfooter" %>
The Assembly Directive
The Assembly directive links an assembly to the page or the application at parse time. This could
appear either in the global.asax file for application-wide linking or in the page file or a user
control file for linking to a page or user control. The basic syntax for a sample Assembly directive
is:

<%@ Assembly Name ="myassembly" %>

The attributes of the Assembly directive are:

Attributes Description

Name the name of the assembly to be linked

Src the path to the source file to be linked and compiled dynamically

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 8

The Master Directive


The Master directive specifies a page file as being the mater page. The basic syntax for a sample
MasterPage directive is:

<%@ MasterPage Language="C#" AutoEventWireup="true"


CodeFile="SiteMater.master.cs" Inherits="SiteMaster" %>

The MasterType Directive


The MasterType directive assigns a class name to the Master property of a page, to make it
strongly typed. The basic syntax for a MasterType directive is:

<%@ MasterType attribute="value"[attribute="value" ...] %>

The PreviousPageType Directive


The PreviousPageType directive assigns a class to a page, so that the page is strongly typed. The
basic syntax for a sample PreviousPagetype directive is:

<%@ PreviousPageType attribute="value"[attribute="value" ...] %>


The Reference Directive
The Reference directive indicates that another page or user control should be compiled and
linked to the current page. The basic syntax for a sample Reference directive is:

<%@ Reference Page ="somepage.aspx" %>

Understanding the provider model in ASP.NET


Providers can be of two types, namely membership and roles providers based on the types of
the services they provide. The membership provider stores the user names and passwords, and
the roles provider stores the users roles. By default, ASP.NET uses the
ASPNetSqlMembershipProvider Provider. You can change the default provider by using the web
Site Administration Tool or the Microsoft Management Console(MMC).

Implementing Code Sharing


Code Sharing is mechanism through which a common code is shared among different pages of
web application. It is particularly beneficial when you want to make the code with specific
functionality , accessible to all the pages in a Web Application. The following 3 methods are used
to implement code sharing

1. Using the code directory

2. Using the Bin directory

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 9

3. Using the Global Assembly Cache

Using The Code Directory


ASP.NET provides a directory known as App_Code to store code files, accessible to all the
webpages of a web application. When you add files such as class or .xsd files, inside the the
App_Code folder, the files are automatically detected and compiled at runtime. After
completion any page inyour web application can access those files or classes. You need to right
click the project name in the solution explorer and select the Add  Add ASP.NET folder 
App_Code option from the context menu to create the App_Code folder.

Using the Bin Directory


The code for a specific functionality in a webpage of web application can be made accessible to
all the web pages by storing the code file in the Bin directory. The Bin directory is similar to the
App_Code directory except that it stores the precompiled assemblies of the code files that are
required by all the web pages of a web application.

Using Global Assembly Cache


You can use the global assembly cache to implement a specific functionality to all the webpages
of the web application. These assemblies can be accessed by all the web pages of the web
application.

Compilation in ASP.NET
ASP.NET first compiles the code into one or more assemblies that are nothing but the files with
the extension .dll. When the code is compiled, it is converted into a language independent and
CPU- independent language called Microsoft Intermediate Language(MSIL).

Structure of an Application
The structure of the web application includes the concepts of application domain, application
lifetime, and application directory structure. Application domain is a virtual boundry inside
which an application runs, while application lifetime is the span of time for which an application
domain exists. Application directory structure , on the other hand, specifies the directory
structure that organizes the various entitites associated with an application , such as
references, resources and code files in separate directories.

The Application Domain

To understand the concept of domain, we need to understand how an web application works
after it is deployed. We deploy a web application created in ASP.NET on a webserver, such as IIS
the client browser sends a request for the Web application to the Web Server, which is further
then passed to the ASP.NET worker process. The worker process then executes various pages in
their respective domains.

Therefore the application domain provides an isolation boundary for applications, which is
required to ensure the code is running in one application is not affected by another application.

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 10

The application Lifetime

Application lifetime refers to the time span for which an application domain persists.

The Application Directory Structure

The directory structure of an ASP.NET application is as follows:

• Bin – contains compiled .NET assemblies, containing precompiled web pages and web
service classes.

• App_Code – Contains source code files,compiled dynamically ,to be used in the ASP.NET
web application

• App_GlobalResources – Contains the resources that can be used in all Web pages as
well as the controls of the ASP.NET Web application.

• App_LocalResources -- Contains the resources that are accessible only to a specific Web
Page of the ASP.NET Web application.

• App_webReferences – Contains the references to the Web services used by the


ASP.NET Web application.

• App_Data – Contains the database and XML files of the ASP.NET Web Application.

• App_Browser – Contains browser definition files that identify browsers for different
ASP.NET Web Application.

• App_Themes – contains the themes used by ASP.NET Application.

The Global.asax Application File


The Global.asax file, also known as the ASP.NET application file, is an optional file that contains
code for responding to application-level events raised by ASP.NET. The Global.asax file resides in
the root directory of an ASP.NET-based application. At run time, Global.asax is parsed and
compiled into a dynamically generated .NET Framework class derived from the HttpApplication
base class.

Methods corresponding to events that do not fire on each request


Application_Start() – fired when the first resource is requested from the web server and the web
application starts.

Session_Start() – fired when session starts on each new user requesting a page.

Application_Error() – fired when an error occurs.

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 11

Session_End() – fired when the session of a user ends.

Application_End() – fired when the web application ends.

Application_Disposed() - fired when the web application is destroyed.

Using States

State is quite an innovative concept in the web development because it eliminates the
drawback of losing state data due to reloading of a web page. By using states in a web
application you can preserve the state of the application either at the server or the client end.
The state of a web application helps you to store the runtime changes that have been made to
the web application. There are various methods for storing state information. These include the
following:

1. Hidden fields: Refers to the control that is not visible when a web application is
viewed in the browser.

2. Cookies: Refers to the text files that store data, such as user ID and preferences at
the client end.

3. Query Strings: Refers to the information strings added at the end of a URL to
maintain the state of a web application.

The following are some of the methods used to save state information on the web server

1. Application State: Stores application data not frequently modified by users. An object of
the HttpApplicationState Class is used to store the state of an ASP.NET Web
Applications.

2. Session State: Stores information specific to a user session. User session refers to the
duration for which a user uses a web site. An object of the HttpSessionState class is used
to store the session state for each ASP.NET web application that is executed.

3. Profile Properties: Stores a user specific data in a persistent form,

Application State
Application state is used to store data corresponding to all the variables of an ASP.NET web
application. The data in application state is stored once and read several times. Application state
uses the HttpApplicationState class to store and share the data throughout the application. You
can access the information stored in an application state by using the HttpApplication class
property. Data stored in application state is accessible to all the pages of the application and is
the same for all the users accessing the application. The HttpApplicationState class provides a

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 12

lock method which you can use to ensure that only one user is able to access and modify the
data of an application at any instant of time.

Session State
Each client accessing a Web application maintains a distinct session with the web server and
there is also specific information associated with each of the sessions. Session state is defined in
the <sessionsSate> element of the Web.config file. It also stores the data specific to a user
session in session variables. Different session variables are created for each user session. In
addition, session variables can be accessed from any page of the application. When a user
accesses a page a session ID for the user is created.

The session ID is transferred between the server and the client over the HTTP protocol using
cookies.

View State
View state stores page – specific information when a page is posted back to the server. When a
page is processed, the current state of the page and its control is hashed (transforming a
sequence of characters into a fixed length value) into a string and save as a hidden field on the
page. Such a state of the page is called view state.

The ViewState property is used to save the view state of each control used in a page. If the
ViewState property is not used, when the values written in the controls are not retained when
the page is reloaded

View state is maintained in a web page by default. You can include the following directive at the
top of the web page to disable its view state.

<%@ Page EnableViewState = “false”%>

To disable the view state of web control, add the following attribute to the control:

Page.EnableViewState = “false”

Listing Example:

Let’s create a sample web application, StateImplementation, which uses all the three state
types—application, session and view. After creating an empty web site follow the steps:

1. Add the Default.aspx file in the web application.


2. Add the code in the Default.aspx page, as shown in listing below

Global.asax File
<%@ Application Language="C#" %>

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 13

<script runat="server">

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup
Application["visits"] = 0;

void Application_End(object sender, EventArgs e)


{
// Code that runs on application shutdown

void Application_Error(object sender, EventArgs e)


{
// Code that runs when an unhandled error occurs

void Session_Start(object sender, EventArgs e)


{
// Code that runs when a new session is started
Session["mytext"] = " I am the user !!";
}

void Session_End(object sender, EventArgs e)


{
// Code that runs when a session ends.
// Note: The Session_End event is raised only when the
sessionstate mode
// is set to InProc in the Web.config file. If session
mode is set to StateServer
// or SQLServer, the event is not raised.

</script>

Default.aspx File

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 14

protected void Button1_Click(object sender, EventArgs e)


{
string txtvalue = TextBox1.Text;
ViewState.Add("item", txtvalue);
string item = (string)ViewState["item"];
Label1.Text = item;
}

protected void Page_Load(object sender, EventArgs e)


{
Application["visits"] = (int)Application["visits"] + 1;
Label2.Text = Application["visits"].ToString();
Label3.Text = (String)Session["mytext"];
}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Untitled Page</title>
<style type="text/css">
.style1
{
font-weight: bold;
text-decoration: underline;
}
</style>
</head>
<body>

<form id="form1" runat="server">


<div>

<span class="style1">View State</span><br />


<br />
Enter your name<asp:TextBox ID="TextBox1"
runat="server"></asp:TextBox>
<br />
<asp:Button ID="Button1" runat="server"
onclick="Button1_Click" Text="Submit" />
<br />
<br />
<asp:Label ID="Label1" runat="server"
Text="Label"></asp:Label>
<br />
<br />
<span class="style1">Application State</span><br />
<asp:Label ID="Label2" runat="server"
Text="Label"></asp:Label>
<br />
<br />
<span class="style1">Session State</span><br />

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 15

<asp:Label ID="Label3" runat="server"


Text="Label"></asp:Label>
<br />
<br />

</div>
</form>
</body>
</html>

HTTP Handlers

Every request into an ASP.NET application is handled by a specialized component known as an


HTTP handler. The HTTP handler is the most important ingredient while handling ASP.NET
requests.

Examples: ASP.NET uses different HTTP handlers to serve different file types. For example, the
handler for web Page creates the page and control objects, runs your code, and renders the final
HTML.

ASP.NET default handlers:

1. Page Handler (.aspx) - Handles Web pages


2. User Control Handler (.ascx) - Handles Web user control pages
3. Web Service Handler (.asmx) - Handles Web service pages
4. Trace Handler (trace.axd) - Handles trace functionality

Postback
PostBack is the name given to the process of submitting an ASP.NET page to the server for
processing. PostBack is done if certain credentials of the page are to be checked against some
sources (such as verification of username and password using database). This is something that
a client machine is not able to accomplish and thus these details have to be 'posted back' to the
server.

Postback includes cross-post-page posting, which is the name given to the process of receiving
the response of a request by the server on another page.

Questions:
1. What is ASP.NET?
2. Define Postback.
3. What are Http Handlers?
4. What is a state? Explain various methods used to save state information?
5. Write a short note on Global .asax file.
6. Explain various methods of Global.asax File.

Prof. Sushant S. Sundikar Web Programming


Unit 3: ASP.NET ASP.NET 16

7. Explain the directory structure of a ASP.net Web Application.


8. Explain different directives of an ASP.net Page.
9. List the different file types of ASP.net
10. Explain various coding models of ASP.NET
11. How do you implement code sharing in ASP.NET web application?
12. With an example explain asp.net postback .
13. Write an ASP.NET program to keep track of the number of visitors visiting the web page
and to display this count of visitors, with proper headings.
14. Write an ASP.NET program to store current date-time in a COOKIE and display the ‘Last
visited on’ date-time on the web page upon reopening of the same page.
15. Write an ASP.NET program to store page views count in SESSION, to increment the
count on each refresh, and to show the count on web page.

Prof. Sushant S. Sundikar Web Programming

You might also like