Unit 3 Notes
Unit 3 Notes
NET
ASP.NET is part of the Microsoft .NET Framework. To build ASP.NET pages, you need to take
advantage of the features of .NET Framework, which consists of two parts:
The .NET Framework contains more than 13,000 classes you can use when building applications.
Framework Class Library was designed to make it easier to perform the most common
programming tasks. Following are just a few examples of the classes in the framework:
File class-Enables you to represent a file on your hard drive. You can use the File class
to check whether a file exists, create a new file, delete a file, and perform many other file-
related tasks.
Graphics class-Enables you to work with different types of images such as GIF, PNG,
BMP, and JPEG. You can use the Graphics class to draw rectangles, arcs, ellipses, and
other elements on an image
Random class-Enables you to generate a random number.
SmtpClient class-Enables you to send email. You can use the SmtpClient class to send
emails that contain attachments and HTML content.
Each class in the Framework can include properties, methods, and events. The properties,
methods, and events exposed by a class are the members of a class.
For example, following is a partial list of the members of the SmtpClient class:
Properties
Host-The name or IP address of your email server
Port-The number of the port to use when sending an email message
Methods
Send-Enables you to send an email message synchronously
SendAsync-Enables you to send an email message asynchronously
Events
SendCompleted-Raised when an asynchronous send operation completes
For example, the SmtpClient class includes two properties named Host and Port, which enable
you to specify the email server and port to use when sending an email message.
The SmtpClient class also includes two methods you can use to send an email:
i) Send()
ii) SendAsync().
The Send method blocks further program execution until the send operation is completed. The
SendAsync() method, on the other hand, sends the email asynchronously. Unlike the Send()
method, the SendAsync() method does not wait to check whether the send operation was
successful.
Finally, the SmtpClient class includes an event named SendCompleted, which is raised when an
asynchronous send operation completes. You can create an event handler for the
SendCompleted event that displays a message when the email has been successfully sent.
Understanding Namespaces
All the classes are defined in single name called namespaces in ASP.NET.
For example
1. All the classes related to working with the file system are located in the System.IO namespace.
2. All the classes for working a Microsoft SQL Server database are located in the
System.Data.SqlClient namespace.
Before you can use a class in a page, you must indicate the namespace associated with the
class. There are multiple ways of doing this.
1. First you can fully qualify a class name with its namespace. For example, because the File
class is contained in the System.IO namespace, you can use the following statement to check
whether a file exists:
System.IO.File.Exists(“SomeFile.txt”)
You can add an <$I<%@ Import % directive><%@ Import %> directive to a page to import a
particular namespace.
ASP.NET gives you the most commonly used namespaces for free:
System
System.Collections
System.Collections.Generic
System.Collections.Specialized
System.ComponentModel.DataAnnotations
System.Configuration
System.Data.Entity.Linq
System.Data.Linq
System.Text
System.Text.RegularExpressions
System.Web
System.Web.Caching
System.Web.DynamicData
System.Web.SessionState
System.Web.Security
System.Web.Profile
System.Web.UI
System.Web.UI.WebControls
System.Web.UI.WebControls.WebParts
System.Web.UI.HtmlControls
System.Xml.Linq
The second part of the .NET Framework is the Common Language Runtime (CLR). The Common
Language Runtime is responsible for executing your application code.
When you write an application for the .NET Framework with a language such as C# or Visual
Basic .NET, your source code is never compiled directly into machine code. Instead, the C# or
Visual Basic compiler converts your code into a special language named MSIL (Microsoft
Intermediate Language).
MSIL looks very much like an object-oriented assembly language. However, unlike a typical
assembly language, it is not CPU specific. MSIL is a low-level and platform-independent
language.
When your application actually executes, the MSIL code is "just-in-time" compiled into machine
code by the JITTER (the Just-In-Time compiler). Normally, your entire application is not compiled
from MSIL into machine code. Instead, only the methods that are actually called during execution
are compiled.
In reality, the .NET Framework understands only one language: MSIL. However, you can write
applications using languages such as Visual Basic .NET and C# for the .NET Framework
because the .NET Framework includes compilers for these languages that enable you to compile
your code into MSIL.
You can write code for the .NET Framework using any one of dozens of different languages,
including the following:
Ada
Apl
Caml
COBOL
Eiffel
Forth
Fortran
JavaScript
Oberon
PERL
Pascal
PHP
Python
RPG
Scheme
Small Talk
The vast majority of developers building ASP.NET applications write the applications in either C#
or Visual Basic .NET.
ASP.NET controls are the heart of the ASP.NET Framework. An ASP.NET control is a .NET class
that executes on the server and renders certain content to the browser.
The ASP.NET Framework contains over 70 controls. These controls can be divided into eight
groups:
HTML elements in ASP.NET files are, by default, treated as text. To make these
elements programmable, add a runat="server" attribute to the HTML element. This
attribute indicates that the element should be treated as a server control.
Note: All HTML server controls must be within a <form> tag with the runat="server"
attribute!
Note: ASP.NET requires that all HTML elements must be properly closed and properly
nested.
ASP.NET Pages
The ASP.NET Framework enables you to create two different types of ASP.NET pages.
1. Single-file
2. Code Behind(two-file ASP.NET pages)
Single-file
In a single-file ASP.NET page, a single file contains both the page code and page
controls. The page code is contained in a <script runat="server"> tag.
you can create a two-file ASP.NET page. A two-file ASP.NET page is normally referred to
as a "code-behind" page. In a code-behind page, the page code is contained in a
separate file.
Code declaration blocks are lines of code enclosed in <script> tags. They contain the
runat=server attribute, which tells ASP.NET that these controls can be accessed on the
server and on the client. Optionally you can specify the language for the block. The code
block itself consists of the definition of member variables and methods.
Example:
<asp:Label
id="Label1"
Runat="server" />
Note - When using Visual Web Developer, you create a code-behind page by selecting Web Site,
Add New Item, selecting the Web Form Item, and checking the Place Code in Separate File
check box before adding the page.
Page Events
Whenever you request an ASP.NET page, a particular set of events is raised in a particular
sequence. This sequence of events is called the "page execution lifecycle."
Here is the sequence of events that are raised whenever you request a page:
1. PreInit
2. Init
3. InitComplete
4. PreLoad
5. Load
6. LoadComplete
7. PreRender
8. PreRenderComplete
9. SaveStateComplete
10. Unload
5. State management
To refer to the problems mentioned before, ASP.NET provides solutions for session and
application state management. State information can, for example, be kept in memory or
stored in a database. It can be shared across Web farms, and state information can be
recovered, even if the server fails or the connection breaks down.
6. Update files while the server is running
Components of your application can be updated while the server is online and clients are
connected. The Framework will use the new files as soon as they are copied to the
application. Removed or old files that are still in use are kept in memory until the clients
have finished.
ASP.NET Overview
ASP.NET provides services to allow the creation, deployment, and execution of Web
Applications and Web Services
Like ASP, ASP.NET is a server-side technology
Web Applications are built using Web Forms. ASP.NET comes with built-in Web Forms
controls, which are responsible for generating the user interface. They mirror typical
HTML widgets like text boxes or buttons. If these controls do not fit your needs, you are
free to create your own user controls.
Web Forms are designed to make building web-based applications as easy as building
Visual Basic applications
ASP.NET Architecture
ASP.NET is based on the fundamental architecture of .NET Framework. Visual studio provide a
uniform way to combine the various features of this Architecture.
Architecture is explained form bottom to top in the following discussion.
ADO.NET is intended specifically for developing web applications. This is evident from its
two major design principles:
1. Disconnected Datasets—In ADO.NET, almost all data manipulation is done
outside the context of an open database connection.
2. Effortless Data Exchange with XML—Datasets can converse in the universal
data format of the Web, namely XML.
4. The 4th layer of the framework consists of the Windows application model and, in
parallel, the Web application model.
The Web application model-in the slide presented as ASP.NET-includes Web Forms and
Web Services.
ASP.NET comes with built-in Web Forms controls, which are responsible for generating
the user interface. They mirror typical HTML widgets like text boxes or buttons. If these
controls do not fit your needs, you are free to create your own user controls.
Web Services brings you a model to bind different applications over the Internet. This
model is based on existing infrastructure and applications and is therefore standard-
based, simple, and adaptable.
Web Services are software solutions delivered via Internet to any device. Today, that
means Web browsers on computers, for the most part, but the device-agnostic design of
.NET will eliminate this limitation.
5. One of the obvious themes of .NET is unification and interoperability between various
programming languages. In order to achieve this; certain rules must be laid and all the
languages must follow these rules. In other words we cannot have languages running
around creating their own extensions and their own fancy new data types. CLS is the
collection of the rules and constraints that every language (that seeks to achieve .NET
compatibility) must follow.
6. The CLR and the .NET Frameworks in general, however, are designed in such a way that
code written in one language can not only seamlessly be used by another language.
Hence ASP.NET can be programmed in any of the .NET compatible.
AdRotator Control
AdRotator control is available in ASP.Net to make the task of rotating the advertisement images
in a web form quickly and easily.
AdRotator control are used to create a dynamic ads. The AdRotator Control presents ad images
each time a user enters or refreshes a webpage. When the ads are clicked, it will navigate to a
new Web location. The AdRotator control is used to display a sequence of ad images.The
AdRotator control to work we need an Advertisement file (XML file) and some sample images.
Adding the AdRotator web server control to your web application. First, select the AdRotator and
drag and drop the control to your web form. Map the XML file which contains the details about
each and every ad.
This control uses an XML file to store the ad information. The XML file must begin and end with
an <Advertisements> tag. Inside the <Advertisements> tag there may be several <Ad> tags
which defines each ad.
The predefined elements inside the <Ad> tag are listed below:
Element Description
Properties
Property Description
AdvertisementFile Specifies the path to the XML file that contains ad information
AlternateTextField Specifies a data field to be used instead of the Alt text for an ad
runat Specifies that the control is a server control. Must be set to "server"
Height The height of the ad in pixels. This value overrides the default
height setting for the AdRotator control.
Width The width of the ad in pixels. This value overrides the default width
setting for the AdRotator control.
The advertisement file is an XML file. The following are some of the elements of this XML file.
XML code that has the details about the ads. The file Ads.xml looks like the code below:
<Advertisements>
<Ad>
<ImageUrl>adimages/2.jpg</ImageUrl>
<NavigateUrl>http://cat2.com</NavigateUrl>
<AlternateText>Cat 2</AlternateText>
<Impressions>30</Impressions>
</Ad>
<Ad>
<ImageUrl>adimages/3.jpg</ImageUrl>
<NavigateUrl>http://cat3.com</NavigateUrl>
<AlternateText>Cat 3</AlternateText>
<Impressions>20</Impressions>
</Ad>
Events Description
It is raised once per round trip to the server after creation of the
AdCreated
control, but before the page is rendered
Occurs when the server control is initialized, which is the first step
Init
in its lifecycle.
Load Occurs when the server control is loaded into the Page object.
MultiView Control:
The MultiView control represents a control that acts as a container for groups of View controls.. It
creates a set of views and one view is visible at a time. Use View control to create views inside
the MutliView control. Add the View controls into a MultiView control.
The main advantage of the multiview control is that we can specify the required view only (i.e
display the required view only) on a single page.Multiview control helps us to create different
views in the same page and display the view as the user clicks the links.
The MultiView control acts as a container for groups of View controls. Each View control in turn
contains child controls such as buttons and text boxes.
The MultiView and Wizard controls both allow you to create multiple sections of controls on the
same page. The Wizard control has features built in to facilitate its operation such as built-in Next
and Prev buttons. With the Multiview control the responsibility to add and code the navigation falls
to you.Figure: MultiView controls contain individual View controls
Me.MultiView1.ActiveViewIndex = 1
Me.MultiView1.SetActiveView( )
Me.MultiView1.Views(1))
Properties Description
A zero based index that denotes the active view; if no view is active
ActiveViewIndex
then the index is -1.
The CommandName attribute of the Button controls associated with the navigation of the
MultiView control are associated with some related field of the MultiView control.
For example, if a Button control with CommandName value as NextView is associated with the
navigation of the multiview, it automatically navigates to the next view when the button is clicked.
The following table shows the default command names for the above properties:
Properties Description
NextViewCommandName NextView
PreviousViewCommandName PrevView
SwitchViewByIDCommandName SwitchViewByID
SwitchViewByIndexCommandName SwitchViewByIndex
Methods Description
Events Description
Apart from the above mentioned properties, methods and events, multi view control inherits the
members of the control and object class.
Wizard Control
Wizard control eliminates the need to design forms to execute a step by step process in the
actual business flow. This simplifies the work of developers to design and write the code. The
ASP.NET Wizard control simplifies many of the tasks associated with building a series of forms to
collect user data. The control provides a mechanism that allows you to easily build the desired
wizard as a collection of steps
The control provides a mechanism that allows you to easily build the desired wizard as a
collection of steps, add a new step, or reorder the steps. You don't have to write any
infrastructure whatsoever for navigation or to persist user data between steps.
The Wizard control works much like the MultiView control in that they both contain sections to
place controls in. While the sections in a MultiView control are views, the sections in a Wizard
control are called steps. The Wizard control has features built in to facilitate its operation such as
built-in Next and Prev buttons. With the Multiview control the responsibility to add and code the
navigation falls to you.
These steps are stored in the WizardSteps collection. The primary difference between the two
controls is that the Wizard control can display links to all of the steps in a sidebar on the left-hand
side of the control.
You can add or remove steps from a wizard control by selecting the Add/Remove WizardSteps
option from the smart tag Wizard Tasks menu.
Figure : Use the Wizard control to implement step-by-step processes.
Template Description
FinishNavigationTemplate Specifies the navigation bar shown before the last page of the wizard; by
default, navigation bar contains the Previous and Finish buttons
SideBarTemplate Used to display content in the left side of the wizard control
StartNavigationTemplate Specifies the navigation bar for the first view in the wizard; by default,
contains only the Next button
StepNavigationTemplate Specifies the navigation bar for steps other than first, finish, or complete; by
default, contains Previous and Next buttons
Property Description
ActiveStep Returns the current wizard step object; the object is an instance of the WizardStep class
ActiveStepIndex Gets and sets the zero-based index of current wizard step
DisplaySideBar Toggles the visibility of the sidebar; the default value is True
FinishStepButtonText Gets and sets the text for the Finish button
NextStepButtonText Gets and sets the text for the Next button
PreviousStepButtonText Gets and sets the text for the Previous button
The wizard ActiveStep property can be set by the ActiveStepIndex="0" of the wizard control. The
first form will have the next navigation control.
Setting Description
Wizard Events -
ImageMap control
The ASP.NET ImageMap control allows you to create an image that has individual regions that
users can click, which are called hot spots. Each of these hot spots can be a separate hyperlink
or postback event.
ImageMap Elements:
o The ImageMap control consists primarily of two pieces. The first is an image, which can
be a graphic in any standard web graphic format, such as a .gif, .jpg, or .png file.
o The second element is a collection of hotspot controls. Each hotspot control is a different
element. For each hotspot control, you define its shape — a circle, rectangle, or
polygon — and the coordinates that specify the location and size of the hot spot.
There are three different types of hot spots offered by ImageMap control. They are:
o CircleHotspot
o RectangleHotspot
o PolygonHotspot
CircleHotspot: CircleHotspot defines circle shaped hot spot region in an ImageMap control. To
define the region for a circle hot spot, we should define X and Y coordinates for circle as well as
radius property which usually is the distance from the center of circle to the edge.
All these hotspots types have some properties to customize the hotspot region and behavior.
We can specify Left, Top, Right and Bottom for Rectangle hotspot and X, Y and Radius
properties for Circle hotspot.
Each hot spots can be configured as a hyperlink that goes to a URL that you provide for that hot
spot. Alternatively, we can configure the control to perform a postback when a user clicks a hot
spot, providing a unique value for each hot spot. The postback raises the ImageMap control's
Click event. In the event handler, you can read the unique value that you assign to each hot spot.
Master pages:
ASP.NET master pages allow you to create a consistent layout for the pages in your application.
A single master page defines the look and feel and standard behavior that you want for all of the
pages (or a group of pages) in your application. You can then create individual content pages that
contain the content you want to display. When users request the content pages, they merge with
the master page to produce output that combines the layout of the master page with the content
from the content page.
In addition to static text and controls that will appear on all pages, the master page also includes
one or more ContentPlaceHolder controls. These placeholder controls define regions where
replaceable content will appear. In turn, the replaceable content is defined in content pages.
Content Pages
You define the content for the master page's placeholder controls by creating individual content
pages, which are ASP.NET pages (.aspx files and, optionally, code-behind files) that are bound to
a specific master page. The binding is established in the content page's @ Page directive by
including a MasterPageFile attribute that points to the master page to be used.
From the user's perspective, the combined master and content pages are a single, discrete page.
The URL of the page is that of the content page.
From a programming perspective, the two pages act as separate containers for their respective
controls. The content page acts as a container for the master page. However, you can reference
public master-page members from code in the content page.
Note that the master page becomes a part of the content page. In effect, the master page acts in
much the same way a user control acts — as a child of the content page and as a container
within that page. In this case, however, the master page is the container for all of the server
controls that are rendered to the browser.
Master pages provide functionality that developers have traditionally created by copying existing
code, text, and control elements repeatedly; using framesets; using include files for common
elements; using ASP.NET user controls; and so on.
They allow you to centralize the common functionality of your pages so that you can
make updates in just one place.
They make it easy to create one set of controls and code and apply the results to a set of
pages. For example, you can use controls on the master page to create a menu that
applies to all pages.
They give you fine-grained control over the layout of the final page by allowing you to
control how the placeholder controls are rendered.
They provide an object model that allows you to customize the master page from
individual content pages.
Master pages allow you to create a consistent look and behavior for all the pages (or
group of pages) in your web application.
A master page provides a template for other pages, with shared layout and functionality.
The master page defines placeholders for the content, which can be overridden by
content pages. The output result is a combination of the master page and the content
page.
The content page contains the content you want to display.
When users request the content page, ASP.NET merges the pages to produce output
that combines the layout of the master page with the content of the content page.
Figure: Master pages combine with content pages to form the rendered page.
A complete master page contains HTML, optional ASP.NET web controls, optional user controls,
and one or more required ContentPlaceHolder controls. A ContentPlaceHolder control is a
special ASP.NET web container control (<asp:contentplaceholder>) responsible for containing
the controls placed on a content web page. You will find the ContentPlaceHolder control in the
Standard section of the Toolbox. You can place one or more ContentPlaceHolder controls on a
master page. All content on a content form is restricted to one of the ContentPlaceHolder controls
defined on the content page's master page. The master page content on a content page is
grayed out and not editable from within the content page. The only live areas available in the
designer are the ContentPlaceHolder controls defined in the master page.
To create a master page you simply create a new page of type master page (see Figure).
Figure: A master page is comprised of HTML, web controls, and one or more
ContentPlaceHolders
Figure: Check the "Select master page" checkbox to create a content page.
Site Navigation
You can easily build navigation into your pages by using the following ASP.NET site-navigation
controls:
SiteMapPath Control
Menu Control
Treeview Control
Before using Site Navigation control let go through overview of sitemap, which is used as
datasource to assign this control.
SiteMap
SiteMap file is an XML File, which contains details of navigation that is followed by navigation
control.
This control displays a navigation path — which is also known as a breadcrumb or eyebrow —
that shows the user the current page location and displays links as a path back to the home page.
The control provides many options for customizing the appearance of the links.
The SiteMapPath control creates breadcrumb navigation with very little effort on your part.
Fig.Output Listing of AsiaNews page displaying breadcrumb navigation
PathSeparator Property:
PathSeparator property defines the element to separate the link elements. By default, (>) greater
than symbol is used to separate link elements as shown in above listing
PathDirection Property:
This property changes the direction of the links generated in the output. Possible settings for this
property are RootToCurrent and CurrentToRoot. In the above example, I have used default
RootToCurrent setting. If we change the setting to CurrentToRoot you will the output as shown
below. I think you got the difference.
Output listing with PathDirection set to CurrentToRoot
ParentLevelsDisplayed : It specifies the number of levels of parent nodes and then displays the
control accordingly related to the currently displayed node.
RenderCurrentNodeAsLink : It specifies whether or not the site navigation node that represents
the currently displayed page is rendered as a hyperlink.
PathSeperator : It specifies the string that displays the SiteMapPath nodes in the rendered
navigation path.
CurrentNodeStyle : It specifies the style used for the display text for the current node.
RootNodeStyle : It specifies the style for the root node style text.
NodeStyle : It specifies the style used for the display text for all nodes in the site navigation path.
The Menu control is used to display menus. The menu can be displayed vertically or horizontally.
Below are two screenshots showing vertical and horizontal menus:
Horizontal Menu:
Vertical Menu:
For making a menu change its orientation you just need to change the Orientation property of the
Menu control to Horizontal or Vertical.
Eg.,
Menu.Orientation = Orientation.Vertical;
You can set individual properties of the Menu control to specify the size, color, font, and other
characteristics of its appearance. In addition, you can apply skins and themes to the Menu
control.
Menu control displays two types of menus: a Static menu and Dynamic menu. The static menu
is always displayed in menu control. By default, only menu items at the root levels are displayed.
You can also display additional menu levels by setting StaticDisplayLevels property.
Menu items with a higher level than the value specified by StaticDisplayLevels property are
displayed in dynamic menu. A Dynamic menu appears only when the user positions the mouse
pointer over the parent menu item that contains a Dynamic submenu.
When the user clicks a menu item, the Menu control can either navigate to a linked Web page or
simply post back to the server. If the NavigateUrl of a menu item is set, the Menu control
navigates to the linked page; otherwise, it posts the page back to the server for processing. By
default, a linked page is displayed in the same window as menu control.
Features
Drag and drop the menu server control from Navigation Section of Toolbox and similarly drag
and drop the SiteMapDataSource control from Data Section of Toolbox and connect the two by
using Menu control’s DataSourceId property. From this example, you can see that I’m using a
SiteMapDataSource control that automatically works with the application’s web.sitemap file.
DataSourceID property will connect the menu control with SiteMapDataSource control
Menu Control Properties dialog box
Fig.Output listing for Menu Control using SiteMapDataSource control using sitemap xml
TreeView Control
Root - A root node is a node that has no parent node. It has one or more child nodes.
Parent - A node that has a parent node and one or more child nodes
Leaf - A node that has no child nodes
Step 1: Open Visual Studio 2008 and drag a TreeView control from the toolbar and drop on page
as follows:
Select "New data source" and select sitemap and press ok.
XmlDataSource - This control allows you to bind to XML data, which can come from a
variety of sources such as an external XML file, a DataSet object and so on. Once the
XML data is bound to the XmlDataSource control, this control can then act as a source of
data for other data-bound controls such as TreeView and Menu. For example, you can
use the <asp:XmlDataSource> control to represent a hierarchical XML data source.
SiteMapDataSource - This control basically retrieves the site map information from the
web.sitemap file.
Displaying checkbox with treeview control, you can assign "ShowCheckBox" property of
TreeView control to either
TreeNodeStyle Properties
Web Parts
A Web Part, also called a Web Widget, is an ASP.NET server control which is Web Part
Pages by users at run time. It can be put into certain places in a web page by end users, after
developing by programmer. End users can customize Web Parts pages by changing the page
layout, adding and removing Web Parts, editing Web Parts properties, establishing connections
between Web Parts, and more.
ASP.NET Web Parts is an integrated set of controls for creating sites that enable end
users to modify the content, appearance, and behavior of web pages directly from a browser. The
modifications can be applied to all users on the site or to individual users. When users modify
pages and controls, the settings can be saved to retain a user's personal preferences across
future browser sessions, a feature called personalization. These Web Parts capabilities mean that
developers can empower end users to personalize a web application dynamically, without
developer or administrator intervention.
o Web Parts allows for personalization of page content. They allow users to move or hide
the Web Parts and add new Web Parts changing the page layout.
o Web Parts allows user to export or import Web Parts settings for use in other pages.
Web Parts retain the properties, appearance and the data across the pages when
imported or exported.
o Web Parts can be assigned role-based access. So you can determine which Web Parts
can share by all or which should be hidden for certain roles. This helps us to provide
customized content based on security.
o Web Parts can talk to each other. You can utilize the data in one Web Part in another
Web Part for different purposes.
Web Parts Modes
The modular and customizable sites that you can build with the new Portal Framework enable
you to put the web page that is in view into several modes for the end user. Modes are very
powerful in that they enable user to edit Web Parts, delete the Web Parts or customize Web
Parts.
There are two basic ways to create a Web Part. You can treat any standard Microsoft ASP.NET
control as a Web Part or you can build a custom control that derives from the base WebPart
class.
You are not required to modify a control in any way to use it as a Web Part. Standard ASP.NET
controls (such as the Calendar and GridView controls), Web User Controls, and even custom
controls can all be used as Web Parts
WebPartManager
WebPartManager is the most important of all the Web Part controls, responsible for managing
and coordinating all controls inside WebPartZones. The Web Parts framework doesn't work
without it, so every page that uses Web Parts must have an instance of WebPartManager
declared, and it must be declared before other Web Parts controls. WebPartManager has no UI,
so it's not visible on the page. It also exposes a very rich API for adding Web Parts to the page,
closing Web Parts, connecting Web Parts, and more.
WebPartZone
WebPartZone is arguably the second most important Web Part control. It's used to define zones,
which serve as containers for Web Parts. There is no practical limit to the number of
WebPartZones a page can contain, and no limit to the number of Web Parts that a zone can
contain. A WebPartZone control can host controls that do not derive from the WebPart class, by
wrapping them with a GenericWebPart control at run time.
Catalog Zone
One of the chief benefits to building pages from Web Parts is that the content of these pages can
be interactively configured by the user. It's a simple matter, for example, to enable users to
restore closed Web Parts to the page by including a CatalogZone in the page.
The purpose of the CatalogZone control is to allow end users to customize Web Parts pages by
adding Web Parts to them. Web Parts can come from three sources: Web Parts that were
previously present in the page but were closed, Web Parts that don't appear on the page by
default but that can be added, and Web Parts imported from .WebPart files.
A CatalogZone control becomes visible only when a user switches a Web page to catalog display
mode (CatalogDisplayMode) as shown below:
CatalogPart:
CatalogPart controls provide the UIs for adding Web Parts to the page. A CatalogZone can
contain any combination of CatalogParts.
A CatalogZone can contain several types of CatalogPart controls. The following list summarizes
the CatalogPart controls provided with the Web Parts control set:
PageCatalogPart
DeclarativeCatalogPart
ImportCatalogPart
PageCatalogPart
The PageCatalogPart class serves one very specific purpose on a Web Parts page: it acts as a
page catalog to contain any controls previously added to the page that a user has closed, and
that the user can add back to the page. Add a PageCatalogPart control to your page if you want
to provide users with the flexibility of closing and reopening controls. If your page does not allow
users to close controls at all, there is no need to add a PageCatalogPart control to your page.
DeclarativeCatalogPart
The DeclarativeCatalogPart control provides a way for developers to add a set of server controls
declaratively to a catalog on a Web page. A catalog, in the Web Parts control set, is simply a list
of WebPart or other server controls that is visible when a page is in catalog display mode. A user
can select controls from the list and add them to the Web page, which effectively gives users the
ability to change the set of controls and the functionality on a page, as shown below:
ImportCatalogPart
The ImportCatalogPart control enables users to import a description file that describes settings on
a WebPart control or server control that a user wants to add to a Web page. After the user has
imported the description file, the WebPart control referenced in the file appears within the
ImportCatalogPart control when the page is in catalog mode, and a user can then add the control
to the page. User can view the ImportCatalogPart in Catalog Display mode, as shown below.
User can browse the web part file and then upload by clicking Upload button.
Editor Zone
The purpose of the EditorZone control is to allow end users to customize Web Parts pages by
editing the properties of the page's Web Parts. Editing UIs are provided by EditorPart controls,
which divide Web Part properties into four categories:
Properties that affect appearance, Properties that affect behavior, Properties that affect layout
and Custom properties added by Web Part developers.
An EditorZone can contain any combination of EditorParts. EditorZones are only visible when the
display mode is EditDisplayMode. User can click the Edit verb from webpart to open the Editor
Zone.
Editor Zone with AppearanceEditorPart
Editor Zone with LayoutEditorPart
Web Parts can and often do implement custom properties to complement the built-in properties
provided by the Web Parts framework. A Web Part that shows stock prices, for example, might
implement a public property named "Stocks" to enable end users to specify which stock prices
are shown. PropertyGridEditorParts provide UIs for editing custom properties. Attributing a
property [WebBrowsable] enables that property to appear in a PropertyGridEditorPart. Of course,
the PropertyGridEditorPart must be declared in an EditorZone if it's to appear on the page.
WebPart Connection
Connections enable Web Parts to share data. A classic example is a Web Part control that shows
the current weather and allows the user to enter a zip code so the weather can be localized.
Another Web Part on that page--perhaps one that shows news headlines--might want that zip
code so it, too, can localize content. Rather than require the user to enter the zip code twice, you
can connect the two Web Parts so that one can get the zip code from the other. Connections can
be defined statically by page developers, or they can be created dynamically by end users. The
ConnectionsZone control provides a UI for creating connections dynamically.
Connection Provider
Writing a connection provider is no more difficult than writing a method that returns an interface
reference and attributing that method [ConnectionProvider]. The first parameter to
[ConnectionProvider] assigns a friendly name to the provider connection point and is displayed by
the ConnectionsZone UI. The second parameter assigns a unique ID to the provider connection
point. A provider can implement multiple provider connection points if desired. Each provider
connection point must be assigned a unique ID.
ConnectionConsumer
Writing a connection consumer is a matter of writing a method that receives an interface
reference and attributing that method [ConnectionConsumer]. The first parameter to
[ConnectionConsumer] assigns a friendly name to the consumer connection point and is
displayed by the ConnectionsZone UI. The second parameter assigns a unique ID to the
consumer connection point.
Unit IV- Advanced Features of ASP.NET
Security in ASP.NET
The most useful feature available in ASP.NET 3.5 is a suite of seven controls designed to simplify
the applications that authenticate users. In Visual Studio 2008, these controls are located in the
toolbox under the Login tab.
1. “Login”: Allows the user to log in by entering a user name and password.
2. “CreateUserWizard”: Allows the user to create a new user account.
3. “PasswordRecovery”: Allows the user to retrieve a forgotten password.
4. “ChangePassword”: Allows the user to change his or her password.
5. “LoginView”: This displays the contents of a template based on the user’s login status.
6. “LoginStatus”: If the user is logged in, displays a “Logout” link for the user to log out. If the
user isn’t logged in, displays a “Login” link that leads to the application’s login page.
7. “LoginName”: This displays the user’s login name if the user is logged in.
Two aspects of user registration and login security in ASP.NET, and they are:
1. Authentication – The process of determining who a user is, and whether the user really
is who he or she claims to be.
2. Authorization – The process of determining whether a particular user, once
authenticated, can access a particular Web site page.
1
Three types of authentication
1. Forms-based authentication:
This method of authentication uses a membership database to store the names and
passwords of valid users. In this method, whenever a user attempts to access a restricted
or limited access page, ASP.NET automatically redirects the user to a login page, which
is normally named “Login.aspx”, which prompts the user to login with a user name and
password in order to authenticate that user. The originally requested page is then
displayed if the user is valid. This is the most common type of authentication for Web
sites that allow public access but require that users create login accounts to access the
application.
2. Windows-based authentication:
This method of authentication uses the existing Windows accounts to authenticate users.
This type of authentication is used mostly for intranet applications, where the users
already have valid Windows accounts.
3. Passport authentication:
Login control
ASP.NET 2.0’s new “Login” control provides you with a more convenient way to let the users of
your application log in to you application. The “Login” control should be placed in a page called
“Login.aspx” unless you changed the default “<authentication>” in the “web.config” file for the
login page.
2
The “Login” control in its simplest form will look like the following:
If you insert wrong username and password then message will show like this:
Note:
The “Login” control displays text boxes that let the user enter a user name and password.
If the fields are filled in, the “Login” control uses the membership provider to look up the
user name and password in the membership database.
If the user name and password are valid, the user is logged in and the page requested is
displayed else if it is not valid, an error message is displayed and the user will not be
logged in to show the requested page.
In ASP.NET, you have the ability to customize your “Login” control by using any of the optional
attributes listed below.
Attribute Description
CreateUserText The text displayed as a link to the register new user page.
The URL of the page for successful log in. If you don’t specify this
DestinationPageUrl attribute, the page which the user was on before getting to this page
is displayed.
3
A checkbox, which is a Boolean, to choose whether the Login
DisplayRememberMe Control should automatically let the user save his info by saving a
cookie and avoid re-logging in.
Is the text that will be displayed if the Log in information is not valid.
FailureText If you do not change this message, a default message“Your login
attempt has failed. Please try again” is displayed.
A text displayed underneath the title text providing the user with login
InstructionText information. If you do not change this attribute, the default is an
empty string.
The URL for the image used as a link to the recover a lost password
PasswordRecoveryIconUrl
page.
CreateUserWizard control
ASP.NET “CreateUserWizard” control automates the task of entering the information for a new
user and creating a record for the user in the membership database. The “CreateUserWizard”
control displays text boxes that let the user enter a user name, a password, an e-mail address, a
security question, and the answer to the security question.
4
Note:
If the user clicks the “SignUp” link, the “CreateUserWizard” control attempts to create a
new user account with the information entered by the user into the form.
If the account is successfully created, the user is logged in to the new account.
If the account can’t be created, for instance if the account with the same user name
already exists, an error message is displayed.
The “CreateUserWizard” control in its simplest form will look like the following:
In ASP.NET 2.0, you have the ability to customize your “CreateUserWizard” control by using any
of the optional attributes listed below.
Attribute Description
5
runat “runat=“Server” is needed for all ASP.NET server controls.
CancelButtonImageUrl The URL for the image used for the Cancel button.
CancelDestinationPageUrl The URL of the page after the Cancel button is clicked.
ContinueButtonImageUrl The URL for the Continue button image on the Success page.
The URLof page the user is taken to after clicking the Continue
ContinueDestinationPageUrl
button.
InstructionText The text for the instructions to use the “CreateUserWizard” control.
6
Note:
In ASP.NET 2.0, you can apply AutoFormat or the style attributes to customize the
appearance of the “CreateUserWizard” control.
The user is always logging to the application after the register is complete, so if you
would prefer not to, you can specify it using the LoginCreatedUser="False" attribute.
If you want the user account to be automatically deavticated till the administrator or
moderator approve it, you can specify it using DisableCreatedUser="True".
By default, the “CreateUserWizard” control has two steps, the “CreateUserWizardStep”
and “CompleteWizardStep” as shown in the code above. You can add steps or even a
sidebar with links to each of the steps.
The “CreateUserWizard” control can send a confirmation e-mail to the new user using
two methods;
o In the “<MailDefinition>” child element
<MailDefinition
From="[email protected]"
Subject="Subject Line"
BodyFileName="BodyFile.txt">
</MailDefinition>
Note:
The body of the e-mail message will be taken from the file "BodyFile.txt" in the
“BodyFileName attribute”.
This “.txt” file can include “<%UserName%>” and “<%Password%>” so you can put the
user’s account name and password into the email.
For the “<MailDefinition>” child element to work, “<MailSettings>" element in the
application’s “web.config” file should be changed into:
7
<system.net>
<mailSettings>
<smtp>
<network host="smtp.yourhostnamehere.com"
from="[email protected]" />
</smtp>
</mailSettings>
</system.net>
Note:
The “SMTP” settings for the “network host” and the address “from” should be changed to
the one you want to use.
PasswordRecovery control
ASP.NET 2.0’s new “PasswordRecovery” control allows you to easily create a way to retrieve a
forgotten password. In this control, the user has to enter their security question and the answer to
it. If the values are valid, the password is reset to a random value and that password is emailed to
the email address the user provided when registering to the application.
The “PasswordRecovery” control in its simplest form will look like the following:
8
Once users enter valid user names, they must answer their secret questions. In the browser, the
page looks like that shown below.
If everything is formatted correctly, the email will be sent and a message will appear to the user
similar to this:
The new password can be sent to the user’s email account. The “PasswordRecovery” control can
send a confirmation e-mail to the new user using two methods:
9
</MailDefinition>
</asp:PasswordRecovery>
Note:
The body of the e-mail message will be taken from the file "BodyFile.txt" in the
“BodyFileName”attribute.
This “.txt” file can include “<%UserName%>” and “<%Password%>” so you can put the
user’s account name and password into the email.
In ASP.NET 2.0, you have the ability to customize your “PasswordRecovery” control by using any
of the optional attributes listed below.
Attribute Description
The text fot the “Failure” text field if the password could not be
GeneralFailureText
retrieved.
SuccessPageUrl The URL for theSuccess page if the password has been recovered.
The text for the message if the password retrieval is successful, and
SuccessText
this is not displayed if the “SuccessPageUrl” is provided.
UserNameInstructionText The text for the instructions for the Username request area.
10
ChangePassword control
ASP.NET 2.0’s new “ChangePassword” control gives you the ability to automate the process of a
user wanting to change their password. You can configure the new “ChangePassword” control to
accepts the username and the password the user wishes to change. You can also configure it
such that the user cannot enter his username, but should be logged into the application as a user
to change the password.The new “ChangePassword” control also can be configured such that
after changing the password, the new password can be e-mailed back to the user.
The “ChangePassword” control in its simplest form will look like the following:
The “ChangePassword” control can send a new password e-mail to the user using the
“<MailDefinition>” child element. The following is a sample code of how this will look like:
Note:
The body of the e-mail message will be taken from the file "BodyFile.txt" in the
“BodyFileName attribute”.
This “.txt” file can include “<%UserName%>” and “<%Password%>” so you can put the
user’s account name and password into the email.
In ASP.NET 2.0, you have the ability to customize your “ChangePassword” control by using any
of the optional attributes listed below.
Attribute Description
11
runat runat="Server" is needed for all ASP.NET server controls.
CancelButtonImageUrl The URL for the image used for the Cancel button.
CancelDestinationPageUrl The URL of the page after the Cancel button is clicked.
The text diplyed for the instruction for the new password and
PasswordHintText its requiermetns, like how many character, minimum length,
etc…
12
PasswordLabelText The text displayed for the “Current Password” label field.
Note:
The “ChangePassword” control requires the user to be logged in to change the password
by default. You can change this by specifying the “DiplayeUsername=True” attribute. This
will display a “Useraname"textbox, where the user has to enter the valid user name and
password to change the password for any user.
The “ChangePassword” control has two views, and they are:
o The Initial view – this is the Change Password view including the text boxes for
the user to enter the new password.
o The Success view – displayed when the password change is successful with a
confirmation message. The success view is not displayed if the
“SuccessPageUrl” is provided, but instead the page in the URL specified will be
shown.
13
LoginView control
ASP.NET 2.0’s new “LoginView”control is a template control. This template control can display
the contents of its templates according to the login status of the user. This gives you the ability to
customize your content of your web application for the needs of different users.
For example:
The User authentication application should use a “LoginView” control to display a link to the
administrator’s page because this page should be only visible to the users with the login status of
an “Admin”.
The “LoginView” control does not have any special attributes to customize its appearance or
behavior but you can customize the “LoginView” control by using the three types of templates of
which each can be coded in as a child element. The three templates are:
The following is a sample code for all the three types of templates of a “LoginView” control.
14
Note:
The “<RoleGroups>” elements can containg more than one “<RoleGroups>”, these
elements can be used alongside the “Anonymous” and the “LoggedIn” templates.
LoginName control
ASP.NET 2.0’s new “LoginName” control is used to display the user’s username which the user
logged in to the web application from. If a user is not currently logged into the web application, the
“LoginName” control does not display anything.
The “LoginName” control in its simplest form will look like the following:
If you want a custom message such as a welcome message to be displayed in front of the
Username, you can do the following:
Note:
The “Welcome” text will be added as a prefix to the Username if the user has logged in, and if no
user is logged in nothing is displayed.
LoginStatus control
ASP.NET 2.0’s new “LoginStatus” control will display a link for the user to log into or log out of the
web application depending on whether theuser is logged in or out.
For example:
The “LoginStatus” control in its simplest form will look like the following:
15
In ASP.NET 2.0, you have the ability to customize your “LoginStatus” control by using any of the
optional attributes listed below.
Attribute Description
The action to do after the user logs out. This can be specified to “Redirect”
to redirect the user to a page in the “LogoutPageUrl” attribute, or
LogoutAction
“RedirectToLoginPage” to redirect the user to the login page, or “Refresh”
to refresh the current page.
The URl for the rdirect page after a user logs out if the “LogoutAction”
LogoutPageUrl
attribute specifies “Redirect”.
Web pages rarely are stand alone. Web applications almost always need to track users who visits
multiple pages, whether to provide personalization, store information about a user or to track
usage for reporting purposes.
HTTP (Hyper Text Transfer Protocol) is a stateless protocol. When the client disconnects from
the server, the ASP.Net engine discards the page objects. This way each web application can
scale up to serve numerous requests simultaneously without running out of server memory.
However, there need to be some technique to store the information between requests and to
retrieve it when required. This information i.e., the current value of all the controls and variables
for the current user in the current session is called the State.
16
Types of State Management
1. Client – Side State Management
Client Side State Management involves storing information either on a Web page or on a Client
computer. There are four ways to manage states.
View State
Hidden Form Fields
Cookies
Query String
View State
In this method, the ViewState property that is inherited from the base Control class is used to
automatically save the values of the page and of each control prior to rendering of the page.
ViewState is implemented with a hidden form field called the _VIEWSTATE, which is
automatically created in every Web Form page. When ASP.Net executes a Web page on a Web
Server, the values stored in the ViewState property of the page and controls on it are collected
and formatted into a single encoded string. The encoded string is then assigned to the Value
attribute of the hidden form field _VIEWSTATE and is sent to the client as a part of the Web
page.
Query String
The Query string is a part of the request that appears after the Question mark (?) character in the
URL. A query string provides a simple way to pass information from one page to another.
17
Cookies
A cookie, also known as an HTTP cookie, web cookie, or browser cookie, is usually a small piece
of data sent from a website and stored in a user's web browser while a user is browsing a
website. When the user browses the same website in the future, the data stored in the cookie can
[1]
be retrieved by the website to notify the website of the user's previous activity. Cookies were
designed to be a reliable mechanism for websites to remember the state of the website or activity
the user had taken in the past. This can include clicking particular buttons, logging in, or a record
of which pages were visited by the user even months or years ago.
Application State
An ASP.Net application is the collection of all web pages, code and other files within a single
virtual directory on a web server. When information is stored in application state, it is available to
all the users.
To provide for the use of application state, ASP.Net creates an application state object for each
application from the HTTPApplicationState class and stores this object in server memory. This
object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global application
data like tax rate, discount rate etc and to keep track of users visiting the site.
Application state data is generally maintained by writing handlers for the events:
Application_Start
Application_End
Application_Error
Session_Start
Session_End
Session State:
When a user connects to an ASP.Net website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session state
object becomes part of the context and it is available through the page.
18
Session state is generally used for storing application data like inventory or supplier list, or a
customer record or shopping cart. It can also keep information about the user and his preference
and keep track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to
server and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of
session state items.
A Default.aspx is added in your solution and it is traditional ASP.NET page which is inherited from
System.Web.UI.Page. But you need to create page which inherit from MobilePage class in
System.Web.UI.MobileControls namespace. In this demonstration, you will use controls from
the System.Web.Mobile namespace that are specifically designed for devices that cannot
display as much information as a desktop browser.
19
Test Application
Select Microsoft Mobile Explorer and press F5 to run the application. Microsoft Mobile
Explorer Emulator will appear. Click ASP.NET Development Server icon in the system tray to get
application URL name
and its port. It may be different in your system.
In the Microsoft Mobile Explorer Emulator type URL as http://localhost:1439/LRC/Loan_
20
RepaymentCalculator.aspx
Enter Amount, Term & Rate. Click on Repayment button in the screen. You will get result like
bellow,
21
22