Advanced ASP
Advanced ASP
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.
I M.Sc.(CS)
Distributed Technologies
Unit IV
Advanced Features of ASP.NET
ASP.Net is an exciting server side technology used for developing web based applications
It uses the namespaces, classes and methods provided by the .NET Framework
o MasterPage
o Data Control
o Navigation Control
Master Page:
o is use to define common structure and interface elements for any website
Data Control
o Data access can possible by using the new data-bound and data source controls
o New data source controls to represent different data backend, such as SQL, business
objects, and XML
o New data-bound controls for rendering common UI for data, such as grids, details, and
formview
o Theme to control the appearance of both the HTML elements and ASP.NET controls
that appear in a page
o A Theme folder can contain a variety of different types of files, including images and
text files
o Also can organize the contents of a Theme folder by adding multiple subfolders to a
Theme folder
▪ A Skin enable to modify any of the proprieties of an ASP.net control that have
an effect on its appearance
Navigation control:
▪ Treeview
▪ Menus
▪ SiteMapPath
▪ Login security
▪ Wizard navigation
▪ Image generation
▪ Menus
▪ Tree views
▪ Portals
▪ And more
Security in ASP.NET
The authentication and authorization of users and resistance against the malicious attacks are
important tasks in web applications
ASP.NET 2.0 introduced a new membership and role management service that provides both
authentication and authorization services and management of users who access our application
without building any tables or writing any code
➢ Security Model
o Membership Provider
o Role Provider
➢ Membership Provider:
The extensible Membership provider framework can register and authenticate new users
o SqlMembership Provider:
▪ can also create custom Membership provider using any OLEDB DataSource or
XML DataSource
o AccessMembership Provider:
➢ Role Provider:
Role Provider are used to manage user roles like creating new roles for users
o ApplicationName:
o ConnectionStringName:
o Description:
o EnablePasswordReset:
▪ When true, users can reset their password to a randomly generated password
o EnablePasswordRetrieval:
▪ When true, user passwords can be retrieved from the Membership provider
o PasswordFormat:
• Clear
• Encrypted
• Hashed
▪ When passwords are hashed, the original passwords cannot be retrieved from the
Membership provider
o RequiresQuestionAndAnswer:
▪ When true, the user must answer a password retrieval question before the user
password can be reset or retrieved
o RequiresUniqueEmail:
▪ When true, a unique e-mail address must be associated with each user
3. Explain in detail the Different Login and Password Server Controls:
o Login
o LoginStatus
o LoginName
o ChangePassword
o PasswordRecovery
o LoginView
o CreateUserWizard
The Login server control display standard login interface for user authentication
The login control can be used as a standalone control on a main and home page or can use it
on a dedicated login page
Password
▪ FailureText: used to control the content and appearance of the text that is
displayed when a login attempt fails
This control enables user to click a link to Login or Logout of web application
Source code:
<form id="form1" runat="server">
<asp:LoginStatus ID="LoginStatus1" runat="server" />
</form>
Source code:
<form id="form1" runat="server">
<asp:LoginName ID="LoginName1" runat="server" />
</form>
This control displays textboxes for entering the original password and entering a new
password
New Password
The Confirm New Password must match the New Password entry
Source code:
<form id="form1" runat="server">
<asp:ChangePassword ID="ChangePassword1" runat="server">
</asp:ChangePassword>
</form>
Submit
Source code:
<form id="form1" runat="server">
<asp:PasswordRecovery ID="PasswordRecovery1" runat="server">
</asp:PasswordRecovery>
</form>
Can be used to display different content depending on the role of the current user
Source code:
<form id="form1" runat="server">
<asp:LoginView ID="LoginView1" runat="server">
</asp:LoginView>
</form>
Used to allow users to create a new user entry in the membership system
Password
Confirm Password
E-mail
Security Question
Security Answer
Create User
Source code:
Source Code:
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default"
%>
<!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">
<asp:Login ID="Login1" runat="server" Height="239px" Width="595px">
</asp:Login>
</form>
</body>
</html>
View Code:
Imports System.Data
Imports System.Data.SqlClient
Partial Class _Default
Inherits System.Web.UI.Page
Dim con As New SqlConnection
Dim ad As New SqlDataAdapter
Dim ds As New DataSet
Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As
System.Web.UI.WebControls.AuthenticateEventArgs) Handles Login1.Authenticate
con = New SqlConnection
con.ConnectionString = "Datasource"
con.Open()
ad = New SqlDataAdapter("select * from test Name='" & Login1.UserName & "' and No=" &
Login1.Password, con)
ds = New DataSet
ad.Fill(ds)
If ds.Tables(0).Rows.Count > 0 Then
Response.Write("You are authenticate user")
Else
Response.Write("Incorrect user")
End If
End Sub
End Class
State Management in ASP.NET
Statement is the process by which we maintain state and page information over multiple
requests for the same or different pages
This stores information on the client’s computer by embedding the information into a web
page, a Uniform Resource Locator (URL) or a cookie
This techniques available to store the state information at the client end are listed below:
a. View State
b. Control State
c. Hidden Fields
d. Cookies
e. Query Strings
a. View State
▪ This property provides dictionary object for retaining values between multiple
request for the same page
▪ When the page is processed, the current state of the page and controls is hashed
into a string and saved in the page as a hidden field
▪ It is used by the Asp.net page framework to automatically save the values of the
page and of each control just prior to rendering to the page
▪ We can store values in view state as well. The following example shows how
to store a value in the view state
ViewState(“color”)=”red”
b. Control State
▪ To store control-state data in order for a control to work properly the control
state is used
c. Hidden Fields
▪ Hidden fields store data in an HTML form without displaying it in the user’s
browser
d. Cookies
▪ A cookie is a small amount of data that is store a value in the user’s browser
that the browser sends with every page request to the same server
▪ The most common use of cookies is to identify a single user as he or she visits
multiple web pages
e. Query Strings
http://www.contoso.com/listwidgets.aspx?category=basic&price=100
a. Application State
▪ Is used to store and retrieve information that can be shared among all user of an
application
b. Session State
▪ Used to store and retrieve information about particular sessions
▪ Both Application state and Session state information is lost when the application restart
c. Profile Properties
▪ Profile.postalcode=textbox1.text
ASP.NET provides a mobile component which allows we to build applications for mobile
devices to access web pages
Mobile ASP.Net pages are based on the MobilePage class which exists in
System.Web.UI.MobileControls namespace
Uses on a mobile ASP.NET page come from their own namespace, we need to include that
namespace on each of our mobile ASP.Net pages
Example :
2. On the File Menu, choose New, and then choose Web Site. The New Web Site dialog box
appears
6. Language Visual C#
7. Click OK button
3. Right-click the application in Solution Explorer and choose Add New Item
5. Name Calculator.aspx
Mobile Controls
1. Label Control
2. Link Control
Provides, to allow the visitors to navigate to another page or another form within the
current page
<mobile:Form id=”Form1” runat=”server” >
<mobile:Label id=”Label1” runat=”server” Text=”Link Test Page”/>
<mobile:Link id=”Link1” runat=”server” Text=”click here!”
NavigateUrl=”http://www.google.com” />
<mobile:Link id=”Link2” runat=”server” Text=”or here!”
NavigateUrl=”http://www.gmail.com” Alignment=”Right”/>
</mobile:Form>
3. Call Control
Use the Call Control to make it easier for the visitor to call the contact
That supports dialing phone numbers. If the visitor were to click the call control, they
would e asked to confirm that they wanted to make the call
4. Image Control
Web Services
What is Web Services
A
s
w
e
c
an see in the figure, Java, .net, and PHP applications can communicate with other applications
through web service over the network.
For example, the Java application can interact with Java, .Net, and PHP applications. So web
service is a language independent way of communication.
1. SOAP
2. WSDL
3. UDDI
SOAP
WSDL
UDDI
➢ UDDI is an acronym for Universal Description, Discovery and Integration is specification for a
registry of information for web services
➢ UDDI is a XML based framework for describing, discovering and integrating web services.
➢ UDDI is a directory of web service interfaces described by WSDL, containing information about
web services.
We can now use ASP.NET to create Web Services based on industrial standards including
XML, SOAP, and WSDL.
A Web Service is a software program that uses XML to exchange information with other
software via common internet protocols. In a simple sense, Web Services are a way of
interacting with objects over the Internet.
➢ A web service is
• Language Independent.
• Protocol Independent.
• Platform Independent.
• It assumes a stateless service architecture.
• Scalable (e.g. multiplying two numbers together to an entire customer-relationship management
system).
• Programmable (encapsulates a task).
• Based on XML (open, text-based standard).
• Self-describing (metadata for access and use).
• Discoverable (search and locate in registries)- ability of applications and developers to search for
and locate desired Web services through registries. This is based on UDDI.
• Microsoft coined the term "Web services" in June 2000, when the company introduced Web
services as a key component of its .Net initiative, a broad new vision for embracing the Internet in
the development, engineering and use of software.
• As others began to investigate Web services, it became clear that the technology could
revolutionize (be the next stage in) distributed computing.
• Web services encom a set of related standards that can enable any two computers to communicate
and exchange data via a network, such as the Internet.
• The primary standard used in Web services is the Extensible Markup Language (XML) developed
by the World Wide Web Consortium (W3C).
• Developers use XML tags to describe individual pieces of data, forming XML documents, which
are text-based and can be processed on any platform.
• XML provides the foundation for many core Web services standards (SOAP, WSDL, and UDDI)
and vocabularies (XML-based markup for a specific industry or purpose).
• Almost every type of business can benefit from Web services such as expediting software
development, integrating applications and databases, and automating transactions with suppliers,
partners, and clients.
• XML- Describes only data. So, any application that understands XML-regardless of the
application's programming language or platform has the ability to format XML in a variety of
ways (well-formed or valid).
• SOAP- Provides a communication mechanism between services and applications.
• WSDL- Offers a uniform method of describing web services to other programs.
• UDDI- Enables the creation of searchable Web services registries.
When these technologies are deployed together, they allow developers to package applications as services
and publish those services on a network.
• Use open, text-based standards, which enable components written in various languages and for
different platforms to communicate.
• Promote a modular approach to programming, so multiple organizations can communicate with
the same Web service.
• Comparatively easy and inexpensive to implement, because they employ an existing infrastructure
and because most applications can be repackaged as Web services.
• Significantly reduce the costs of enterprise application (EAI) integration and B2B
communications.
• Implemented incrementally, rather than all at once which lessens the cost and reduces the
organizational disruption from an abrupt switch in technologies.
• The Web Services Interoperability Organization (WS-I) consisting of over 100 vendors promotes
interoperability.
➢ SOAP : -
Simple Object Access Protocol(SOAP) is a protocol that is used to exchange structured
information at the time of implementing a web service.
SOAP is relied on XML. Message format of SOAP usually relies on another protocol of
different application layers.
Among these the most notable application layer is Remote Procedure Call(RPC) and HTTP.
SOAP forms the foundation layer for web services protocol stack.
This stack provides the basic framework for messaging on which the web services are built.
➢ WSDL :
Web Service Definition Language(WSDL) is used to describe a web service based on XML
WSDL is used for describing web services and to locate the services. WSDL consists of the
information on what the service is all about, its residing location and the way of invocation the
service.
➢ UDDI :
Universal Discovery Description Integration(UDDI) is used to publish and discover the
information about the web services,
UDDI is a specification. It is an XML based standard.
This standard is used for describing, publishing, and finding the services.
These services are found in a distributed environment through the use of a server called registry
server.
Connecting a Web Services to Database in ASP.NET
a simple Web Method will be created in Web Service to fetch data from database and the fetched
data will be displayed in GridView.
➢ Database
We have made use of the following table Customers with the schema as follows.
2. Once the Web Service is added. You will need to add the following namespaces.
C#
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
VB.Net
Imports System.Data
Imports System.Configuration
Imports System.Data.SqlClient
3. Third step is to add the WebMethod for getting data from database.
C#
[WebMethod]
public DataTable Get()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "Customers";
sda.Fill(dt);
return dt;
}
}
}
}
}
VB.Net
<WebMethod()> _
Public Function Get() As DataTable
Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
Using con As New SqlConnection(constr)
Using cmd As New SqlCommand("SELECT * FROM Customers")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
dt.TableName = "Customers"
sda.Fill(dt)
Return dt
End Using
End Using
End Using
End Using
End Function
4. Finally you will need to add the Web Reference of the Web Service we just created to the project as
shown below.
HTML Markup
The HTML Markup consists of an ASP.Net GridView which will be populated using Web Service.
The GridView is populated from the database inside the Page Load event of the page.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
this.BindGrid();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Me.BindGrid()
End If
End Sub
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data
Imports System.Data.SqlClient
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function find(ByVal n1 As String) As String
Dim con As New SqlConnection
Dim ad As New SqlDataAdapter
Dim ds As New DataSet
Dim ret As String
Return ret
End Function
End Class
Design Page (default.aspx)
Output:
Accessing a Web Service through an ASP.Net Application
Web services use XML to code and decode your data and SOAP to transport
it using open protocols.
With Web services, your accounting departments Win 2K servers' billing system
can connect with your IT suppliers UNIX server.
1. To create a new Web Site project, choose New from File menu, then choose
Web Site as shown below:
2. C
hoose ASP.NET Web Site. Name the project and click OK:
After creating the Web Site project, it’s time to add a Web reference for our Web service.
1. In the solution explorer, right click the project node, choose Add Web Reference:
After clicking the Go button, you will see the Web services APIs.
3. Set a name for your Web service reference in the Web reference name
field and click Add Reference:
Third Step: Call the Web Services APIs Inside the Code
After successfully adding to the Web service, now we are ready to call the Web
services APIs inside our project.
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Service
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function sum(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Return n1 + n2
End Function
Public Function sub1(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Return n1 - n2
End Function
Public Function mul1(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Return n1 * n2
End Function
Public Function div1(ByVal n1 As Integer, ByVal n2 As Integer) As Integer
Return n1 / n2
End Function
End Class