4.5 in Simple Steps - Nodrm
4.5 in Simple Steps - Nodrm
Authored by:
Published by:
©Copyright by 2013 Dreamtech Press, 19-A, Ansari Road, Daryaganj, New Delhi-110002
This book may not be duplicated in any way without the express written consent of the publisher, except in the
form of brief excerpts or quotations for the purposes of review. The information contained herein is for the
personal use of the reader and may not be incorporated in any commercial programs, other books, databases,
or any kind of software without written consent of the publisher. Making copies of this book or any portion for
any purpose other than your own is a violation of copyright laws.
Limits of Liability/disclaimer of Warranty: The author and publisher have used their best efforts in preparing
this book. The author make no representation or warranties with respect to the accuracy or completeness of
the contents of this book, and specifically disclaim any implied warranties of merchantability or fitness of any
particular purpose. There are no warranties which extend beyond the descriptions contained in this paragraph.
No warranty may be created or extended by sales representatives or written sales materials. The accuracy and
completeness of the information provided herein and the opinions stated herein are not guaranteed or
warranted to produce any particulars results, and the advice and strategies contained herein may not be
suitable for every individual. Neither Dreamtech Press nor author shall be liable for any loss of profit or any
other commercial damages, including but not limited to special, incidental, consequential, or other damages.
Trademarks: All brand names and product names used in this book are trademarks, registered trademarks, or
trade names of their respective holders. Dreamtech Press is not associated with any product or vendor
mentioned in this book.
ISBN: 978-93-5004-999-0
Edition: 2013
CONTENTS
Chapter 1 Introducing Visual Studio 2012 1
Understanding .NET Framework.........................................................................................................2
Need for .NET Framework ...........................................................................................................2
Components of .NET Framework ................................................................................................. 3
Versions of .NET Framework ........................................................................................................6
Getting Started with Visual Studio 2012 ............................................................................................. 6
Editions of Visual Studio 2012 .....................................................................................................7
Installing IIS 7.5 ..................................................................................................................................8
Installing Visual Studio 2012........................................................................................................9
Opening Visual Studio 2012 ......................................................................................................13
Visual Studio 2012 Integrated Development Environment ...............................................................14
The Start Page ............................................................................................................................15
The Toolbars ..............................................................................................................................16
The Toolbox ...............................................................................................................................16
The Server Explorer Window .....................................................................................................17
The Solution Explorer Window ..................................................................................................18
The Class View Window ............................................................................................................18
The Properties Window .............................................................................................................19
The Document Outline Window ...............................................................................................20
The Object Browser Window ....................................................................................................20
The Code Editor .........................................................................................................................21
The Design View ........................................................................................................................22
The Source View ........................................................................................................................23
The Output Window ..................................................................................................................24
The Error List Window ...............................................................................................................24
IntelliSense .................................................................................................................................25
New Features in Visual Studio 2012 IDE ..........................................................................................26
Projects and Solutions ................................................................................................................26
Window Management ...............................................................................................................27
Search ........................................................................................................................................29
Find Strings by Using Regular Expression Syntax from the .NET Framework ................................30
Code Editing for C++ .................................................................................................................31
Multibrowser Support.................................................................................................................31
Page Inspector ............................................................................................................................31
HTML Editor ...............................................................................................................................32
CSS Editor...................................................................................................................................35
Examples in Tooltips ..................................................................................................................39
JavaScript Editor .........................................................................................................................39
Visual C# 2012 .................................................................................................................................40
New Features in Visual C# 2012................................................................................................40
The Visual C# 2012 Keywords ...................................................................................................41
Visual C# 2012 Statements ........................................................................................................42
The Using Statement .........................................................................................................................44
Declaring Constants ...................................................................................................................44
Declaring Variables....................................................................................................................45
Introducing Data Types ..............................................................................................................47
Converting Data Types ...............................................................................................................48
The Arithmetic Operators ...........................................................................................................49
String Concatenation ..................................................................................................................51
ASP.NET 4.5 in Simple Steps
iv
Contents
v
ASP.NET 4.5 in Simple Steps
vi
Contents
vii
ASP.NET 4.5 in Simple Steps
viii
CHAPTER 1
Introducing Visual Studio 2012
Introduction
The .NET Framework is one of the most widely used software development environments in today’s
programming world. Before the introduction of .NET Framework, programmers had to face a lot of
difficulties to integrate the code written using different programming languages because each language
used a different execution environment to execute the code written in that language. For example, a
code written using Visual Basic 6.0 requires an execution environment different from that required by a
code written using C++ language. The .NET Framework, offered by Microsoft, has provided
programmers a single platform for developing applications using different programming languages,
such as Visual Basic, Visual C#, and Visual C++. The .NET Framework reduces the difficulty involved in
building large, reliable applications.
To leverage the features and services offered by .NET Framework, Microsoft has introduced a
development and execution software called Visual Studio (VS), which is an Integrated Development
Environment (IDE) designed to help application developers for building simple and complex applications
and creating innovative solutions. VS provides the necessary environment in which developers can
create and execute various types of applications, including Console applications, Windows Forms
applications, Windows Presentation Foundation (WPF) applications, Windows Communication
Foundation (WCF), Web applications, and Web services. It has also improved and made the process of
development easier. The latest version of VS is more powerful as compared to the previous versions of
VS, as it contains lots of features and enhancements. The latest versions of .NET Framework and VS
were released in 2012 as .NET Framework 4.5 and VS 2012, respectively.
ASP.NET 4.5 in Simple Steps
VS 2012 helps in minimizing the application development time, simplifies the process of testing
applications, provides different toolsets for integrating graphic designers into the overall development
process, supports multiple versions of the .NET Framework, enhances data retrieval and data binding,
helps in finding sections of code that need refactoring, provides support for Web, Mobile, Windows, and
Office application development, and integrates with the .NET Framework 4.5.
In this chapter, you will learn about Microsoft VS 2012, how to install VS 2012, and how to work with it.
You will also learn about IDE of VS 2012 and the new features introduced in this edition. In addition,
you will also learn about Visual C# 2012 which helps in developing ASP.NET applications. .
Fig.ASP- 1.1
2
Introducing Visual Studio 2012
Language Independence:: Provides multiple language support by using the feature known as
Common Type Syste em (CTS) that is built into Common Language Runtime (CLR). The CTS
supports a variety of types and operations found in most programming languages; and
therefore, calling one language from another does not require type conversions. Although C# is
especially designed for the .NET platform, you can build .NET applications in a number of other
languages, including C++ and Visual Basic.
Base Class Library (BCL):: Provides the basic features for the development of an application, such
as ASP.NET application, a Windows Forms application, or a Web Service. The BCL acts as the
important point of interaction with the CLR.
Easy Deployment: Makes the deployment process easier. In most cases, to install an application,
you need to copy the application along with its components on the target computer. The .NET
Framework facilitates easy deployment of applications by installing new applications or
components that do not have an adverse effect on the existing applications. Applications are
deployed in the form of assemblies in .NET. Therefore, registry entries are not required to store
information about components and applications. In addition, assemblies also store information
about different versions of a single component used by an application. Therefore, version
problem is also eliminated in .NET Framework.
Security:: Provides security models that allow you to authenticate users appropriately and obtain
the correct security context within applications. Now, let’s discuss the .NET Framework
architecture to understand ASP.NET T in more detail.
3
ASP.NET 4.5 in Simple Steps
The .N
NET CLR solves this problem by providing a single runtime environment for multiple languages.
The CLR manages the code at the execution time. Code management is considered as the basic
principle of the CLR as it is a process in which the execution of a program is managed and controlled by
the CLLR. The code that is executed by the CLR environment, instead of being executed by the operating
system, is called managed code e, and the code that is executed directly by the operating system and not
by the CLR is called unmanaged cod de. CLR also handles runtime services, including language
integratio
on, securitty, and memory managemen nt. During development, the CLR provides features that
are needed to simplify the process. Fig.ASP-1.2 shows a diagrammatic summary of the major
components of the CLR:
Fig.ASP- 1.2
4
Introducing Visual Studio 2012
Fig.ASP- 1.3
Assemblies
Every software application has an executable (.exe) file. Apart from the .exe file, there are some
Dynamic Link Librarie es (DLL) and Librarry (LIB) files that contain the compiled code of some commonly
used functions. These files are packaged and shipped along with the software application, since these
are necessary to run the application. In terms of .N NET runtime, the process of packaging is called
assemblinng. An assembly is a partially compiled code file that is used for deployment of a .NET
application. An assembly contains MSIIL, metadatta, and other files, which are required to execute a .N
NE T
program successfully.
Assembliees play an important role in .N NET Framework. An a ssemblly is a fundamental unit of
deploymen nt, which is the process wherein you can install an application on a computer. Assemblie es can
be created with the help of some development tools.. Yo ou can make assemblie es in the form of .dll or
.exe files by using VS 201 12. Whenever you compile your source code, the EXE/DLL file, which is
generated after compilation, is actually an assembly.
Metadata
The metadata contains information about the assembly. The assembly uses metadata to describe itself.
To ensure that the correct method is called, the CLR also checks the metadata. The language compilers
generate the metadata, but you can create your own metadata by using custom attributes.
Just-In-Time Compiler
The Just-In-Time (JIT) compiler compiles the MSIL code into executable code (.exe ). The executable code
is specific to the computer and the operating system in which the compilation takes place. The JIT
compilation takes place whenever the CLR invokes the JIT compiler for compilation of MSIL files.
5
ASP.NET 4.5 in Simple Steps
System Requirements
Various hardware and software requirements are required to install VS 2012.
Table 1.1 lists the minimum system requirements that your computer should meet to install VS 2012:
Table 1.1: System Requirements for Installing VS 2012
Hardware and Software Requirements
Processor Minimum: 1.6 GHz Pentium processor
Supported architecture ×86 and ×64 Windows on Windows (WOW) mode
Operating System Windows 7 SP1 (×86 and ×64)
Windows 8 (×86 and ×64)
Windows Server 2008 R2 SP1 (×64)
Windows Server 2012 (×64)
6
Introducing Visual Studio 2012
7
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.4
Fig.ASP- 1.5
The Program
ms window appears (Fig.ASP- 1.6).
3. Click the Turn Windows Features on or offf option on the right pane of the Program
ms window, as
shown in Fig.ASP- 1.6:
8
Introducing Visual Studio 2012
Fig.ASP- 1.6
Fig.ASP- 1.7
A Microsoft Windowws message box appears that shows the progress of turning on the feature of IIS, as
shown in Fig.ASP- 1.8:
Fig.ASP- 1.8
It remains for few minutes till the turn-on of the feature completes. After the successful completion of
installing IIS 7.5, let’s now learn to install VS 2012.
9
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.9
The Microsoft Visual Studio 2012 Ultimate edition logo appears, as shown in Fig.ASP- 1.10:
Fig.ASP- 1.10
After sometime, the Microsoft Visual Studio 2012 Ultimatte wizard appears.
3. Select the I agree to the License terms and condition
ns check box (Fig.ASP- 1.11).
4. Click the Nexxt button, as shown in Fig.ASP- 1.11:
Fig.ASP- 1.11
10
Introducing Visual Studio 2012
The next screen appears in the wizard that prompts you to select the features that you want to
install (Fig.ASP- 1.12).
5. Select the Select Alll check box if you want to install all the features of Visual Studio 201
12
(Fig.ASP- 1.12).
6. Click the INSTALLL button, as shown in Fig.ASP- 1.12:
Fig.ASP- 1.12
The installation process of Visual Studio 2012 Ultimatte starts. The progress bar displays the
progress of the installation process (Fig.ASP- 1.13).6
Fig.ASP- 1.13
11
ASP.NET 4.5 in Simple Steps
After the successful installation of the components of Visual Studio 201 12, a new screen in the
wizard appears that prompts you to restart the system for completing the installation of Visual
Studio 20112 (Fig.ASP- 1.14).
7. Click the Restart No
ow button to restart the system, as shown in Fig.ASP- 1.14:
Fig.ASP- 1.14
When your computer restarts, again the installation of the components of Visual Studio Ultimate
201
12 starts, as shown in Fig.ASP- 1.15:
Fig.ASP- 1.15
After the successful installation of all the components, the Setup Successfu
ul message appears on
the screen (Fig.ASP- 1.16).
12
Introducing Visual Studio 2012
Fig.ASP- 1.16
Fig.ASP- 1.17
13
ASP.NET 4.5 in Simple Steps
When you open the VS 2012 for the first time, the Choose Default Environment Setting
gs dialog
box that prompts you to configure the IDE appears (Fig.ASP- 1.18).
2. Select the General Development Settings option from the Choose your default environment
settings list box (Fig.ASP- 1.18).
3. Click the Start Visual Studiio button, as shown in Fig.ASP- 1.18:
Fig.ASP- 1.18
The Microsoft Visual Studiio message box appears on the screen that indicates the time taken to
load the user settings for the first time, as shown in Fig.ASP- 1.19:
Fig.ASP- 1.19
14
Introducing Visual Studio 2012
The Toolbox
The Server Explorer Window
The Solution Explorer Window
The Class View Window
The Properties Window
The Document Outline Window
The Object Browser Window
The Code Editor
The Design view
The Source view
The Output Window
The Error List Window
IntelliSense
Let’s now discuss each of them in detail.
Fig.ASP- 1.20
15
ASP.NET 4.5 in Simple Steps
Get Started:: Contains links to various programming tasks in the product’s documentation.
How to Videos (Streaming):: Contains videos related to Visual Studio 2012.
Latest News:: Contains links to interesting news and announcements.
The Toolbars
The Toolbarrs in the Visual Studio 2012 ID
DE provides developers with an easy access to the features of
the IDE. The .NET IDE provides different toolbars for each category of tasks that are needed in the
process of developing an application. The Standard Toolbaar is the default visible toolbar, as shown in
Fig.ASP- 1.21:
Fig.ASP- 1.21
The other toolbars are enabled for developers to view by using the Customize
e option of the toolbar.
Users can customize this toolbar by adding or removing buttons from it. The buttons on this toolbar
represent the following tasks:
Navigate Backward
d: Navigates to the previously visited location within the application.
Navigate Forward d: Navigates to the subsequently visited location within the application.
New Projectt: Creates a new project or a new Web site.
Ad
dd New Ite
em: Adds new items, such as Web Form and Style sheet in the Web application.
Open File:: Opens a Web project, Windows project, or any other .NET project in the IDE.
Save
e: Saves the form that is currently designed.
Save Alll: Saves all the changes made to a project.
Cutt: Cuts the objects or items, such as code and controls.
Copyy: Copies the objects or items.
Pastee: Pastes the cut or copied items.
Undo o: Reverts the changes made in an application.
Redo
o: Reset the changes made in an application.
Start Debugging
g: Debugs the code.
Solution Configuration
n: Specifies the configuration of a project.
Find in File
es: Finds keywords in the project.
The Toolbox
The Toolbo ox contains a number of tabs; each tab contains a list of controls and components that can be
dragged onto your Web Form. The Toolbox is docked on the left-hand side of the IDE; however, if it is
not visible, you can access the Toolbox from the View menu or press the CTRL+ALT+ +X keys together to
open it.
There are different sets of controls available in the Toolbox, depending on the type of application that is
active in the Visual Studio 2012 IDE. If you are designing a Web Form in a Web application, you will get a
specific set of controls, and if you are designing a Windows form in a Windows application, you will get a
16
Introducing Visual Studio 2012
specific set of controls. Moreover, there will be some other controls available within the Toolbox. You can
also add other customized tabs to the Toolbox; wherein you can place your favourite controls and
components or add your own customized controls. You can view the Toolbox, as shown in Fig.ASP- 1.22:
Fig.ASP- 1.22
Visual Studio 2012 has introduced the Searcch Toolbo ox feature to search a particular control in the
Toolbboox. It has also the pin icon on the Titlle bar to auto hide or pin down the window.
Fig.ASP- 1.23
17
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.24
Object Pane
Member
Pane
Fig.ASP- 1.25
18
Introducing Visual Studio 2012
You can use the Class View window to open files and navigate directly to the lines of code where the
symbols appear. Selecting an object in the Objects pane displays its member in the Members pane. The
Class View toolbar allows you to create a virtual folder and navigate within the Objects and the
Members panes. The various buttons available in the Class View toolbar are described as follows:
New folder:: Creates a new folder or subfolder into which you can drag symbols for easy access.
Back:: Navigates to the previously selected items until you reach the first item.
Forward:: Navigates to the next item selected until you reach the most recent item selected.
Class View Settings:: Helps assign different settings. The various commands available in Class
View Settings are as follows:
Show Base Types:: Displays the base types in the Objects pane.
Show Project References:: Displays a virtual folder that displays objects placed in the project
references.
Show Hidden Types and Members:: Displays hidden types in the Objects pane and hidden
members in the Members pane.
Show Public Members:: Displays public members for users who are using the classes.
Show Protected Members:: Displays the protected members for the users who are extending
the classes.
Show Private Members:: Displays the private members of all accessibility levels for users who
are implementing and using the classes.
Show Other Members:: Displays members that do not fall in the categories of public, private,
protected, or inherited.
Show Inherited Members:: Displays inherited members in the Members pane.
View Class diagram:: Displays the class details of the currently selected object. When you select
an object in the Objects pane, you can get the class diagram by clicking this button in the
toolbar.
Fig.ASP- 1.26
19
ASP.NET 4.5 in Simple Steps
The Propertie
es window can be viewed by performing either of the following:
Selecting VIEWProperties Windowss from the menu bar.
Pressing the F4 key.
The properties of Windows Forms or Web Forms and the controls on the forms can be set interactively at
the application design time by using this window. The buttons on the toolbar of the Propertie es window
allow sorting of properties in alphabetical order or category wise navigation of properties and events.
The properties of a control are grouped under the following main categories:
Accessibilitty: Contains properties of a control, such as AccessKey and TabIndex.
Appearancce: Contains properties that control the appearance of a control on a Web page.
Behavio
or: Contains properties that decide the behaviour of a control on the Web page.
Datta: Contains expressions that can be bound to serve er control.
Layouut: Contains properties that are used to set Height and Width of a control.
Missc: Contains programmatic name of the control.
Fig.ASP- 1.27
The Document Outlinne window can be viewed by performing either of the following:
Selecting VIEWOther WindowsDocument Outline from the menu bar.
Pressing the key combination Ctrl+Alt+
+T.
The Document Outlin ne window incorporates the drag-and-drop feature for allowing controls to be
represented to other containers.
20
Introducing Visual Studio 2012
Fig.ASP- 1.28
21
ASP.NET 4.5 in Simple Steps
The Code editoor enables writing of syntactically correct code so that only logical errors can be filtered
out, as shown in Fig.ASP- 1.29:
Fig.ASP- 1.29
Fig.ASP- 1.30
In the Designn view, you can perfectly align the Web controls on a Web Form and set the graphical
properties of these controls. As a result, you can customize the overall appearance of the Web Form.
22
Introducing Visual Studio 2012
Moreover, you can also edit the Web controls in the Design
n view,, which are not visible while the Web
Form executes in the browser.
In the Designn view, you can produce the visual effects and set different appearances for the controls.
The Design n view offers a lot of customization and formatting features for the Web Forms, some of which
are as follows:
You can directly write text on the Web Form.
You can customize the layout of the Web Forms as absolute and relative using position option in
the Format menu.
You can apply various font styles, foreground, and background colours on the Web Form and
the controls contained in it.
In the Designn view, you can immediately see the result of setting most of the properties for the Web
Forms or its controls that are set through the Properties window.
23
ASP.NET 4.5 in Simple Steps
left: 89px; position: absolute; top: 234px" ForeColor="Red" ToolTip=
"Click me" />
<asp:Label ID="Label1" runat="server" Text="Label" style="z-index:
101; left: 101px; position: absolute; top: 171px" BackColor="Blue"
BorderColor="#00C000" BorderStyle="Double"
ForeColor="Lime"></asp:Label>
Fig.ASP- 1.31
Fig.ASP- 1.32
24
Introducing Visual Studio 2012
Fig.ASP- 1.33
IntelliSense
Visual Studio 2012 IDE Code Edito or supports the feature of IntelliSensse, which helps you to write
accurate code. As you start typing the code, the methods, properties, and events of the .NET Framework
Class Library are automatically offered as a sorted list with the help of IntelliSensse feature. This list,
which automatically opens in an IntelliSensse, shows all the members that are valid for using the code.
When the Web developer selects an option from the IntelliSensse, it is included in the line of code with
accurate spelling and case. While writing the code, if there is any error in the code, the IntelliSense
underlines the code or the keyword that signifies an error. Fig.ASP- 1.34 shows the IntelliSensse:
Fig.ASP- 1.34
25
ASP.NET 4.5 in Simple Steps
The preceding figure shows an IntelliSensse, which has appeared automatically. From the list of items
displayed by the IntelliSensse, a developer can choose the next desired item. The IntelliSensse has the
scroll bar to navigate through all the items that appear in an alphabetically sorted order.
Now, let’s learn about the new features introduced in Visual Studio 2012 IDE.
26
Introducing Visual Studio 2012
In addition, import element should also be changed so that the compatibility of various versions of
Visual Studio is maintained. Note that if a project is shared between Visual Studio 2010 and Visual
Studio 2012 in two different computers and uses local database in the App_Data folder, then the same
version of SQL Server must be installed in both the computers.
Fig.ASP- 1.35
Fig.ASP- 1.36
Window Management
The improvements and enhancements made in Window management in Visual Studio 2012 are as
discussed in the following.
27
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.37
Fig.ASP- 1.38
28
Introducing Visual Studio 2012
Fig.ASP- 1.39
Fig.ASP- 1.40
Search
The enhancements and features included in searching feature in the Visual Editor 2012 editor are
discussed in the following.
Quick Launch
You can use the Quick Launch text box for searching across the IDE. This box is enabled by default after
the installation of Visual Studio 2012 and is located at the top-right corner of the menu bar. The
shortcut key for accessing this searching text box is Ctrl+Q. The Quick Launch search box is shown in
Fig.ASP- 1.41:
29
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.41
Fig.ASP- 1.42
Find Strings by Using Regular Expression Syntax from the .NET Framework
You can find strings by using regular expression syntax from the .NET Framework by using Find and
Replace control. There are two rabs in this control that are Find in Files and Replace in Files. The Find in
File
es tab searches the strings in the current document or solution, whereas that searched strings can be
replaced by another string using the Replace in File
es tab as shown in Fig.ASP- 1.43:
Fig.ASP- 1.43
30
Introducing Visual Studio 2012
Multibrowser Support
In Visual Studio 2012 IDE the list of browsers installed in your computer appears in a new drop-down
list next to the Debug drop-down list. Using this feature, you can test a particular Web page,
application, or site in different browsers. By default this browser drop-down list displays the default
browser of your system, as shown in Fig.ASP- 1.44:
Fig.ASP- 1.44
The Browse Witth option available in the drop-down list allows you to test a Web page in several
browsers after selecting them. When you press F5 or CTRL+F5, your application will launch in all of the
browsers that you selected.
Page Inspector
Visual Studio 2012 has introduced the page inspector tool that renders a Web page in the Visual Studio
IDE and allows you to examine the source code and the resulting output simultaneously. Moreover, Page
Inspecto
or is a great tool for debugging. Fig.ASP- 1.45 shows a Page Inspecto
or:
31
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.45
HTML Editor
Visual Studio 2012 introduces some new features in the HTMLL editor that helps in easing the tasks of a
programmer. The following are the new features added in the HTM
ML editor:
Improved IntelliSense
This feature provides IntelliSensse for code nuggets in HTM ML attributes, thereby making the life of
programmers a little bit easier, as they are not required to remember the name of the complex tags and
attributes. Instead, they can just type the first few letters to get the required list of items beginning with
the typed letters. The previous versions of Visual Studio do provide IntelliSensse, but only for the server-
side code nuggets and not for the HTM ML attributes. However, in Visual Studio 2012, IntelliSense is
provided for both server-side code nuggets and HTM ML attributes. Fig.ASP- 1.46 shows the IntelliSense
for the value attribute of the <inputt> element:
Fig.ASP- 1.46
Smart Tasks
This feature adds a small glyph just below a server tag when the insertion point is inside the server
element. The smart tasks menu is displayed when the glyph is clicked or the Ctrl +. key combination is
pressed from the keyboard. The smart tasks feature was already available in the previous versions of
Visual Studio, but can be used through the Desig gn view only. However, in Visual Studio 2012, the smart
tasks feature can also be used though the Source e view. The smart taskks menu associated with the
calendaar tag in the Sourcce view is shown in Fig.ASP- 1.47:
32
Introducing Visual Studio 2012
Fig.ASP- 1.47
Fig.ASP- 1.48:
Fig.ASP- 1.49
Fig.ASP- 1.50
33
ASP.NET 4.5 in Simple Steps
The Save As dialog box appears (Fig.ASP- 1.51). Type the file name in the File nam
me text box; in our
case, we have typed VideoController.asccs, as shown in Fig.ASP- 1.51:
Fig.ASP- 1.51
Now, click the OK button to create the user control. The newly created user control tag replaces the
selected text, as shown in Fig.ASP- 1.52:
Fig.ASP- 1.52
Fig.ASP- 1.53
When you press the enter key, you will get the insertion point indented to its correct position, as shown
in Fig.ASP- 1.54:
Fig.ASP- 1.54
This smart indentation will make the document more readable and aesthetically pleasing.
34
Introducing Visual Studio 2012
Fig.ASP- 1.55
To generate an event handler, you need to select the Create New Even nt option. The event handler is
generated with a correct signature. In addition, the name of the event handler’s method is derived by
using the name of the control’s ID, as shown in Fig.ASP- 1.56:
Fig.ASP- 1.56
Here, the ID is btnSavve and the Clicck is event. By appending the Clicck word to the btnSavve, that is,
btnSave_Clicck, the corresponding event handler method is generated in the .cs file in case of C# and
.vb file in case of Visual Basic. The event handler method in C# is shown in Fig.ASP- 1.57:
Fig.ASP- 1.57
You can also write the customized event in the event handler method.
CSS Editor
Visual Studio 2012 has introduced the CSS editor for dealing with cascading style sheets. The editor
provides the following features:
Fig.ASP- 1.58
35
ASP.NET 4.5 in Simple Steps
Hierarchical Indentation
This feature indents the content of a CSS file in a hierarchical manner to depict the logical organization
of cascading rules. The indentation of a child rule is determined by its parent rules. The advantage of
hierarchical indentation is that it provides a visual representation of the cascading styles that are applied
on a Web page. When you end a child rule with a brace, Visual Basic 201 12 automatically indents the
content according to its parent rules. For example, “#list” is a parent rule and “#list a” is its child rule,
which is indented hierarchically in a .ccss file, as shown in Fig.ASP- 1.59:
Fig.ASP- 1.59
Visual Studio 2012 IDE provides tools to manage the hierarchical indentation. You can open the
Option ns dialog box from TOOLLS Optionss, present in the menu bar of the IDE, to enable or disable
the hierarchical indentation. By default, the hierarchical indentation is enabled, but you can disable it by
deselecting the Hierarchical indentatio
on check box (Fig.ASP- 2.22). The check box can be accessed by
or CSS
selecting the Text Edito Formatting option from the left pane of the Options dialog box, as
shown in Fig.ASP- 1.60:
Fig.ASP- 1.60
Fig.ASP- 1.61
36
Introducing Visual Studio 2012
Moreover, the selector hacks are supported to maintain the hierarchical indentation even if they are
applied. A common way to apply a selector hack is to prepend a selector with *:first-child + htm
ml, which
maintains the hierarchical indentation. The selector hacck is shown in Fig.ASP- 1.62:
Fig.ASP- 1.62
Vendor-specific Schemas
This feature supports the use of browser-specific CSS properties in the IntelliSense. Different browsers
are created by different vendors and have their own vendor specific schemas due to which developers
had to code for specific browsers according to its vendor specific syntax. CSS S3 has resolved this issue by
providing CSS properties that are specific to a browser, such as Mozillla (-moz), Microsofft Interne et
Explore er (-ms), Operra (-o), and Webkiit (-webkit). The browser-specific properties can be displayed in the
IntelliSense by typing hyphen (-) followed by the initial letter of the specific browser, as shown
in Fig.ASP- 1.63:
Fig.ASP- 1.63
Fig.ASP- 1.64
Colour Picker
This feature provides a colour picker when a colour value is entered in the CSS property. The previous
versions of Visual Studio provide IntelliSense for colour values, but were in the form of
drop-down list. Visual Studio 2012 has provided IntelliSense for colour values in the form of a colour
picker, which is displayed automatically, and shows a list of colours that can be selected using a
37
ASP.NET 4.5 in Simple Steps
keyboard or mouse. For the keyboard selection, press the down arrow key to access the colour picker,
the right or left arrow key to navigate the colour picker, and then the Enter key to select the colour value.
A colour picker in its contracted form is shown in Fig.ASP- 1.65:
Fig.ASP- 1.65
Fig.ASP- 1.65 shows the colour picker in the default form. If you have already used some colours, then
the colour picker also displays the previously used colours separated by a bar followed by the default
colour palette. The colour picker also contains a small double-upward-arrow button on the right that
can be expanded to display a complete colour picker. You can also press the downward arrow key twice from
the keyboard to display the expanded form of the colour picker. The expanded form contains an opacity slider, a
colour picker button on the bottom left to select a colour, a strip containing the colours, and new colour viewer. The
opacity slider can be moved to control the alpha channel to automatically convert the selected colour in RGBA, as
shown in Fig.ASP- 1.66:
Fig.ASP- 1.66
Snippets
This feature supports the use of browser-specific CSS properties in the form of snippets. Snippets help a
programmer to create cross-browser styles quickly and easily. Visual Studio 2012 provides CSS snippets
that can be generated through IntelliSensse. You can type the @ symbol to generate the IntelliSensse list,
as shown in Fig.ASP- 1.67:
Fig.ASP- 1.67
38
Introducing Visual Studio 2012
You can select any one option from the IntelliSensse at a time; suppose you have selected the
@keyframe es element and then press the Tab
b key twice to get the corresponding snippet, as shown in
Fig.ASP- 1.68:
Fig.ASP- 1.68
Custom Regions
This feature helps you to group related style blocks into named custom regions, which can be expanded
or collapsed. The custom regions feature was already present in the code editor. Now, Visual Studio
2012 has introduced the custom region feature in the CSS editor as well. When the region is collapsed,
it displays only the name of the region followed by ellipses indicating that there is more content in the
region, as shown in Fig.ASP- 1.69:
Fig.ASP- 1.69
Examples in Tooltips
This feature displays a tooltip when you type a property in the code editor to display a helpful example
that shows how values can be assigned to that property.
JavaScript Editor
Visual Studio 2012 has also introduced the JavaScript editor, which is a completely new feature that
improves the working experience with JavaScript in Visual Studio. The editor provides the following
features:
Code outlinin
ng: This feature outlines all functions present in the JavaScript code, which can be
collapsed or expanded according to need for focusing on a particular function.
Brace matchin
ng: This feature highlights the corresponding brace if the insertion point is placed on
an opening or closing brace, thereby easing the debugging process.
Go to Definitio
on: This feature allows you to jump to the source for a variable or function by using
the Go to Definition command, thereby decreasing the search overhead.
ECMAScriptt5: This feature supports the syntax and Application Programming Interfaces (APIs)
present in the ECMAScript5 standard, which is the latest standardized version of the JavaScript
language.
39
ASP.NET 4.5 in Simple Steps
DOM IntelliSensse: This feature improves the IntelliSense for the APIs of Document Object Model
(DOM) by supporting HTML 5 APIs, such as DOM storage, query selector, canvas, and cross-
document messaging. Also, the DOM IntelliSense is executed by a single JavaScript file rather
than through native library definitions, thereby making it easier to extend or replace.
VSDOC signature overload ds: This feature uses the <signature> element to declare the
comments of the IntelliSense for the separate overloading of JavaScript functions.
Implicit reference
es: This feature allows you to include JavaScript file to the central list, thereby
making its content available to the IntelliSense without explicitly referencing it.
Set a breakpoint within a single line of code: This feature allows you to set breakpoint when a line
contains more than one statement.
Control objects available in global scope:: The feature controls objects that are available in
global scope.
View statement completion for identifiers:: This feature allows completion for identifiers even when
accurate information about the object isn't available.
Visual C# 2012
Visual C# 2012 2 is one of the programming languages available in VS 201 12. You can use all the .NNE T
Framework Class Library and their members in Visual C# syntax, and use Visual C# programming
constructs in the code to develop ASP.NE ET applications. C# is an object-oriented programming
language and combines the power and efficiency of C++, the simple and clean object-oriented design
of Java, and the simplification of Visual Basic. With a wide range of features, C# becomes the integral
part of .NET. The features of C# are flexible, powerful, easy to use, visually oriented, Internet friendly,
and secure.
C# does not use multiple inheritance and pointers, but provides garbage collection at runtime.
Moreover, C# includes the useful operations such as operator overloading, enumerations, preprocessor
directives, pointers, and function pointers. It also supports the concept of properties. C# 2012 has been
greatly improved for C# developers as it now includes new compiler features, new language constructs,
and improved debugging.
40
Introducing Visual Studio 2012
the use of callbacks to specify the tasks that need to be performed after the asynchronous process
finishes. This makes the code complex and difficult to manage. However, with the use of the
async keyword in a method, lambda expression, or anonymous method, difficult tasks of
asynchronous coding are simplified as most of the tasks are now handled by a compiler. As a
result, asynchronous programming becomes as easier as a synchronous programming.
Caller information
n: Obtains information about the caller of a method that includes the path of
source code, the line number in the source code, and the member names of the caller.
Programmers find this information very helpful to debug, trace, and create diagnostic tools for a
program. The caller info attributes are present in the System.Runtime.ComplierServices
namespace. Some of the caller info attributes are as follows:
CallerFilePath
h: Provides the full path of a source file that contains the caller.
CallerLineNumberr: Provides the line number in a source file from which the method is
called.
CallerMemberName
e: Provides the member names, such as method, property, or event of a
caller.
Each of the caller info attributes has a default value which is applied to optional parameters only.
Lambda expressions:: Introduces with some enhancements in VS 2012. The previous version of
C# 2012 has the issue that you can use the iteration variable of a foreach loop in a lambda
expression that is contained within the loop but its use produces unexpected results. The Visual
C# 2012 has resolved this issue and the use of iteration variable of foreach loop in a lambda
expression do not produce unexpected results.
LINQ expressionss: Introduces with some enhancements in the VS 2012. The previous version of
Visual C# 2012 has the issue that you can use the iteration variable of a foreach loop in a LINQ
expression that is contained within the loop but its use produces unexpected results. The Visual
C# 2012 has resolved this issue and the iteration variable of foreach loop in a LINQ expression
do not produce unexpected results.
Named argumentss: Introduces with some enhancements in the use of named arguments and
positional arguments. The previous version of Visual C# 2012 has the issue that there exist side
effects in named and positional arguments that are combined in a method call. The Visual C#
2012 used in Visual Studio 2012 has resolved this issue and side effects are now occurred from
left to right in the argument list of the calling statement.
Overload resolution: Introduces with some enhancements in VS 2012. The previous version of
Visual C# 2012 was found problems in overload resolution that exist in method calls containing
named arguments and param parameters. The Visual C# 2012 used in Visual Studio 2012 has
resolved these problems and when more than one resolution candidate is found, overload
resolution prefers the most specific type match for named arguments.
41
ASP.NET 4.5 in Simple Steps
Apart from the keywords given in Table 1.2, there are some unreserved keywords, such as Aggregatte,
Anssi, Assemblly, Autto, Binarry, and Comparre. However, working with the unreserved keywords is not
recommended because it can make your code difficult to read and can lead to errors that can be
difficult to be identified.
42
Introducing Visual Studio 2012
In addition to single statements, statements can be grouped into blocks similar to that shown in the
following example, where we are testing the value in the variable number to see if it is less than 0:
protected void Button1_Click(object sender, EventArgs e)
{
int number = 44;
string strError;
if (number < 0)
{
strError = "Negative number.";
Response.Write(strError);
}
else
{
strError = "Positive number.";
Response.Write(strError);
}
}
In this case, we have added some statements inside the if statement, which starts with the conditional
statement if (number < 0), creating a block of statements. The statement that is declaring a variable
using keywords, such as int is a declaration statement that creates the variable number and gives it the
value 44. The preceding code snippet checks whether or not the number is less than 0. If yes, the message
Negative number is displayed, and if not, then the message Positive number is shown.
In a programming language, syntax is a convention or rule that needs to be followed while declaring or
defining a variable or a function. In other words, if you make any mistake in writing the syntax, your
program is not compiled. Observe that whenever there is a formal definition of syntax, you see the use
of square brackets ([]) as well as curly brackets ({ }). Any item enclosed within square brackets means
that the item is an optional one. Similarly, if you use the curly braces, it indicates that you need to select
one of the enclosed items.
The general statement syntax in C# is as follows:
[ <attributelist> ] [ accessmodifier ] [ { [ Shared ] | [ Static ] } ]
[ ReadOnly ] variablelist
Here, all the items in square brackets are optional and you are required to choose only one of the items
in curly braces. You can also use keywords shown in the second set of curly braces, such as Static
or/and Shared.
Table 1.3 provides a detailed explanation of the preceding syntax:
Table 1.3: Syntax Explanation
Parts Explanation
Attribute list Gives a list of attributes that apply to the variables/constants that you declare in the
statement. Separate multiple attributes with commas.
Access modifier Gives access to the variables/constants. Can be public, protected, friend, private,
or protected friend.
Static Makes variables static, which means they will retain their values even after the
procedure in which they are declared ends.
Shared Modifies a variable as shared, meaning that it is not associated with a specific
instance of a class or a method, but can be shared across many instances.
43
ASP.NET 4.5 in Simple Steps
Declaring Constants
Constantts are the names given to values that do not change during the execution of a program.
Constants are useful when we have to use a value at many places in a program without changing its
values. If we declare a value as a constant at one point and for further references to that value, we use
the name of the constant instead of the value, then all the instances of that value can be modified by
changing only the value of the constant at the declaration.
In Visual C# 201
12, constants are declared with the keyword const, as shown here:
44
Introducing Visual Studio 2012
Declaring Variables
A variable is a storage element in C#. This implies that a variable can store one or more values of a
certain type, such as int, float, char, and string. As the name indicates, the value of a variable can be
changed, but the name remains the same. A variable is a form of field and can be assigned a value at
the time of its declaration by using the = operator. The following are some examples of variable
declarations and assignments:
int i;
i=15;
In the first line of the preceding code, we declare a variable named i of the integer data type. The
second line of the code assigns a value of 15 to the integer variable i. A variable can be local or class
level. Local variables exist within the scope of a given method in a class, whereas class variables exist
for the entire lifetime of the object instance of a class. Class variables can be used in any method of a
class and can be public, private, or protected, just similar to the methods. If a class variable is public, it
can be read or written from any class method, whether or not that method resides within the same class.
Local variables cannot be defined as public or private because they are not accessible outside the
method in which they are defined.
C# also uses static class variables, which can be used in static class methods. A single instance of the
static class variable exists for all instances of a given class. Variables can be used of either simple or
array types. To create an array of integers, for example, you would do something as follows:
Int[] arr=new int[10];
45
ASP.NET 4.5 in Simple Steps
Variables, however, are not restricted to simple Value types or arrays of those Value types. You can also
define the variables that are user-defined types. For example, you can create an enumeration, as we
have discussed earlier in this chapter. Alternatively, you can create a class instance(object) by writing the
following:
Demo d=new Demo();
The default data type, if you do not specify one, is Objecct. If a variable is not initialized to a value, it is
initialized to a default value for its data type. The following are the default values for the respective data
types:
0 for all numeric types (including Byte).
Binary 0 for Char.
NULL for all reference types, such as Object, String, and all arrays. It indicates that no object is
associated with the reference.
False for Boolean.
12:00 AM of January 1 of the year 1 for date (01/01/0001 12:00:00 AM).
A new object is created using the new keyword. For example, a new TextBox control in Visual C# is
created through the Code window as follows:
TextBox TextBox1= new TextBox();
It is not necessary to create a new object by using the new keyword at the time of its declaration. We can
also create it at some other place later in the program by using the new keyword, as shown here:
Textbox TextBox1;
TextBox1 = new TextBox();
In Visuall C#, the new object is created immediately if you declare it with the new keyword. You can
declare multiple variables of the same data type without repeating the type keyword:
int count1, count2;
In the preceding code snippet, we have declared the two variables count1 and count2 of int data type
without repeating the Integer keyword twice. Variable names can be prefixed to indicate their data
type. However, the use of these prefixes is optional.
Table 1.5 lists some of the prefixes for the Visual Basic data types:
Table 1.5: Variable Prefixes
Date Type Prefix
Boolean Bln
Byte Byt
Collection object Col
Date (Time) Dtm
Double Dbl
Error Err
Integer Int
Long Lng
46
Introducing Visual Studio 2012
The use of variable prefixe es that are defined in the preceding table provides some information
regarding the variable’s data type. It can be extremely helpful when someone else reads your code. In
the next section, we learn about data types available in Visual C# 201
12.
47
ASP.NET 4.5 in Simple Steps
48
Introducing Visual Studio 2012
Subtraction 10 Ð 2 8
Table 1.9 shows the use of the asterisk (**) for multiplication and (/) for division:
Table 1.9: Arithmetic Operators—Multiplication and Division
Operatio
on Example Resullt
Multiplication 6*5 30
Division 60 / 12 5
The other two arithmetic operators are integer division (\\) and Modulus (% %). For dividing integers, the
backslash character (\) is used. If you get any remainder from the division, it is ignored. The modulus
operator, represented by the symbol %, is just the opposite. It divides two numbers and returns only the
remainder. Table 1.10 shows these operators:
49
ASP.NET 4.5 in Simple Steps
Modulus 11 %3 3; Remainder 2 2
Now, consider an example where an arithmetic statement contains more than one arithmetic operator:
5 + 3 * 2
What can be the answer? The answer depends on how you proceed. If you go from left to right and add
5 and 3 first and then multiply by 2, the answer is 16. However, if you multiply 3 by 2 first and then add
5 to it, the answer will be 11. Confused? This might seem quite confusing to you, but the possibility of
such confusion can be avoided by having rules of precedence. That means arithmetic operations are
performed in a specific order of precedence. The order is as follows:
Exponentiation (^)
Multiplication (*) and division (/)
division (\)
Modulus (%)
Addition (+) and subtraction (-)
Therefore, in an assignment statement, exponentiatio on operations are done first, then comes
multiplicatio
on and divisio on, integer divisions, modulu us operations, and finally, addition ns and
subtraction
ns. Therefore, the answer in our example will be 11 instead of 16 since multiplication is done
before addition.
In case if the precedence level of two operators are the same, for example, multiplication and division,
the operations are done from left to right. For example:
20 / 2 * 5
In the preceding example, since both the operators have the same precedence level, division will be
done first (due to the standard order of operations), yielding the result 10. Multiplication operation will
then be performed, which will result in 50. In case we want to perform multiplication first and then
division, we have to use the parenthesis operator to force operations within the parenthesis to be
performed first. If we rewrite the example, it will be as follows:
20 / (2 * 5)
Here, the multiplication is done first and then the division operation is performed, yielding the final
result as 2. There is no limitation on the number of parenthesis to be used; however, remember that
every opening parenthesis needs a closing parenthesis. If you type an assignment statement in the
Visuall C# Code window with unmatched parenthesis (a syntax error), the end of the statement is
“ssquiggle,” indicating an error. When you nest a set of parenthesis within another set of parenthesis,
evaluation starts with the innermost set of parenthesis and move outward. For example:
((2 + 3) * 5) + 7
In this case, addition of 2 and 3 is performed first and then the result is multiplied by 5, and finally, 7 is
added to the result. Therefore, the final answer comes to be 32.
Proper knowledge of the operator precedence and use of parenthesis is a must. Cross-checking your
assignment statements significantly eliminates the chances of committing any mistakes.
50
Introducing Visual Studio 2012
String Concatenation
Many times, you may need to combine two strings to display a message. This process of adding two
strings is called as string concatenatio
on. The addition (+) operato
or is used for concatenatio
on. Let’s look
at the following example:
Concatenated_String = “Visual ” + “C# 2012”
The variable Concatenated String now contains the value “Visual C# 2012.” You can also use the
(+
+) operator to concatenate two strings. As a developer, it will be better if you become comfortable with
the usage of String variables.
This now completes our discussion on basics of Visual C# 2012. Now, let’s create a simple Web site by
using VS 2012 with Visual C#.
51
ASP.NET 4.5 in Simple Steps
Fig.ASP- 1.70
52
Introducing Visual Studio 2012
6
3
4
5
7
8
Fig.ASP- 1.71
The WebApplication
n1 window appears. In the right pane of the window, the Solution Explore
er
window appears (Fig.ASP- 1.72).
0. Right-click the WebApplication
10 n1 in the Solution Explore
er window (Fig.ASP- 1.72).
A context menu appears on the screen (Fig.ASP- 1.72).
1. Click the Add New Ite
11 em option from the context menu, as shown in Fig.ASP- 1.72:
10
11
Fig.ASP- 1.72
The Add New Item – WebApplication n1 dialog box appears (Fig.ASP- 1.73).
12. Select the Web option under the Visual C# node (Fig.ASP- 1.73).
13. Click the Web Forrm option from the middle pane of the window (Fig.ASP- 1.73).
14. Click the Add button to add the Web Form in the WebApplicationn1, as shown in Fig.ASP- 1.73:
53
ASP.NET 4.5 in Simple Steps
13
12
14
Fig.ASP- 1.73
16
18
17
Fig.ASP- 1.74
The Web Form now appears with the three controls, as shown in Fig.ASP- 1.75:
Fig.ASP- 1.75
54
Introducing Visual Studio 2012
Table 1.11 lists the controls that we have added on the Web Form.
Table 1.11: Hello World Web Site Control Details
Control Description
TextBox Accepts the name of Web site users
Label Displays the name entered in the TextBox control concatenated with a welcome text
Button Assigns the text from the TextBox control to the Label Control
The IDs of these controls are TextBoxx1, Labell1, and Button n1. The IDs are provided to these
controls as a default value by Visual Studio 20112.
When you add a Labe el control on the WebForm1.aspxx page, it displays a default text as Labe el.
Similarly, the button displays Butto
on. You can replace the default text by using the Texxt property of
the controls.
19. Click Labell1 to open its Propertie
es window and set the Texxt property as HELLO WORLD FROM M:,
as shown in Fig.ASP- 1.76:
19
Fig.ASP- 1.76
20
Fig.ASP- 1.77
21.. Set the Title propertty for WebForm1.aspx as HELLO WORLLD, as shown in Fig.ASP- 1.78:
After setting the properties of the controls, the Web Form appears (Fig.ASP- 1.78).
22. Double-click the Button n control, as shown in Fig.ASP- 1.78:
55
ASP.NET 4.5 in Simple Steps
22
Fig.ASP- 1.78
Fig.ASP- 1.79
56
CHAPTER 2
Web Application in ASP.NET 4.5
Introduction
The Web application is a collection of Web pages comprising images, videos, and other digital assets
that provide you with relevant information. Earlier, we worked only on desktop applications that were
accessible to only a system in which they were installed, and could not be accessed by other users. They
could not be hosted on Internet either. Web applications came into existence in order to overcome these
shortcomings. A Web application makes use of the Internet and becomes accessible to users from all
over the world. A Web application is accessible only through Web browserrs, which are software
applications that enable you to display and interact with text, images, and other information typically
located on a Web site or a Web application. Nowadays, most of the Web applications are also
accessible through mobile phones. Even users with impaired vision can access Web applications
through screen readers that are capable of interpreting texts as sounds. To develop Web applications,
one should be well conversant with ASP.NET technologies, which are used to develop content-rich
dynamic and personalized Web sites.
This chapter discusses the usage of Web applications, improvements in ASP.NET 4.5, and coding
techniques in Web application. Now, let’s start our discussion with the usage of Web applications.
58
Web Application in ASP.NET 4.5
Support for the WebSockets protocol:: Enables developers to create a secure real-time
bidirectional communication between a client and a server over HTTP. The WebSockets
protocol is supported not only by browsers but also by clients. The WebSockets protocol contains
resources such as support for scripting languages like HTML and JavaScript, and support for
Transmission Control Protocol/Internet Protocol (TCP/IP) on both the client and the mobile
operating system. The advantage of using the WebSockets protocol is that it supports large data
transfer between the client and the server, which runs for a longer period of time. ASP.NET 4.5
and IIS (Internet Information Service) 8 provide low-level WebSockets support for asynchronously
reading and writing both the string and binary data with the help of managed APIs (Application
Programming Interfaces). ASP.NET 4.5 includes the System.Web.WebSockets namespace that
contains classes, such as AspNetWebSocket, AspNetWebSocketContext, and
AspNetWebSocketOptions for using the WebSockets protocol.
Bundling:: Allows developers to create bundles of individual JavaScript and .css files by combining
them. These bundles are generated by using the Bundle class or by using its child classes, such as
ScriptBundle and StyleBundle. After configuring an instance of a bundle class, the instance of
Bundle class is added to a global collection of Web applications so that JavaScript and
Cascading Style Sheet (CSS) files can be made available to incoming requests. The BundleConfig
file performs bundle configuration in default templates for creating bundles of core scripts and
.css files used by the default templates. After the bundling of files, they are sorted alphabetically
and then arranged in a way so that libraries and their custom extensions are loaded first.
Bundles are referenced by using the helper methods, such as Render, which generates markup
element for each resource in a bundle in the debug mode. On the other hand, Render
generates a single markup element for the whole bundle in the release mode. Developers can
set these modes in an application by using the web.config file.
59
ASP.NET 4.5 in Simple Steps
Minification
n: Shrinks JavaScript and .css files by removing whitespaces and other characters that
are not required. It is commonly used to condense JavaScript and .css files. The minification
feature can be used with Web Forms, ASP.NET MVC, and Web pages.
Support for asynchronous modules and handlers : Allows developers to write asynchronous HTTP
modules and asynchronous HTTP handlers in developing Web applications. Some properties
have been added in classes of the System.Web namespace to allow developers to effectively write
asynchronous modules and handlers. These properties are as follows:
ClientDisconnectedToken n: It is a property added in the HttpResponse class, which notifies the
application when a client gets disconnected from the Web server.
TimedOutToken n: It is a property added in the HttpRequestWrapper class, which notifies the
application when a client request has taken more time than the allowed request time-out
value.
ThreadAbortOnTimeoutt: It is a property added in the HttpContextBase class, which allows
developers to control the behaviour of timed-out requests by setting the value of the
ThreadAbortOnTimeout property to false.
Abortt: Allows you to terminate the available TCP connection of a request.
Integrated Anti-XSS encoding routines : Cross-site scripting is one of the major security threats in
Web sites. Due to lack of security mechanism in browsers, attackers can inject client-side script
from Web pages to database to access vital information. Integrated Anti-XSS encoding routines
allow developers to perform anti-cross-site scripting. Previously, the routines were available as
external DLL, but are now included in the core functionality of ASP.NET 4.5. Routines are
implemented by using the AntiXssEncoder class, which is available in the
System.Web.Security.AntiXss namespace. Developers can call the static methods of the
AntiXssEncoder class directly for using in an application. The best way for using the new anti-XSS
encoding routines is by configuring an ASP.NET application. Developers can use the
AntiXssEncoder class by default after configuring the ASP.NET application.
Support for OAuth and OpenID : OAuth is an open standard for authorization, which provides a
method to clients to access server resources using credentials, such as username and password.
OpenID is an open standard to authenticate users. User can create accounts with OpenID
identity providers, and use those accounts to access any Web site that supports OpenID
authentication. Support for OAuth and OpenID allows developers to create Web sites that give
permissions to the users to log in with the credentials created on other sites, such as Google,
Yahoo, Facebook, Twitter, and Windows Live.
Both bundling and minification are used with Web Forms, ASP.NET MVC, and Web pages.
60
Web Application in ASP.NET 4.5
Strongly typed binding expressions in data controlss: Allows you to write strongly typed, two-way
data-binding expressions for data controls, in place of using Eval or Bind expression. In this
manner, you can use the complex properties of data controls. You can also use these expressions
with the new model-binding feature.
Unobtrusive JavaScript for client-side validation n: Moves the client-side validation code into a
single external JavaScript file, which reduces the page size and loads the page faster. In addition,
this feature provides better caching of files.
HTML-encoded data-binding expressionss: Allows you to encode the data-binding expressions in
the Hypertext Markup Language (HTML) format by adding colon(:) at the end of the <%#prefix,
which marks the start of data-binding expressions.
Fallback support for Content Distribution Networks (CDNs) in the ScriptManager controll: Tests
whether the script was loaded successfully from the CDN by using the EnableCdn property of the
ScriptManager control. If the script was not loaded successfully from the CDN, then it tries to load
the script from the alternate local location.
Support for HTML5 form types:: Specifies the improvements done in the Web Forms controls to
take advantage of new features of HTML5:
The TextBox control now supports new HTML5 input types, such as email and date time, as
the TextMode property of the control has been updated.
The FileUpload control has been updated to support multiple files upload from browsers
which is a HTML5 feature.
Validator controls in HTML5 allow validation of HTML5 input elements.
The HTML5 elements that contain a URL (Uniform Resource Locater) using their attributes can
now include the runat=server attribute. Therefore, you can use the ~ operator to display the
application root.
The UpdatePanel control has been modified to support the posting of HTML5 input fields.
Improved paging in the GridView controll: Specifies the improvement in the paging functionality
by using the AllowCustomPaging and VirtualItemCount properties of the GridView control. These
two properties eliminate the need for the GridView control to fetch all the rows from the database
every time a new page is loaded.
Enhancements to Web Forms compilation n: Specifies the following improvements that have
extended the Web Forms compilation system:
Includes a ControlBuilderInterceptor class that allows you to customize Web Forms page and
control compilation output.
Includes a TemplateParser.ParseTemplate method that allows you to create an ITemplate
instance from a string of ASPX markup.
61
ASP.NET 4.5 in Simple Steps
62
Web Application in ASP.NET 4.5
63
ASP.NET 4.5 in Simple Steps
ASP.NET MVC 4, Web API, and ASP.NET Web Pages (Razor) Are Now Open
Source
The Apache 2.0 license is now used by ASP.NET MVC 4, ASP.NET Web API, and ASP.NET Web Pages v2
(Razor syntax). The important points of this development model are following:
Source code location:: Specifies the location of the source code which is available on CodePlex.
You can access the code by using the URL such as http://aspnetwebstack.codeplex.com/ and the
code uses Git for version control.
See check-ins and provide feedbackk: Allows the community to see and give feedback on
developer check-ins which can belong either to Microsoft or community or both.
64
Web Application in ASP.NET 4.5
Community contributions:: Allows developers to contribute by submitting patches and code. The
developers may or may not belong to Microsoft community.
Check-ins are evaluated:: Specifies the review of each check-in against existing standards by the
Microsoft development team for inclusion.
Community code is included in Visual Studio
o: Specifies the inclusion of approved community
code for inclusion in ASP.NET and Visual Studio.
Microsoft development and support continue e: Specifies that Microsoft reserved the right of
development of ASP.NET MVC, Web API, and Razor and can use them as standalone and part of
Visual Studio. The development is done according to Microsoft support policy.
Microsoft has not made ASP.NET Web Forms open source as they use the System.Web.dll
assembly on which Windows server platform is dependent.
65
ASP.NET 4.5 in Simple Steps
The code-behind file uses the partial class rather than the main class and does not inherit the .aspx file;
however, both the files are combined together during compilation to implement the complete
application.
SUMMARY
In this chapter, you have learned about:
Usage of Web applications to make life smooth in this fast-paced world by bringing everything
within our reach.
Improvement in ASP.NET 4.5 Web pages to make the Web page more user friendly, secure, and
powerful.
ASP.NET 4.5 coding techniques for writing code in a Web application.
66
CHAPTER 3
Standard Controls
Introduction
In the previous chapters, you have already learned how to work with Visual Studio 2012 to create Web
applications. Now, let’s discuss Web form controls. These controls are used to design the interface for a
Web application. For example, when you visit the website of Google, you type your search query in a
text box, which is a control.
ASP.NET provides a standard set of controls that can be used to develop Web applications. You can
access all these controls from the Toolbox present in the Visual Studio 2012 Integrated Development
Environment (IDE). These controls can easily be used by just dragging and dropping them at a desired
location on a Web form. Based on the tasks they perform, these controls on the Toolbox are grouped
under various categories, known as tabs. For example, the controls that are used to validate data are
placed under the Validation tab and the controls used to log on to websites are placed under the Login
tab. Similarly, controls for common use are placed under the Standard tab and are known as Standard
controls. All the Web server controls are based on the WebControl class, which originate from the
Control class.
This chapter begins by introducing the inheritance hierarchy and properties of the Control class and
System.Web.UI.WebControl class. It then discusses the various controls that originate from the
WebControl class, including TextBox, Button, Label, Literal, Image, ImageButton, ImageMap,
DropDownList, CheckBox, CheckBoxList, RadioButton, RadioButtonList, Table, Panel, AdRotator,
Calendar, HyperLink, FileUpload, HiddenField, and Wizard. In addition to discussing these controls, you
also learn to implement the controls in Web applications.
Let’s begin immediately by introducing the Control class.
68
Standard Controls
Table 3.2 lists the noteworthy public methods of the Control class:
Table 3.2: Noteworthy Public Methods of the Control Class
Method Description
ApplyStyleSheetSkin Uses the style properties defined in the page style sheet of a server control
DataBind() Binds a data source to the invoked server control and all its child controls
Dispose Enables a server control to perform final clean-up before the control is
released from memory
FindControl(string) Finds the current naming container for the specified server control
Focus Obtains input focus to a control
HasControls Determines if a server control contains any child controls
RenderControl Outputs server control content and stores tracing information about the
control if tracing is enabled
ResolveClientUrl Obtains a Uniform Resource Locator (URL) that can be used by the browser
ResolveUrl Converts a URL according to the requesting client
SetRenderMethodDelegate Assigns an event handler delegate to render a server control and its content
into its parent control
69
ASP.NET 4.5 in Simple Steps
Table 3.3 lists the noteworthy public events of the Control class:
Table 3.3: Noteworthy Public Events of the Control Class
Event Description
DataBinding Occurs when a server control binds to a data source
Disposed Occurs when a server control is released from memory, which is the last stage of
the lifecycle of the control when an ASP.NET page is requested
Init Occurs when a server control is initialized, which is the first step in the lifecycle of
the control
Load Occurs when a server control is loaded into the Page object
PreRender Occurs when a server control is about to render to its containing Control object
Unload Occurs when a server control is unloaded from memory
70
Standard Controls
Table 3.5 lists the noteworthy public methods of the WebControl class:
Table 3.5: Noteworthy Public Methods of the WebControl Class
Method Description
ApplyStyle Copies the specified style to a Web control. This method also overwrites any
existing style elements of the control.
CopyBaseAttributes Copies the properties that are not encapsulated by the Style object from a
specified server control to the server control that this method is called from. This
method is used primarily by control developers.
MergeStyle Copies only non-blank elements of the specific style to a server control, but does
not overwrite any predefined style elements of the control.
In this section, we have not mentioned the events of the WebControl class because this class inherits all
its events from the Control class. Now, let’s discuss the TextBo
ox control.
71
ASP.NET 4.5 in Simple Steps
You can enter text in a text box as a password, but the text is commonly masked with asterisks (*). You
can use the Textbo ox control to enter passwords by setting the TextMod de property of the control to
Passworrd.
The display the width of a text box is set with its Column ns property and if it is a multiline text box, the
display height is set with the Row
ws property.
Table 3.6 lists the noteworthy public properties of the TextBox class:
Table 3.6: Noteworthy Public Properties of the TextBox Class
Property Description
AutoCompleteType Obtains or sets a value that indicates the AutoComplete behavior of a TextBox
control
AutoPostBack Obtains or sets a value that indicates whether or not an automatic postback to the
server occurs when a TextBox control loses focus
CausesValidation Obtains or sets a value indicating whether or not validation is performed when a
postback occurs
Columns Obtains or sets the display width of a text box in characters
MaxLength Obtains or sets the maximum number of characters allowed in a text box
ReadOnly Obtains or sets a value indicating whether or not the content of a TextBox control
can be changed
Rows Obtains or sets the number of rows displayed in a multiline text box
Text Obtains or sets the text content of a TextBox control
TextMode Obtains or sets the behavior mode (single-line, multiline, or password) of a TextBox
control
ValidationGroup Obtains or sets a group of server controls for which the TextBox control causes
validation when the control posts back to the server
Wrap Obtains or sets a value indicating whether or not the text content wraps within a
multiline text box
72
Standard Controls
Table 3.8 lists the noteworthy public properties of the Button class:
Table 3.8: Noteworthy Public Properties of the Button Class
Property Description
CausesValidation Obtains or sets a value indicating whether or not validation is performed when a
Button control is clicked
CommandArgument Obtains or sets an optional parameter that is passed to the Command event of a
Button control along with the associated CommandName property
CommandName Obtains or sets the command name associated with a Button control that is passed
to the Command event
OnClientClick Obtains or sets the client-side script that executes when a Button control’s Click event
is raised
PostBackUrl Obtains or sets the URL of a page to post when a Button control is clicked
Text Obtains or sets the text caption displayed in a Button control
UseSubmitBehavior Obtains or sets a value indicating whether or not a Button control uses the client
browser’s submit mechanism or the ASP.NET postback mechanism
ValidationGroup Obtains or sets the group of server controls for which a Button control performs
validation when the control posts back to the server
Table 3.9 lists the noteworthy public events of the Button class:
Table 3.9: Noteworthy Public Events of the Button Class
Event Description
Click Occurs when a Button control is clicked.
Command Occurs when a Button control is clicked
Let’s now discuss the use of the TextBox and Button controls with the help of a Web application.
73
ASP.NET 4.5 in Simple Steps
13
Fig.ASP-3.1
The Propertie
es window opens (Fig.ASP-3.2).
14.. Set the TextMod
de property of the TextBoxx1 control to SingleLin
ne, as shown in Fig.ASP-3.2:
14
Fig.ASP-3.2
Similarly, add 2 TextBox controls (T TextBoxx2 and TextBoxx3), 1 Button control, and 1 Label control to the
Web form from the Toolbox and set the TextMod de property of the TextBoxx2 control to MultiLin
ne and the
TextModde property of the TextBoxx3 control to Passworrd. In addition, set the Texxt property of the Buttoon
control to Clicck Me and the Texxt property of the Labe
el control to Enter Passworrd. The Web form appears,
as shown in Fig.ASP-3.3:
74
Standard Controls
Fig.ASP-3.3
By default, the controls add in the same row; therefore, you need to manually arrange the
controls according to your requirement.
Listing 3.1 shows the source file for the Textbox and button contro
ol application after adding the controls
to the Web form and setting their properties:
Listing 3.1
1: Code of the WebForm1.aspx Form of the Textbox and button control Web Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Textbox_and_button_control.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click Me" />
<br />
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br />
<br />
<asp:TextBox ID="TextBox2" runat="server" Height="89px"
TextMode="MultiLine"></asp:TextBox>
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter Password"></asp:Label>
<br />
<asp:TextBox ID="TextBox3" runat="server" TextMode="Password"></asp:TextBox>
</div>
</form>
</body>
</html>
15. Double-click the Buttoon control in the Desig
gn mode and add the following code snippet to the
Clicck event of the Button control:
protected void Button1_Click(object sender, EventArgs e) {
TextBox1.Text = "You have clicked the button";
}
75
ASP.NET 4.5 in Simple Steps
16. Press the F5 key to view the output in the browser, as shown in Fig.ASP-3.4:
Fig.ASP-3.4
In Fig.ASP-3.4, you write multiline text in the TextBo ox control whose TextMod de property is set to
MultiLin
ne, and singleline text in the TextBo ox control whose TextMod de property is set to SingleLin ne.
Whatever you type in the TextBo ox control whose TextMod de property is set to Passworrd, appears as
special character. If you click the Butto on control, you can see text in the text box, whose TextMod de
property is set to SingleLin
ne. This text is the output of the execution of the code written for the click event
of the Butto
on control in the code-behind page (WebForm1.aspx.cs).
Whenever a Web page is refreshed or postback operation is performed, all TextBox controls
except the Textbox control whose TextMode property is set to SingleLine, appear empty.
76
Standard Controls
Fig.ASP-3.5
Listing 3.2 shows the source file for the Label control application after adding all the controls to the Web
form and setting their properties:
Listing 3.2: Code of the WebForm1.aspx Web Form of the Label control Web Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Label_control.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Click to
change label properties " />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br />
<br />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Show / Hide
Label" />
</div>
77
ASP.NET 4.5 in Simple Steps
</form>
</body>
</html>
0. Double-click the Button
10 n1 control in the Desig
gn mode and add the following code snippet to the
Clicck event of the Button control:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "Label Text is changed";
Label1.BorderStyle = BorderStyle.Dotted;
Label1.BackColor =System. Drawing.Color.Aqua;
}
11. Double-click the Button n2 control in the Desig
gn mode and add the following code snippet to the
Clicck event of the Button control:
protected void Button2_Click(object sender, EventArgs e)
{
Label1.Visible = false;
}
12. Press the F5 key to view the output in the browser.
13. Click the Click to change label propertie es button. The text in the Labe
el control changes according
to the style specified in the Click event of the Button1 control, as shown in Fig.ASP-3.6:
Fig.ASP-3.6
78
Standard Controls
Fig.ASP-3.7
Listing 3.3 shows the source file (WebForm1.aspx) for the Literal control application after adding all the
controls to the Web form and setting their properties:
Listing 3.3: Code of the WebForm1.aspx Form Web of the Literal control Web Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Literal_control.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Click me" />
<br />
<asp:Literal ID="Literal1" runat="server"></asp:Literal>
</div>
</form>
</body>
</html>
10. Double-click the Button control in the Design mode and add the following code snippet to the
Click event of the Button control:
protected void Button1_Click(object sender, EventArgs e) {
Literal1.Text = "<h1> Welcome to ASP.NET 4.5</h1>";
}
79
ASP.NET 4.5 in Simple Steps
Fig.ASP-3.8
80
Standard Controls
2. Select FILENewProjecct from the menu bar. The New Project dialog box appears.
Templates
3. Select Installed Visual C#
Web option from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.
5. Enter Imagecontrol in the Name text box as the name of the Web application, and specify an
appropriate location for the application in the Location combo box.
6. Click the OK button. The Imagecontrol Web application is created.
7. Add a Web form to the Imagecontrol application.
8. Drag and drop an Image e control (IImage1) from the Toolbox on to the Web form and set the
control’s Height and Width properties in the Properties window.
9. Right-click the name of the Web application in the Solution Explorer window. A context menu
appears (Fig.ASP-3.9).
10. Select Add New Folder option from the context menu Fig.ASP-3.9:
10
Fig.ASP-3.9
A new folder is added to the Imagecontrol application in the Solution Explorer window.
11. Specify the name of the folder as images.
12. Right-click the imagess folder. A context menu appears (Fig.ASP-3.10).
13. Select AddExisting Item from the context menu, as shown in Fig.ASP-3.10:
13
Fig.ASP-3.10
81
ASP.NET 4.5 in Simple Steps
16
Fig.ASP-3.11
17. Open the Propertie e1 control and click the ellipse button in the ImageUrrl
es window of the Image
property, as shown in Fig.ASP-3.12:
17
Fig.ASP-3.12
18
19
Fig.ASP-3.13
You can see the selected image on the Image control of the Web form, as shown in
Fig.ASP-3.14:
82
Standard Controls
Fig.ASP-3.14
Listing 3.4 shows the source file (WebForm1.aspx) for the Imagecontroll Web application:
Listing 3.4
4: Code of the WebForm1.aspx Form of the Imagecontroll Web Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Imagecontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/Tulips.jpg" />
</div>
</form></body></html>
20. Press the F5 key to view the output in the browser. The image appears, as shown in
Fig.ASP-3.15:
Fig.ASP-3.15
83
ASP.NET 4.5 in Simple Steps
Let’s now learn how to use the Imagebutton control in a Web application.
84
Standard Controls
5. Enter imagebuttoncontrool in the Namme text box as the name of the Web application, and enter
an appropriate location for the application in the Locatio
on combo box.
6. Click the OK button. The imagebuttoncontro
ol application is created.
7. Add a Web form to the imagebuttoncontro
ol application.
8. Add a folder named image
es and add some images to the folder in the imagebuttoncontrol
application.
9. Add one ImageButton
n control, two Labe
el controls (LLabell1 and Labell2) and one TextBo
ox control
(TextBox1).
10. Open the Propertiess window and set the Texxt property of the Labell1 control to Click on the
imag
ge, the Texxt property of the Labell2 control to You clicked the image button at, and the Height
and Widthh properties of the ImageButtoon control to 71pxx and 85p px.
11. Click the ellipse button of the ImageUrrl property of the ImageButton
n1 control in the Propertie
es
window.
The Select Imag
ge dialog box appears.
12. Select the image
es folder from the Project folderrs pane of the Select Imag
ge dialog box.
13. Select the name of the image from the Contents of folde
er pane.
14. Click the OK button to save the settings.
The source file for the imagebuttoncontro ol application, after adding all the controls to the Web form and
setting their properties, is as shown in Listing 3.5:
Listing 3.5
5: Code of the WebForm1.aspx Web Form of the imagebuttoncontrol Web Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="imagebuttoncontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Click on the image "></asp:Label>
<br />
<br />
<asp:ImageButton ID="ImageButton1" runat="server" Height="71px"
ImageUrl="~/images/Penguins.jpg" Width="85px" />
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="You clicked the image button
at"></asp:Label>
<br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form></body></html>
15. Double-click the ImageButto on control in the Desig
gn mode and add the following code snippet to
the Cllicck event of the control:
protected void ImageButton1_Click(object sender, ImageClickEventArgs e) {
TextBox1.Text = e.X + ", " + e.Y;
}
16. Press the F5 key to view the output in the browser.
85
ASP.NET 4.5 in Simple Steps
When you click the ImageButto on control, you see the position (coordinates) of that point in the TextBo
ox
control, as shown in Fig.ASP-3.16:
Fig.ASP-3.16
Table 3.16 lists the noteworthy public event of the ImageMap class:
Table 3.16: Noteworthy Public Event of the ImageMap Class
Method Description
Click Occurs when a HotSpot object in an ImageMap control is clicked
86
Standard Controls
15
Fig.ASP-3.17
87
ASP.NET 4.5 in Simple Steps
Botto
om to 50, Lefft to 180, Right to 340, and Top to 45. Now, you need to set the properties of
Botto
om to 50, Lefft to 360, Right to 600, and Top to 5.
In figure Fig.ASP-3.18, note that the Behavior group contains various properties of the
RectangleHotSpot. The following is a brief description of these properties:
The AlternateText propertty: Sets an alternate text for an image that is not displayed on a
Web page
The HotSpotMode propertty: Sets the mode of hotspots, such as Navigate, PostBack, Inactive,
and NotSet
The NavigateUrl propertty: Redirects the current Web page to the Web page mentioned in the
URL property of a RectangleHotSpot
The Target propertty: Specifies the frame or window in which a new page Web opens after
navigation
18. Set AlternateText, HotSpotMode, NavigateUrl, and Target properties for each hotspot. In our
case, we have set AlternateText to HotSpot1, HotSpotMode to Navigate, NavigateUrl to
~/WebForm2.aspx, and Target to _self, in the Behavior group.
Similarly, set the
e AlternateText and HotSpotMode properties of second hotspot to
9. Click the OK button to save the settings, as shown in Fig.ASP-3.18:
19
18
19
Fig.ASP-3.18
After the settings are saved, the Web form appears, as shown in Fig.ASP-3.19:
Fig.ASP-3.19
The source file for the ImageMa ap application, after adding all the controls to the Web form and setting
their properties, is as shown in Listing 3.6:
88
Standard Controls
Listing 3.6
6: Code of the WebForm1.aspx Web Form of the ImageMa
ap Web application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Imagemapcontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Using Image Map Control"></asp:Label>
<br />
<br />
<asp:ImageMap ID="ImageMap1" runat="server" Height="105px"
ImageUrl="~/images/Desert.jpg" Width="461px">
<asp:RectangleHotSpot AlternateText="HotSpot1" Bottom="50"
HotSpotMode="Navigate" Left="10" NavigateUrl="~/WebForm2.aspx"
Right="150" Target="_self" Top="5" />
<asp:RectangleHotSpot AlternateText="HotSpot2" Bottom="50"
HotSpotMode="PostBack" Left="180" Right="340" Top="45" />
<asp:RectangleHotSpot AlternateText="HotSpot3" Bottom="50"
HotSpotMode="Inactive" Left="360" Right="600" Top="5" />
</asp:ImageMap>
<br />
<br />
<asp:Label ID="Label2" runat="server"></asp:Label>
</div></form></body></html>
20. Double-click the Web form in the Desig
gn mode and add the following code snippet to the Load
event of the Web form:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label2.Text = "No PostBack performed yet.";
}
else
{
Label2.Text = "PostBack operation is performed by clicking on HOT SPOT 2.";
}
}
21. Press the F5 key to view the output in the browser (Fig.ASP-3.20).
22. Click the HotSpot2
2 hotspot of the ImageMa
ap control, as shown in Fig.ASP-3.20:
Fig.ASP-3.20
89
ASP.NET 4.5 in Simple Steps
Fig.ASP-3.21
Let’s now create a Web application to learn the use of the DropDownLisst control.
90
Standard Controls
5. Enter Dropdownlistcontro
ol in the Namme texxt box as the name of the Web application, and specify
an appropriate location for the application in the Locatio
on combo box.
6. Click the OK button. The Dropdownlistcontro
ol application is created.
7. Add a Web form to the Dropdownlistcontro
ol application.
8. Add two Labe el controls (LLabell1 and Labell2) and one TextBo ox (T
TextBoxx1) control from the
Toolbo
ox to the Web form and set the text property of the Labell1 control to DropDownList
Examplle and that of the Labell2 control to Selected Color:: .
9. Drag and drop a DropDownLisst control from the Toolbo
ox on to the Web form.
10. Set the AutoPostBacck property of the DropDownListt1 control to Tru
ue in the Propertie
es window, as
shown in Fig.ASP-3.22:
10
Fig.ASP-3.22
11
Fig.ASP-3.23
12
13
Fig.ASP-3.24
91
ASP.NET 4.5 in Simple Steps
After the settings are saved, the Web form appears, as shown in Fig.ASP-3.25:
Fig.ASP-3.25
The source file for the Dropdownlistcontro ol application, after adding all the controls to the Web form
and setting their properties, is shown in Listing 3.7:
Listing 3.7
7: Code of the WebForm1.aspx Web Form of the Dropdownlistcontro ol Web application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Dropdownlistcontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
92
Standard Controls
15. Press the F5 key to view the output in the browser, as shown in Fig.ASP-3.26:
Fig.ASP-3.26
In Fig.ASP-3.26, you can see that when you select any color from the drop-down list, the name of the
color appears in the TextBoox control according to the code written for the SelectedIndexChange
ed event
of the DropDownListt1 control.
Now, let’s learn about the CheckBoox control.
93
ASP.NET 4.5 in Simple Steps
94
Standard Controls
6. Click the OK button. The checkbox and checkboxlisst control application is created.
7. Add a Web form to the checkbox and checkboxlisst control application.
8. Add two Labeel controls (LLabell1 and Labell2) and two TextBoox controls (T
TextBoxx1 and TextBoxx2)
to the Web form and set the Texxt property of Labell1 to Select Brea
ad and that of Labell2 to Select
Fillin
ng.
9. Drag and drop two CheckBo ox controls (C CheckBoxx1 and CheckBoxx2) and one CheckBoxLisst
control (C
CheckBoxListt1) from the Toolboox on to the Web form.
0. Open the Propertie
10 es window and set the Texxt properties of the CheckBoxx1 and CheckBoxx2 controls
to Wholle Whea at and Seasame Seed ds, respectively, and set the AutoPostBacck property of each
CheckBo ox control to Tru
ue.
1. Set the Item
11 ms property of the CheckBoxListt1 control by clicking the ellipse button, as shown in
Fig.ASP-3.27:
11
Fig.ASP-3.27
13
Fig.ASP-3.28
14. Set the AutoPostbacck property of the CheckBoxListt1 control to Tru ue, the ReapeatDirectio
on
property to Vertica
al, and the RepeatLayou
ut property to OrderedList,, as shown in Fig.ASP-3.29:
14
Fig.ASP-3.29
95
ASP.NET 4.5 in Simple Steps
After adding the controls and setting their properties, the Web form appears, as shown in Fig.ASP-3.30:
Fig.ASP-3.30
The source file (WebForm1.aspx) for the checkbox and checkboxlist control Web application is shown in
Listing 3.8:
Listing 3.8
8: Code of the WebForm1.aspx Web Form of the checkbox and checkboxlist control Web
Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="checkbox_and_checkboxlist_control.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Select Bread"></asp:Label><br /><br />
<asp:CheckBox ID="CheckBox1" runat="server" Text="Whole Wheat"
AutoPostBack="True" oncheckedchanged="CheckBox1_CheckedChanged" />
<asp:CheckBox ID="CheckBox2" runat="server" Text="Sesame seeds"
AutoPostBack="True" oncheckedchanged="CheckBox2_CheckedChanged" /><br /> <br />
<asp:TextBox ID="TextBox1" runat="server" Width="332px"></asp:TextBox><br /> <br />
<asp:Label ID="Label2" runat="server" Text="Select
Filling"></asp:Label><br /> <br />
<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"
onselectedindexchanged="CheckBoxList1_SelectedIndexChanged"
RepeatLayout="OrderedList">
<asp:ListItem>Cheese</asp:ListItem>
<asp:ListItem>Sausage</asp:ListItem>
<asp:ListItem>Tomato</asp:ListItem>
<asp:ListItem>Ham</asp:ListItem>
</asp:CheckBoxList><br />
<asp:TextBox ID="TextBox2" runat="server" Width="335px"></asp:TextBox><br />
</div></form></body></html>
96
Standard Controls
Fig.ASP-3.31
97
ASP.NET 4.5 in Simple Steps
98
Standard Controls
99
ASP.NET 4.5 in Simple Steps
14
15
Fig.ASP-3.32
Fig.ASP-3.33
After adding all the controls to the Web form and setting their properties, the source file
(WebForm1.aspx) for the Radiobutto
on application appears, as shown in Listing 3.9:
Listing 3.9
9: Code of the WebForm1.aspx Web Form of the Radiobuttoon Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Radiobutton.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Select Vehicle"></asp:Label><br /><br />
<asp:RadioButton ID="RadioButton1" runat="server" Text="Car" AutoPostBack="True"
GroupName="Type" Checked="True" oncheckedchanged="RadioButton1_CheckedChanged" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="Truck"
AutoPostBack="True" oncheckedchanged="RadioButton2_CheckedChanged" />
100
Standard Controls
101
ASP.NET 4.5 in Simple Steps
21. Double-click the RadioButton4 control in the Design mode and add the following code snippet to
the CheckedChanged event of the control:
protected void RadioButton4_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "You have selected: Motorcycle";
RadioButton2.Checked = false;
RadioButton3.Checked = false;
RadioButton1.Checked = false;
}
22. Double-click the RadioButtonList1 control in the Design mode and add the following code
snippet to the SelectedIndexChanged event of the control:
protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox2.Text = "Your vehicle is: ” + RadioButtonList1.SelectedItem.Value.ToString();
}
23. Press the F5 key. The output of the Radiobutton application appears in the browser
(Fig.ASP-3.34).
In Fig.ASP-3.34, you can see that when you select a vehicle from the RadioButto on control and a color
from the RadioButtonLisst control, the selections are displayed in the respective TextBo
ox controls, as
shown in Fig.ASP-3.34:
Fig.ASP-3.34
102
Standard Controls
The Table control requires two important classes to create rows and cells. These are the TableRow class
and TableCell class, respectively. Let’s discuss these classes in the following sections.
103
ASP.NET 4.5 in Simple Steps
104
Standard Controls
10 11
Fig.ASP-3.35
The TableCell Collection Editorr dialog box appears for each TableRo
ow object (Fig.ASP-3.36).
12. Add three TableCelll objects for each TableRo
ow object (Fig.ASP-3.36).
13. Set the Texxt property of each Tablecelll object as Name, Age, and Sex, respectively
(Fig.ASP-3.36).
14. Click the OK button to save the settings, as shown in Fig.ASP-3.36:
13
14
Fig.ASP-3.36
After the settings are saved, the Web form appears, as shown in Fig.ASP-3.37:
Fig.ASP-3.37
105
ASP.NET 4.5 in Simple Steps
After adding all the controls to the Web form and setting their properties, the source file
(WebForm1.aspx) for the Tablecontro
ol application appears, as shown in Listing 3.10:
Listing 3.10
0: Code of the WebForm1.aspx Web Form of the Tablecontro
ol Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Tablecontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:Table ID="Table1" runat="server" BorderColor="Black" BorderStyle="Solid">
<asp:TableRow ID="TableRow1" runat="server" BorderColor="#000000" BorderStyle="Solid">
<asp:TableCell ID="TableCell1" runat="server" BorderColor="Black"
BorderStyle="Solid">Name</asp:TableCell>
<asp:TableCell ID="TableCell2" runat="server" BorderColor="Black"
BorderStyle="Solid">Age</asp:TableCell>
<asp:TableCell ID="TableCell3" runat="server" BorderColor="Black"
BorderStyle="Solid">Sex</asp:TableCell></asp:TableRow>
<asp:TableRow ID="TableRow2" runat="server" BorderColor="#000000"
BorderStyle="Solid">
<asp:TableCell ID="TableCell4" runat="server" BorderColor="Black"
BorderStyle="Solid">Amit Yadav</asp:TableCell>
<asp:TableCell ID="TableCell5" runat="server" BorderColor="Black"
BorderStyle="Solid">24</asp:TableCell>
<asp:TableCell ID="TableCell6" runat="server" BorderColor="Black"
BorderStyle="Solid">Male</asp:TableCell>
</asp:TableRow>
<asp:TableRow ID="TableRow3" runat="server" BorderColor="#000000" BorderStyle="Solid">
<asp:TableCell ID="TableCell7" runat="server" BorderColor="Black"
BorderStyle="Solid">Sudhir Mishra</asp:TableCell>
<asp:TableCell ID="TableCell8" runat="server" BorderColor="Black"
BorderStyle="Solid">34</asp:TableCell>
<asp:TableCell ID="TableCell9" runat="server" BorderColor="Black"
BorderStyle="Solid">Male</asp:TableCell></asp:TableRow>
<asp:TableRow ID="TableRow4" runat="server" BorderColor="#000000"
BorderStyle="Solid">
<asp:TableCell ID="TableCell10" runat="server" BorderColor="Black"
BorderStyle="Solid">Yamini Gupta</asp:TableCell>
<asp:TableCell ID="TableCell11" runat="server" BorderColor="Black"
BorderStyle="Solid">19</asp:TableCell>
<asp:TableCell ID="TableCell12" runat="server" BorderColor="Black"
BorderStyle="Solid">Female</asp:TableCell>
</asp:TableRow>
</asp:Table><br />
</div>
</form>
</body>
</html>
106
Standard Controls
15. Press the F5 key to view the output in the browser, as shown in Fig.ASP-3.38:
Fig.ASP-3.38
In Fig.ASP-3.38, you can see that the data appears in the form of a table containing four rows and
three columns.
Now, let’s discuss the Pane
el control.
107
ASP.NET 4.5 in Simple Steps
5. Enter Panelcontro ol in the Nam me text box as the name of the Web application and specify an
appropriate location for the application in the Locatio on combo box.
6. Click the OK button. The Panelcontro ol application is created.
7. Add a Web form to the Panelcontro ol application.
8. Add three RadioButto on controls (RadioButton1, RadioButton2 2, and RadioButton3 3) from the
Toolboox to the Web form.
9. Set the Texxt property of RadioButton1 1 to Red, RadioButton n2 to Greeen, and RadioButtonn3 to Blue
in the Properties window.
10. Drag and drop a Pane el control (Panel11) on to the Web form.
The source file (WebForm1.aspxx) for the Panelcontro ol application, after adding all the controls to the
Web form and setting their properties, is shown in Listing 3.11:
Listing 3.111: Code of the WebForm1.aspx Web Form of the Panelcontro ol Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Panelcontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:RadioButton ID="RadioButton1" runat="server" Text="Red"
AutoPostBack="True"GroupName="Color" />
<asp:RadioButton ID="RadioButton2" runat="server" Text="Green" AutoPostBack="True"
GroupName="Color" />
<asp:RadioButton ID="RadioButton3" runat="server" Text="Blue" AutoPostBack="True"
GroupName="Color" />
<br />
<br />
<br />
<br />
<br />
</div>
<asp:Panel ID="Panel1" runat="server" Height="34px" Width="210px"></asp:Panel>
</div>
</form>
</body>
</html>
11. Double-click the WebForm1.aspx form in the Desig
gn mod
de and add the following code snippet
in the Load event of the form:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack == false)
{
Panel1.BackColor =System.Drawing.Color.LightGray;
}
}
108
Standard Controls
12. Double-click the RadioButton n1 control and add the following code snippet in the
CheckedChange ed event of the control:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
if(RadioButton1.Checked==true)
{
Panel1.BackColor = System.Drawing.Color.Red;
}
}
13. Double-click the RadioButton n2 control and add the following code snippet in the
CheckedChange ed event of the control:
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton2.Checked == true)
{ Panel1.BackColor = System.Drawing.Color.Green; }
}
14. Double-click the RadioButton n3 control and add the following code snippet in the
CheckedChange ed event of the control:
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
if (RadioButton3.Checked == true)
{ Panel1.BackColor = System.Drawing.Color.Blue; }
}
15. Press the F5 key to view the output in the browser (Fig.ASP-3.39).
Fig.ASP-3.39
When you select any color from the RadioButto on controls, the Pane
el control fills with the selected color,
(Fig.ASP-3.39).
Now, let’s learn about the AdRotato
or control.
109
ASP.NET 4.5 in Simple Steps
110
Standard Controls
9. Add a folder named images and add three images to the folder, in Adrotato
or Web application,
as shown in Fig.ASP-3.40:
Fig.ASP-3.40
14
13
12
Fig.ASP-3.41
111
ASP.NET 4.5 in Simple Steps
<Ad>
<ImageUrl>~/images/Desert.jpg</ImageUrl>
<NavigateUrl>http://www.msn.com</NavigateUrl>
<AlternateText>Visit MSN.com</AlternateText>
<Impressions>80</Impressions>
<Keyword>MSN</Keyword> </Ad>
<Ad>
<ImageUrl>~/images/Hydrangeas.jpg</ImageUrl>
<NavigateUrl>http://www.yahoo.com</NavigateUrl>
<AlternateText>Visit yahoo.com</AlternateText>
<Impressions>80</Impressions>
<Keyword>yahoo</Keyword> </Ad>
</Advertisements>
The preceding code snippet contains the following tags:
<Advertisements>
>: Refers to the opening tag for an XML file
<Ad>
>: Acts as a container for all the other tags in the XML file
<ImageUrl>
>: Specifies the path of an image in the XML file
<NavigateUrl>
>: Specifies the URL where the image navigates after the click event
<AlternateText>
>: Shows the alternate text, in case the image is not visible
<Impressions>
>: Sets the priority of visibility of every image after the AutoPostBack event
<Keyword> >: Filters the images that you want to display on the Web page, according to the
specified keywords in this tag. The <Keyword> tag is used with the KeywordFilter property of
the AdRotatoor control.
6. Open the Propertie
16 es window of the AdRotatorr1 control (Fig.ASP-3.42).
7. Click the ellipse button of the AdvertisementFille property in the Properties window of the
17
AdRotatorr1 control.
The Select XML Fille dialog box appears (Fig.ASP-3.42).
18. Click Adrotato
or in the project folders pane to open the subfolders (Fig.ASP-3.42).
19.. Select XMLFile1.xm
ml from the Contents of folder pane (Fig.ASP-3.42).
0. Click the OK button to save the settings, as shown in Fig.ASP-3.42:
20
18 19
20
Fig.ASP-3.42
112
Standard Controls
The source file (WebForm1.aspx) for the Adrotator application, after adding all the controls to the
Web form and setting their properties, is shown in Listing 3.12:
Listing 3.12
2: Code of the WebForm1.aspx Web Form of the Adrotato
or Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Adrotator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile="~/XMLFile1.xml"
Height="100px" Width="800px" />
</div>
</form>
</body>
</html>
1. Press the F5 key to view the output in the browser (Fig.ASP-3.43).
21
Fig.ASP-3.43
Each time you press the F5 key to refresh the page the images on the Web form will change randomly.
Now, let’s learn about the Calenda
ar control.
113
ASP.NET 4.5 in Simple Steps
114
Standard Controls
115
ASP.NET 4.5 in Simple Steps
116
Standard Controls
Fig.ASP-3.44
The AutoForma
at dialog box appears (Fig.ASP-3.45).
4. Select a Calendar format from the Select a scheme pane. In our case, we select Professional 1
14
(Fig.ASP-3.45).
5. Click the OK button to save the settings, as shown in Fig.ASP-3.45:
15
14
15
Fig.ASP-3.45
After adding all the controls to the Web form and setting their properties, the source file
(W
WebForm1.asppx) for the Calenda
ar application appears, as shown in Listing 3.13:
Listing 3.13
3: Code of the WebForm1.aspx Web Form of the Calenda
ar Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Calendar.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Calendar example"></asp:Label><br /><br />
<asp:Calendar ID="Calendar1" runat="server" BackColor="White" BorderColor="White"
BorderWidth="1px" Caption="Calendar Control" Font-Names="Verdana"
Font-Size="9pt" ForeColor="Black" Height="190px" Width="350px"
CaptionAlign="Left" Font-Bold="True" NextPrevFormat="FullMonth">
117
ASP.NET 4.5 in Simple Steps
Fig.ASP-3.46
The current date and time appear in the TextBoox control whenever a user selected a date in the calendar
(Fig.ASP-3.46)
Now, let’s learn about the HyperLin
nk control.
118
Standard Controls
Table 3.34 lists the Target property options to be set for the Hyperlink class:
Table 3.34: Target Property Options of the HyperLink Class
Propertty Descriptio
on
_blank Renders the hyperlinked content in a new window without frames
_parent Renders the hyperlinked content in the immediate frameset parent
_self Renders the hyperlinked content in a frame with focus
_top Renders the hyperlinked content in a full window without frames
Let’s now create an Web application to learn the use of the HyperLin
nk control.
119
ASP.NET 4.5 in Simple Steps
10
Fig.ASP-3.47
Fig.ASP-3.48
After adding all the controls to the Web form and setting their properties, the source file
(WebForm1.aspx) for the HyperLin
nk application appears, as shown in Listing 3.14:
Listing 3.14
4: Code of the WebForm1.aspx Web Form of the HyperLin
nk Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="HyperLink.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Hyper Links
Example"></asp:Label><br /><br />
<asp:Label ID="Label2" runat="server" Text="URL
HyperLink"></asp:Label><br /><br />
<asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="http://www.google.co.in"
Target="_blank" ToolTip="Visit Google.co.in">Visit
Google.co.in</asp:HyperLink><br /><br /><br /><br /><br /><br /><br /><br />
</div>
</form>
</body>
</html>
11. Press the F5 key to view the output in the browser.
When you click the Visit Google.co.in HyperLink button, the button redirects you to the URL
mentioned in the NavigateUrrl property (which, in our case, is www.google.co.iin), as shown in
Fig.ASP-3.49:
120
Standard Controls
11
Fig.ASP-3.49
While working with the FileUpload control, you should always remember that the control
does not automatically save the files on the server. To save the files on the server, you need
to use the SaveAs method. Before saving files by using the SaveAs method, you must ensure
that ASP.NET has the write permission on the specified directory in which you want to save
the file; otherwise, the operation will fail.
Let’s now create an Web application to learn the use of the FileUploa
ad control
121
ASP.NET 4.5 in Simple Steps
Fig.ASP-3.50
Listing 3.15 shows the source file (WebForm1.aspx) for the Fileupload application after adding all the
controls to the Web form and setting their properties:
Listing 3.15: Code of the WebForm1.aspx Web Form of the Fileupload Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Fileupload.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Please Select a
file to upload"></asp:Label><br /><br />
<asp:FileUpload ID="FileUpload1" runat="server" /><br /><br />
<asp:Button ID="Button1" runat="server" Text="Upload File" />
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label> <br />
122
Standard Controls
</div>
</form>
</body>
</html>
11. Double-click the WebFormm1 form (W WebForm1.asp px) in the Design mode and add the following
code snippet in the Loa
ad event of the form, as shown in the following code snippet:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Label2.Text = "";
}
}
12. Double-click the Buttonn1 control in the Desig
gn mode and add the following code snippet in the
Click event of the control:
protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
FileUpload1.SaveAs("D:"+"/"+FileUpload1.FileName);
Label2.Text = "File Uploaded";
}
else
{
Label2.Text = "No uploaded file";
}
}
13. Press the F5 key to view the output (Fig.ASP-3.51).
14. Click the Browsse button and browse any file available on your system.
15. Click the Upload Fille button (Fig.ASP-3.51)..
The selected file is uploaded and the File Uploade
ed message is displayed, as shown in Fig.ASP-3.51:
15
Fig.ASP-3.51
In our case, we have selected a file from the C: drive, to be uploaded to the D: drive.
However, you can select the path of the file to upload according to the drives available in
your system.
123
ASP.NET 4.5 in Simple Steps
Now, let’s create a Web application to learn the use of the HiddenField control.
Fig.ASP-3.52
124
Standard Controls
11
1. Open the Propertie
es window of the HiddenField1 control.
12
2. Set the Value and Visible properties of the HiddenField1 control to Welcome to ASP.NET 4.5 and
False, respectively.
Listing 3.16 shows the source file (W
WebForm1.asp px) for the Hiddenfielld Web application after adding all
the controls to the Web form and setting their properties:
Listing 3.16
6: Code of the WebForm1.aspx Web Form of the Hiddenfielld Application
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Hiddenfield.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<br />
<asp:HiddenField ID="HiddenField1" runat="Server" Value="Welcome to ASP.NET 4.5"
Visible="False" />
<asp:Button ID="Button1" Text="Click Here to show Hidden Field Value"
runat="server" /><br /> <br />
<asp:Label ID="Label1" runat="server" />
</div>
</form>
</body>
</html>
3. Double-click the Button
13 n1 control in the Design mode and add the following code snippet in the
Clicck event of the control:
protected void Button1_Click(object sender, EventArgs e)
{ Label1.Text = HiddenField1.Value;
}
14. Press the F5 key to view the output (Fig.ASP-3.53).
15. Click the Click Here to show Hidden Field Valu
ue button. The value of the HiddenField control is
displayed as a message, as shown in Fig.ASP-3.53:
15
Fig.ASP-3.53
125
ASP.NET 4.5 in Simple Steps
126
Standard Controls
10
Fig.ASP-3.54
127
ASP.NET 4.5 in Simple Steps
11
12
Fig.ASP-3.55
15
Fig.ASP-3.56
128
Standard Controls
16
17
Fig.ASP-3.57
18. Drag and drop two Labe el controls (LLabell1 and Labell2) and two TextBo
ox controls (T
TextBoxx1 and
TextBoxx2) in the Ente
er Fulll Nam
me step of the Wizard control (Fig.ASP-3.58).
19. Set the Text property of the Labell1 control to First Nam
me and that of Labell2 control to Last Nam
me
Similarly, add one Labe
el control and one TextBo
ox control in Enter Addresss step of the Wizarrd
control.
In the same manner, set the Texxt property of Labell3 to Ente
er Addresss and the TextMod
de property
of TextBo
ox control to Multilin
ne.
The Wizard control, after setting the properties, appears as shown in Fig.ASP-3.58:
Fig.ASP-3.58
Listing 3.17 shows the source file (WebForm1.aspx) for the Wizard control application after adding all
the controls to the Web form and setting their properties:
Listing 3.17
7: Code of the WebForm1.aspx Web Form of the Wizard control Application
< <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Wizardcontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
129
ASP.NET 4.5 in Simple Steps
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Wizard ID="Wizard1" runat="server" ActiveStepIndex="1" Height="204px"
Width="381px"
HeaderText="Wizrad control" Font-Bold="True" Font-Size="0.8em" ForeColor="#C00000"
BackColor="#EFF3FB" BorderColor="#B5C7DE" BorderWidth="1px" Font-Names="Verdana">
<WizardSteps>
<asp:WizardStep ID="WizardStep1" runat="server" Title="Enter Full Name"
StepType="Start">
<asp:Label ID="Label1" runat="server" Text="First Name"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
<asp:Label ID="Label2" runat="server" Text="SurName"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
</asp:WizardStep>
<asp:WizardStep ID="WizardStep2" runat="server" Title="Enter Address"
StepType="Finish">
<asp:Label ID="Label3" runat="server" Text="Enter Address:" Font-Size="X-Small"
ForeColor="Black"></asp:Label>
<asp:TextBox ID="textbox3" runat="server" TextMode="MultiLine"
Height="32px"></asp:TextBox>
</asp:WizardStep>
</WizardSteps>
<StartNavigationTemplate>
<asp:Button ID="StartNextButton" runat="server" CommandName="MoveNext" Text="Next" />
</StartNavigationTemplate>
<StepStyle Font-Size="0.8em" ForeColor="#333333" />
<SideBarStyle BackColor="#507CD1" Font-Size="0.9em" VerticalAlign="Top" />
<NavigationButtonStyle BackColor="White" BorderColor="#507CD1" BorderStyle="Solid"
BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98" />
<SideBarButtonStyle BackColor="#507CD1" Font-Names="Verdana" ForeColor="White" />
<HeaderStyle BackColor="#284E98" BorderColor="#EFF3FB" BorderStyle="Solid"
BorderWidth="2px" Font-Bold="True" Font-Size="0.9em" ForeColor="White"
HorizontalAlign="Center" />
<StepNavigationTemplate>
<asp:Button ID="StepPreviousButton" runat="server" BackColor="White"
BorderColor="#507CD1" BorderStyle="Solid" BorderWidth="1px" CausesValidation="False"
CommandName="MovePrevious" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284E98"
Text="Previous" />
<asp:Button ID="StepNextButton" runat="server" BackColor="White" BorderColor="#507CD1"
BorderStyle="Solid" BorderWidth="1px" CommandName="MoveNext" Font-Names="Verdana"
Font-Size="0.8em" ForeColor="#284E98" Text="Next"/>
</StepNavigationTemplate></asp:Wizard>
</div>
</form>
</body>
</html>
130
Standard Controls
22
Fig.ASP-3.59
23
Fig.ASP-3.60
With this, we come to the end of the chapter. Let’s now recap the main points discussed in the chapter.
131
ASP.NET 4.5 in Simple Steps
SUMMARY
In this chapter, you have learned about:
The class hierarchy and noteworthy properties, methods, events of the Control class.
The class hierarchy and noteworthy properties and methods of the System.Web.UI.WebControl class.
The TextBox control and its implementation
The Button control and its implementation
The Label control and its implementation
The Literal control and its implementation
The Image control and its implementation
The ImageButton control and its implementation
The ImageMap control and its implementation
The DropDownList control and its implementation
The CheckBox control and its implementation
The CheckBoxList control and its implementation
The RadioButton control and its implementation
The RadioButtonList control and its implementation
The Table control and its implementation
The Panel control and its implementation
The AdRotator control and its implementation
The Calendar control and its implementation
The HyperLink control and its implementation
The FileUpload control and its implementation
The HiddenField control and its implementation
The Wizard control and its implementation
132
CHAPTER 4
Navigation Controls
Introduction
The controls that are used in a Web application to provide users with the flexibility of moving back and
forth between different Web pages of a Web site are called Navigation controls. These controls display
the address of a Web page in the form of menus and hyperlinks, which users use to navigate to any
Web page of a Web application from the current Web page. These controls represent the structure of a
Web application, that is, how different Web pages of a Web application are linked together. They also
dynamically order the Web pages when a user traverses through different Web pages. They recognize
the user’s current position in the Web site and shift the reference pointer to other pages accordingly
when the user moves from a Web page to another.
In this chapter, we discuss about the navigation controls, the SiteMapPatth, Menu, and TreeVie
ew controls
in detail.
A default schema of the Web site is automatically created for use by the SiteMapPath h controls. This
schema is contained as an Extensible Markup Language (XML) file known as the sitemap file. This
sitemap file has an extension .sitemap and is visible in the Solutio on Explore
er window when a
SiteMapPath h control is included in the project. In this sitemap file, the Web pages are referred in the
URL attribute of the siteMapNode attributes. The schematic representations of nodes are in the form of
parent-child relationship. A child node can have more nested child nodes for each level of hierarchical
nesting of Web pages.
Table 4.1 lists some noteworthy properties of the SiteMapPatth class:
Table 4.1: Noteworthy Properties of the SiteMapPath Class
Property Description
ParentLevelsDisplayed Obtains or specifies the number of levels of parent nodes, and then
displays the control accordingly
RenderCurrentNodeAsLink Specifies whether or not the site navigation node that represents the
currently displayed page is rendered as a hyperlink
PathSeparator Obtains the string that delimits the SiteMapPath node in the rendered
navigation path
CurrentNodeStyle Obtains the style used for the display text for the current node
RootNodeStyle Obtains the style for the root node display text
NodeStyle Obtains the style used for the display text for all nodes in the site
navigation path
134
Navigation Controls
Let’s create a Web application to learn the usage of the SiteMapPath control.
14
Fig.ASP-4.1
135
ASP.NET 4.5 in Simple Steps
15
16
Fig.ASP-4.2
The Web.sitema
ap option appears in the Solution Explore
er window, as shown in Fig.ASP-4.3:
Fig.ASP-4.3
136
Navigation Controls
Fig.ASP-4.4
Fig.ASP-4.5
137
ASP.NET 4.5 in Simple Steps
Let’s create a Web application to learn the usage of the TreeView control.
138
Navigation Controls
10
Fig.ASP-4.6
11
12
Fig.ASP-4.7
139
ASP.NET 4.5 in Simple Steps
13
14
Fig.ASP-4.8
Similarly, you can add any number of root nodes and child nodes in the root node (Fig.ASP-4.9).
5. Click the OK button after adding the nodes in the TreeView Node Edito
15 or dialog box, as shown in
Fig.ASP-4.9:
15
Fig.ASP-4.9
17
Fig.ASP-4.10
140
Navigation Controls
The AutoForma
at dialog box appears (Fig.ASP-4.11).
8. Select a scheme from the Select a schem
18 me pane. We have selected the Arrow
ws 2 scheme in our
case (Fig.ASP-4.11).
9. Click the OK button, as shown in Fig.ASP-4.11:
19
18
19
Fig.ASP-4.11
Fig.ASP-4.12
0. Press the F5 key to view the TreeView control in the browser (Fig.ASP-4.13).
20
21. Click the Hardwarre node to view the child nodes, as shown in Fig.ASP-4.13:
21
Fig.ASP-4.13
141
ASP.NET 4.5 in Simple Steps
The Men
nu control of ASP.NET has the following two options for displaying data:
Horizontal orientation
n: Displays the items horizontally
Vertical orientation:: Displays the items vertically
A logical relationship is first established among the parent and its children data displayed by this
control. The data items that translate into menu items are added as collection to the menu.
Therefore, for displaying data in a hierarchical format, the M ennu control must be able to read data from
a structured data source. Any data storage medium that contains data in a structural format, such as an
XML file associated with an XmlDataSource e control, can be a structured data source.. You can also
provide the items to be displayed on the Men nu control by setting the items at the design time.
On the basis of type of data they present, the two categories of menu are:
Static Menu
u: Displays its items always on the Web pages
Dynamic Menuu: Creates when the user of a Web page accesses the main menu item; the
dynamic menu items are presented as a submenu
The Menu class provides various properties, methods, and events that are customized in Web
applications to display data by using the Men
nu control. This class is made available in a program by the
following namespace:
System.Web.UI.WebControls.Menu
Table 4.7 lists the public properties of the Menu class:
Table 4.7: Noteworthy Public Properties of the Menu Class
Property Description
Controls Obtains a control collectio
on that contains the child controls of the Menu control
DataBindings Obtains a collection of MenuItemBinding objects that defines the
relationship between a data item and the menu item it is binding to
DisappearAfter Obtains or sets the duration for which a dynamic menu is displayed after the
mouse pointer is no longer positioned over the menu
Let’s create a Web application to learn the usage of the Menu control.
142
Navigation Controls
10
Fig.ASP-4.14
14
15
Fig.ASP-4.15
143
ASP.NET 4.5 in Simple Steps
16
Fig.ASP-4.16
18
Fig.ASP-4.17
The AutoForma
at dialog box appears (Fig.ASP-4.18).
9. Select a scheme from the AutoForma
19 at dialog box. In our case, we have selected Colorfu
ul
(Fig.ASP-4.18)
0. Click the OK button to apply the scheme on the Men
20 nu control, as shown in Fig.ASP-4.18:
19
20
Fig.ASP-4.18
144
Navigation Controls
The Men
nu control appears on the Web Form, as shown in Fig.ASP-4.19:
Fig.ASP-4.19
22
Fig.ASP-4.20
145
ASP.NET 4.5 in Simple Steps
9.. Right-click the name of the Dynamicmenucontro ol application in the Solution Explorer window and
select AddNew Item option from the context menu.
Visual C#
10. Select Installed Data in the left pane and select XML File in the middle pane.
11. Click the Add button of the Add New Item dialog box.
12. Add the following code snippet in the XML file:
<?xml version="1.0" encoding="utf-8" ?>
<application>
<section title="C#" url="http://www.google.com">
<subpage title ="Chapter 1 C#" url="http://www.google.com" />
<subpage title ="Chapter 2 C#" url="http://www.google.com" />
<subpage title ="Chapter 3 C#" url="http://www.google.com"/>
</section>
<section title="ASP.NET" url="http://www.google.com">
<subpage title ="Chapter 1 ASP.NET" url="http://www.google.com"/>
<subpage title ="Chapter 2 ASP.NET" url="http://www.google.com"/>
<subpage title ="Chapter 3 ASP.NET" url="http://www.google.com"/>
</section>
<section title="VB.NET" url="http://www.google.com" >
<subpage title ="Chapter 1 VB.NET" url="http://www.google.com"/>
<subpage title ="Chapter 2 VB.NET" url="http://www.google.com"/>
<subpage title ="Chapter 3 VB.NET" url="http://www.google.com"/>
</section>
</application>
13.3 Click the smart tag (>) option of the Menu
u control. The Menu Tasks appears (Fig.ASP-4.21).
14. Select the <NNew data source...> option from the drop-down list of the Choose Data Source
option in the Menu Tasks, as shown in Fig.ASP-4.21:
14
Fig.ASP-4.21
146
Navigation Controls
15
16
Fig.ASP-4.22
18
19
Fig.ASP-4.23
The name of the XMLFILE1.xmml file appears in the Data file text box.
0. Click the OK button.The XmlDataSourcce appears on the Web form.
20
1. Press the F5 key to view the Men
21 nu control in the browser (Fig.ASP-4.24).
2. Move the mouse on the application node, which is the root node. Its child node appears, as
22
shown in Fig.ASP-4.24:
147
ASP.NET 4.5 in Simple Steps
Fig.ASP-4.24
To change the menu items dynamically, make changes in the XML file at design time. The
changes are automatically reverted in the application.
New Improvements
The Menuu control appears in the form of HTML tables in the previous version of ASP.NET. It was difficult
to apply Cascading Style Sheet (CSS) styles on it and was also mismatched with the accessibility
standards. The Menu control appears as HTML in ASP.NET 4, which consists of an unordered list and list
elements. It is not difficult to apply the CSS styles now.
You will learn about CSS in Chapter 10: Master Pages, Themes, and CSS of this book.
The following code snippet shows the source code of the Menu control in ASP.NET 4:
<asp:Menu ID="Menu1" runat="server">
<Items>
<asp:MenuItem Text="Home" Value="Home" />
<asp:MenuItem Text="About" Value="About" />
</Items>
</asp:Menu>
SUMMARY
In this chapter, you have learned about:
The Navigation control and its features
The SiteMapPath control for connecting to URLs of other Web pages
The TreeView control for displaying the links to Web pages as a tree structure
The Menu control for representing links to Web pages statically and dynamically
148
CHAPTER 5
Validation Controls
Introduction
Validation controls are controls used for validating the data entered in an input control, such as textbox
on a Web page. When a user enters invalid data into an associated control, the validation control
displays an error message on the screen. The data entered by a user is validated each time it is entered,
and the error message disappears only when the data is found valid. Validation controls help save time
and enhance the efficiency of the applications by validating the data before sending a request to the
server.
In this chapter, we discuss about the various validation controls such as RequiredFieldValidator,
RangeValidator, RegularExpressionValidator, CompareValidator, CustomValidator, and ValidationSummary
controls.
In addition to the previously mentioned validation controls, we also discuss the ValidationGroup property.
Let’s begin with the BaseValidator class, which forms the base class for all validation controls.
System.Web.UI.WebControls.Label
System.Web.UI.WebControls.BaseValidator
Table 5.1 lists the noteworthy public properties of the BaseValidator class:
Table 5.1: Noteworthy Public Properties of the BaseValidator Class
Property Description
ControlToValidate Handles an input control, such as the TextBox control, which needs to be
validated
Display Handles the behavior of the error message in a validation control
EnableClientScript Obtains or specifies whether or not the client-side validation is enabled
Enabled Obtains or specifies whether or not the validation control is enabled
ErrorMessage Handles the text for the error message displayed in a ValidationSummary
control when the validation fails
ForeColor Handles the color of the message displayed when the validation fails
IsValid Obtains or specifies whether or not the associated input control passes
validation
SetFocusOnError Obtains or specifies whether or not the focus is set on the control, specified
by the ControlToValidate property when the validation fails
Text Handles the text displayed in the validation control when the validation
fails
ValidationGroup Handles the name of the validation group to which this validation control
belongs
Table 5.2 lists the noteworthy public methods of the BaseValidator class:
Table 5.2: Noteworthy Public Methods of the BaseValidator Class
Method Description
Validate Allows validation on the associated input control and updates the IsValid
property
GetValidationProperty Determines the validation property of a control, if it exists
150
Validation Controls
In the next section, let’s create a Web application to learn the usage of the RequiredFieldValidator
control.
Using the RequiredFieldValidator Control
You can create a Web application to see the usage of RequiredFiledValidator control. Let’s perform the
following steps to use the RequiredFieldValidator control in a Web application:
1. Click StartAll Programs Microsoft Visual Studio 2012 Visual Studio 2012.
2. Select FILENewProject option from the menu bar.
The New Project dialog box appears.
TemplatesVisual C#Web option in the left pane of the New Project dialog
3. Select Installed
box.
4. Select the ASP.NET Empty Web Application template in the middle pane of the New Project dialog
box.
5. Enter Requiredfieldvalidator in the Namee text box to specify the name of the application.
6. Enter an appropriate location for the application in the Location combo box.
7. Click the OK button.
The Requiredfieldvalidator Web application is created.
8. Open the Solution Explorer window and right-click the application name. In our case, we are
right-clicking the Requiredfieldvalidator Web application.
9. Select the Add New Item option from the context menu.
The Add New Item – Requiredfieldvalidator dialog box appears.
10. Select the Web form option from the middle pane.
11. Click the Add
d button.
The WebForm1.aspx form is added to the Requiredfieldvalidator Web application.
12. Add two Label controls, two TextBox controls, and one Button control from the Toolbox to the
Web form.
13. Open the Properties window and set the Text properties of the Label1 control as Enter Name:,
Label2 as Enter Lastname:, and Button1 control as Submit.
14. Drag and drop two RequiredFieldValidator controls on the Web form from the Toolbox.
15. Open the Properties window and bind the ControlToValidate property of RequiredFieldValidator1
control with the TextBox1 control, and set the error message in the ErrorMessage property as
*P
Please enter your name.
Similarly, bind the ControlToValidate property of RequiredFieldValidator2 control with the TextBox2
control, and set the error message in the ErrorMessage property as *PPlease enter your lastname.
After adding all the controls to the Web form, it appears as shown in Fig.ASP-5.1:
151
ASP.NET 4.5 in Simple Steps
Fig.ASP-5.1
Listing 5.1 shows the source code for the WebForm1.aspx form after setting the properties of the control
in the WebForm1.aspx form:
Listing 5.1
1: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Requiredfieldvalidator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Enter Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="*Please enter your name">
</asp:RequiredFieldValidator> <br />
<asp:Label ID="Label2" runat="server" Text="Enter Lastname: "></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="*Please enter your lastname">
</asp:RequiredFieldValidator> <br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
16. Press the F5 key to execute the Web application in the browser (Fig.ASP-5.2).
7. Click the Submitt button without entering data in the two TextBo
17 ox controls (Fig.ASP-5.2).
In this case, both the RequiredFieldValidato or controls (R RequiredFieldValidatorr1 and
RequiredFieldValidatorr2) display error messages, as shown in Fig.ASP-5.2:
152
Validation Controls
17
Fig.ASP-5.2
You can also use it to validate a range of numbers, strings, and dates.
153
ASP.NET 4.5 in Simple Steps
Fig.ASP-5.3
Listing 5.2 shows the source code for the WebForm1.aspx form after adding all the controls in the
Web form:
Listing 5.2:: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Rangevalidator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Range Validator Example"></asp:Label>
<br /> <br />
<asp:Label ID="Label2" runat="server" Text="Your Age "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Age should be between 18 to 99">
</asp:RangeValidator> <br /> <br />
<asp:Label ID="Label3" runat="server" Text="Date of birth (YYYY/MM/DD format)">
154
Validation Controls
</asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Enter a date between 1900/1/1 to 2012/1/1">
</asp:RangeValidator> <br /> <br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
14
Fig.ASP-5.4
The RangeValidato or control checks for a valid age and a valid date, and displays an error message if
any of these values are not entered.
155
ASP.NET 4.5 in Simple Steps
this regular expression matches a word consisting of uppercase or lowercase letters only. The + sign
stands for one or more uppercase and lowercase letters.
The following code snippet shows the regular expression to determine if the text matches a valid
electronic mail (e-mail) address:
\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*
In the preceding code snippet, \w stands for a word character (such as letters, underscores, and the rest)
and * means zero or more.
ASP.NET 4.5 includes some prebuilt regular expressions that you can use to match well-known
sequences of characters, such as a French phone number, social security number, US social security
number, e-mail address, and Internet Uniform Resource Locator (URL) address.
Table 5.5 lists the noteworthy public property of the RegularExpressionValidator class:
Table 5.5: Noteworthy Public Property of the RegularExpressionValidator Class
Property Description
ValidationExpression Obtains or sets the regular expression that you want to match against the data for
validation
Regular expressions are complex to understand, as they require in-depth knowledge of the character
relations required during custom expression definition.
Now, let’s create a Web application to learn the usage of the RegularExpressionValidato
or control.
156
Validation Controls
12
Fig.ASP-5.5
14
Fig.ASP-5.6
Similarly, set the ControlToValidatte property as TextBoxx2, ErrorMessage as Please Enter Some Valid E-
mail Addresss, and select the Internet e-mail addresss in the Regular Expression Edito
or dialog box that
appears on clicking the ellipse button of the ValidationExpressio on property of the
RegularExpressionValidator2 2 control in Propertiess window.
The Web form now appears, as shown in Fig.ASP-5.7:
Fig.ASP-5.7
157
ASP.NET 4.5 in Simple Steps
Listing 5.3 shows the source file for the WebForm1.aspx form after adding all the controls in the
Web form:
Listing 5.3
3: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Regularexpressionvalidator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Using RegularExpressionValidator control">
</asp:Label> <br /> <br />
<asp:Label ID="Label2" runat="server" Text="Enter URL"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
ControlToValidate="TextBox1" ErrorMessage="Please Enter Valid URL"
ValidationExpression="http(s)?://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?">
</asp:RegularExpressionValidator> <br />
<asp:Label ID="Label3" runat="server" Text="Enter E-mail address"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator ID="RegularExpressionValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Please Enter Some Valid E-mail Address"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
</asp:RegularExpressionValidator> <br /> <br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
</div>
</form>
</body>
</html>
15. Press the F5 key to execute the Web application (Fig.ASP-5.8).
16. Enter the invalid URL and E--mail addresss in the respective textboxes and click the Submiit button
to see the output, as shown in Fig.ASP-5.8:
16
Fig.ASP-5.8
The RegularExpressionValidator controlls check for a valid E-mail addresss and a valid URL. If the user
has not entered valid values, the RegularExpressionValidatoor control displays an error message. Let’s
now move further to understand about the CompareValidato or control.
158
Validation Controls
NotEqual Checks that controls values are not equal to each other
DataTypeCheck Compares data types between the value entered into the data-entry control being
validated and the data type specified by the Base CompareValidator Type property
The Type property is used to obtain or specify the data type of both the comparison values entered in
the input control, such as textbox. String is the default data type. Both values are automatically
converted to this data type before the comparison operation is performed. The different data types that
you can use are String, Integer, Double, Date , and Currency..
Table 5.7 lists the noteworthy properties of the CompareValidator class:
Table 5.7: Noteworthy Public Properties of the CompareValidator Class
Property Description
ControlToCompare Obtains or sets the Input control to compare with the Input control being
validated
Operator Obtains or sets the comparison operation
ValueToCompare Obtains or sets a constant value to compare with the value entered by the
user in the input control being validated
In many Web sites, value for two controls are compared to verify authentic values, such as, while
creating a user password and confirm password textbox in a Web site compares values with each other
to maintain the authenticity of a user.
Let’s create a Web application to learn the usage of the CompareValidator control.
159
ASP.NET 4.5 in Simple Steps
Fig.ASP-5.9
Listing 5.4 shows the source code for the WebForm1.aspx form, after adding all the controls in the
Web form:
Listing 5.4: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Comparevalidator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="CompareFieldValidator Example">
</asp:Label> <br /> <br />
<asp:Label ID="Label2" runat="server" Text="Father age:"></asp:Label>
160
Validation Controls
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
13
Fig.ASP-5.10
You can see that an error message specifying Your age should be less than your father’s age
e appears
(Fig.ASP-5.10).
161
ASP.NET 4.5 in Simple Steps
Table 5.8 lists the noteworthy public properties of the CustomValidator class:
Table 5.8: Noteworthy Public Properties of the CustomValidator Class
Property Description
ClientValidationFunction Obtains or sets the name of the custom client-side script
function used for validation
ValidateEmptyText Obtains or sets a Boolean value indicating whether empty text
should be validated
Table 5.9 lists the noteworthy public event of the CustomValidator class:
Table 5.9: Noteworthy Public Event of the CustomValidator Class
Event Description
ServerValidate Occurs when validation takes place on the server
162
Validation Controls
If (arguments.Value = "testuser")Then
arguments.IsValid = True
Else
arguments.IsValid = False
End IF
End Sub
</script>
3. Add a function name to the ClientValidationFunction property that is validatte, as shown in the
13
previous code snippet. The Web form now appears, as shown in Fig.ASP-5.11:
Fig.ASP-5.11
Listing 5.5 shows the source code for the WebForm1.aspx form of the CustomValidato
or control after
adding all the controls in the Web form:
Listing 5.5
5: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Customvalidator.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head>
<body>
<form id="form1" runat="server">
<div>
<script language="vbscript" type="text/vbscript">
Sub Validate (source, arguments)
If (arguments.Value = "testuser")Then
arguments.IsValid = True
Else
arguments.IsValid = False
End IF
End Sub
</script>
<asp:Label ID="Label1" runat="server" Text="Custom Validator example">
</asp:Label> <br /> <br />
<asp:Label ID="Label2" runat="server" Text="Please enter user name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ErrorMessage="Invalid Entry: Correct username is: “testuser”"
ControlToValidate="TextBox1"
ClientValidationFunction="validate"></asp:CustomValidator> <br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" />
163
ASP.NET 4.5 in Simple Steps
</div>
</form>
</body>
</html>
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
16
Fig.ASP-5.12
In Listing 5.5, a function named Validate has been created. In Fig.ASP-5.12, the value entered by the
user should be equal to the value defined by the test user in the code. If the value that the user enters is
not the same as the one defined in the code, then the CustomValidato or control displays an error
message (Fig.ASP-5.12).
164
Validation Controls
Let’s create a Web application to learn the usage of the ValidationSummary control.
165
ASP.NET 4.5 in Simple Steps
Fig.ASP-5.13
Listing 5.6 shows the source code for the WebForm1.aspx form of the ValidationSummaryy control after
adding all the controls in the Web form:
Listing 5.6
6: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Validationsummary.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="ValidationSummary Example">
</asp:Label><br /><br />
<asp:Label ID="Label2" runat="server" Text="First Name: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="TextBox1" Display="None" ErrorMessage="Firstname cannot be empty">
</asp:RequiredFieldValidator><br /><br />
<asp:Label ID="Label3" runat="server" Text="Last Name: "></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" Display="None" ErrorMessage="Lastname cannot be empty">
</asp:RequiredFieldValidator> <br /><br />
<asp:Button ID="Button1" runat="server" Text="Submit" /> <br />
<asp:ValidationSummary ID="ValidationSummary1" runat="server" />
</div>
</form>
</body>
</html>
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
166
Validation Controls
5. Click the Submiit button without entering anything in both the textbox controls, as shown in
15
Fig.ASP-5.14:
15
Fig.ASP-5.14
When the user leaves either or both the TextBoox controls blank, the error message showing the error
messages for both the controls appears (Fig.ASP-5.14).
167
ASP.NET 4.5 in Simple Steps
Fig.ASP-5.15
Listing 5.7 shows the source code for the WebForm1.aspx form of the ValidationGrou
up control after
adding all the controls in the Web form:
Listing 5.7
7: Showing the Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Validationgroup.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Style="z-index: 100;
left: 10px; position: absolute;top: 14px" Text="ValidationGroup Property">
</asp:Label><br/><br/>
<asp:Label ID="Label2" runat="server" Text="First validation
group"></asp:Label><br/><br/>
<asp:Label ID="Label3" runat="server" Text="Name:"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"
runat="server" ControlToValidate="TextBox1"
ErrorMessage="Name cannot be empty." SetFocusOnError="True"
ValidationGroup="FirstValidationGroup">
</asp:RequiredFieldValidator><br/>
<br/>
<asp:Button ID="Button1" runat="server" Text="Submit"
ValidationGroup="FirstValidationGroup" /><br /><br />
168
Validation Controls
You must add the following code snippet in the <configuration> tag in Web.config file of the
application:
<appSettings>
<add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
</appSettings>
14
Fig.ASP-5.16
15. Click the Submiit button in the second validation group. An error message appears, as shown in
Fig.ASP-5.17:
169
ASP.NET 4.5 in Simple Steps
15
Fig.ASP-5.17
SUMMARY
In this chapter, you have learned about:
The importance of BaseValidato or Class
The RequiredFieldValidatoor control and its implementation in a Web application
The RangeValidato or control and its implementation in a Web application
The RegularExpressionValidato or control and its implementation in a Web application
The CompareValidato or control and its implementation in a Web application
The CustomValidato or control and its implementation in a Web application
The ValidationSummarry control and its implementation in a Web application
The ValidationGrou up property and its implementation in a Web application
170
CHAPTER 6
Login Controls
Introduction
Login controls are used in a Web site to provide a robust login solution for Web sites without writing a
single line of code. These controls play an important role while implementing security in a Web site.
Security is implemented in a Web site mainly through two processes, that is, authentication and
authorization. The process of recognizing the identity of a user is known as authentication. The process
of providing access to various resources, such as databases and printers, to the authenticated users is
known as authorization. ASP.NET Web sites can be made highly secure by allowing only authenticated
users to access any of the Web site resources.
In earlier versions of Visual Studio, the task of securing a Web site was performed by prompting a
software developer to write security business logic in the code-behind file or setting the identity of users
inside the authentication and authorization tags of the web.config file. However, both these approaches
are found to be little cumbersome for developers. Now, the task of securing a Web site has become very
easy with the introduction of Visual Studio 2012 Integrated Development Environment (IDE). Visual
Studio 2012 IDE provides a rich set of controls for this purpose under the Login tab of its Toolbox. You
can find the Login, LoginName, LoginStatus, LoginView, PasswordRecovery, CreateUserWizard, and
ChangePassword controls under the Login tab of the Toolbox.
In this chapter, you learn how to create user accounts, as it is necessary to create them for using Login
controls in Web sites. You also learn about some of the Login controls available with Visual Studio
2012. Now, let’s learn how to create a user account for an ASP.NET Web site.
ASP.NET 4.5 in Simple Steps
12
Fig.ASP-6.1
The ASP.net Web Site Administration Tool window opens, displaying its Home page
(Fig.ASP-6.2).
172
Login Controls
13
Fig.ASP-6.2
The Securitty page of the ASP.net Web Site Administration Too ol window appears (Fig.ASP-6.3).
14. Click the Select authentication
n type link under the Userss section and select From the internet radio
butto
on.
15.. Click the Don
ne button. The Securitty page of the ASP.net Web Site Administration Too
ol window
appears again (Fig.ASP-6.3).
16.. Click the Create use
er link under the Userrs section, as shown in Fig.ASP-6.3:
16
Fig.ASP-6.3
The Create Use er section of the Securitty page appears where you need to enter the details of a
user for creating a new user account (Fig.ASP-6.4).
7. Enter the user name in the User Nam
17 me text box (Fig.ASP-6.4).
18. Enter the password in the Passworrd text box (Fig.ASP-6.4).
173
ASP.NET 4.5 in Simple Steps
While creating a user account by using the ASP.net Web Site Administration Tool, the
password is chosen in such a manner that it satisfies some predefined conditions. First, it
must contain a minimum of six characters. Second, it must have at least one numeric digit,
for example, 1, 2, 3, and so on. Finally, it must contain at least one special character, for
example, !, @, #, $, %, *, ^, or &. Examples of correct passwords are testuser1#, 1student&,
collegeStudent1@, 1myName!, and so on. Examples of incorrect passwords are hello, 123,
collegeStudent1, and many more.
9. Re-enter the password in the Confirm Passworrd text box for confirmation (Fig.ASP-6.4).
19
20. Enter an electronic mail (E-mail) address in the E-mail text box. Your password will be sent to this
e-mail address in case you forgot it (Fig.ASP-6.4).
21. Enter the security question in the Security Questio
on text box. This question is asked while
retrieving the forgotten password (Fig.ASP-6.4).
22. Enter the security answer in the Security Answe er text box. You need to provide this as answer of
the security question to retrieve the forgotten password (Fig.ASP-6.4).
3. Click the Create Use
23 er button to create your user account, as shown in Fig.ASP-6.4:
17
18
19
20
21
22
23
Fig.ASP-6.4
Your user account is created and a success message is displayed, as shown in Fig.ASP-6.5:
Fig.ASP-6.5
Now, you can click the Continuue button to create more user accounts. You can close the ASP.net Web
ol window by clicking the Close button (X) present at the top right corner of the
Site Administration Too
window.
174
Login Controls
Table 6.2 lists the noteworthy public events of the Login class:
Table 6.2: Noteworthy Public Events of the Login Class
Event Description
Authenticate Invoked when a user is authenticated
LoggedIn Invoked when the user logs in to the Web site and has been authenticated
175
ASP.NET 4.5 in Simple Steps
The Logiin control is made up of the following combination of standard ASP.NET controls:
User Name label and textbo ox: Displays text for the user name textbox. The user name textbox
accepts the user name used to authenticate the user during the login process.
Password label and textbo ox: Displays text for the password textbox, which accepts the password
entered by the user. The password textbox is always encrypted to prevent the user password from
being displayed in plain text.
Validatorrs: Validates the user name and password textboxes.
Remember me check bo ox: Specifies whether or not the user details should be remembered if the
user logs on to the Web site next time by using the same computer.
Failure text litera
al: Displays a message if the login attempt by the user fails.
Login butto
on: Submits a user request for authentication.
Now, let’s learn how to use the Login control in a Web site. To do so, let’s create a Web site in which the
user is asked to enter the user name and password on a Web form for authentication, and the user is
redirected to another Web form of the Web site if the user is authenticated successfully. Let’s perform the
following steps to know how to use the Login control in a Web application.
1. Open Visual Studio 201 12.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Logincontrol in the Name text box to specify the name of the application, and enter an
appropriate location for the application in the Location combo box.
6. Click the OK button. The Logincontrol application is created.
7. Add a Web form (W WebForm1.aspx) and Web form (W WebForm2.aspx) to the Logincontrol
application as added earlier in the previous application.
8. Drag and drop a Login control from the Toolbox on the WebForm1.aspx form.
The Web form now appears, as shown in Fig.ASP-6.6:
Fig.ASP-6.6
9. Open the Properties window of the Login control by right-clicking it and selecting Properties
option from the context menu.
176
Login Controls
10
Fig.ASP-6.7
The Select UR
RL dialog box appears (Fig.ASP-6.8).
11. Select the WebForm2.asp px option from the Contentts of folderrs pane in the Select UR
RL dialog box
(Fig.ASP-6.8).
2. Click the OK button, as shown in Fig.ASP-6.8:
12
11
12
Fig.ASP-6.8
Listing 6.1 shows the source code of the WebForm1.aspx form after setting the properties of the Login
control:
Listing 6.1
1: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Creatinguseraccounts.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/WebForm2.aspx"
onauthenticate="Login1_Authenticate"></asp:Login>
</div></form>
</body></html>
3. Double-click the Login control and add the following code snippet in the Authenticate event of the
13
Login1 control:
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
{
if (Login1.UserName == "Kogent" && Login1.Password == "india")
177
ASP.NET 4.5 in Simple Steps
{
e.Authenticated = true;
}
}
14
4. Double-click the WebForm
m2 form in the Design view and add the following code snippet in the
Load event of the WebForm2.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("Welcome USER! You logged in successfully ");
}
5. Press the F5 key to run the Web site (Fig.ASP-6.9).
15
16. Enter the user name in the User Namme text box (Fig.ASP-6.9).
17. Enter the password in the Passworrd text box (Fig.ASP-6.9).
18. Select the Remember me next timme check box (Fig.ASP-6.9).
19. Click the Log In button, as shown in Fig.ASP-6.9:
19
Fig.ASP-6.9
As soon as you click the Log In n button, the AutoComplete Passwordds dialog box appears
(Fig.ASP-6.10). If you want your password not to be remembered by Internet Explorer, select the
Don’t offer to remember any more passwords checkbox; otherwise, leave it unselected.
0. Click the Yes button to continue, as shown in Fig.ASP-6.10:
20
20
Fig.ASP-6.10
After performing the above mentioned step, you are redirected to the WebForm2.aspx form, where
you can see a welcome message, as shown in Fig.ASP-6.11:
Fig.ASP-6.11
178
Login Controls
Now, let’s learn how to use the LoginName control in a Web application by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewProjecct option from the menu bar. The New Project dialog box appears.
3.. Templates
Select Installed Visual C# Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Loginnamecontrol in the Name text box to specify the name of the application, and enter
an appropriate location for the application in the Location combo box.
6. Click the OK button. The Loginnamecontrol application is created.
7. Add a Web form to the Loginnamecontrol application.
Similarly, add another Web form to the Loginnamecontrol application and the Label control.
8. Open the Properties Window of Label1 1 control and set the Text property as Welcome!.
179
ASP.NET 4.5 in Simple Steps
9. Drag and drop the LoginNam me control from the Toolbo ox on the WebForm2.aspx Web form.
0. Open the WebForm1.aspx Web form and add the Login control from the Logiin tab of the
10
Toolboox.
1. Open the Propertie
11 es window of the Logiin control and set the URL to WebForm2.aspx in the
DestinationPageUrrl property of the Logiin control, similar to how you have done earlier.
The Web form now appears, as shown in Fig.ASP-6.12:
Fig.ASP-6.12
12
13
Fig.ASP-6.13
16
Fig.ASP-6.14
180
Login Controls
17
18
Fig.ASP-6.15
20
21
Fig.ASP-6.16
181
ASP.NET 4.5 in Simple Steps
24
Fig.ASP-6.17
The message Your account has been successfully created. appears (Fig.ASP-6.18).
5. Click the Nexxt button, as shown in Fig.ASP-6.18:
25
25
Fig.ASP-6.18
182
Login Controls
27
26
28
29
Fig.ASP-6.19
34
Fig.ASP-6.20
183
ASP.NET 4.5 in Simple Steps
The WebForm2.aspx form appears, displaying the welcome message, as shown in Fig.ASP-6.21:
Fig.ASP-6.21
184
Login Controls
Now, you learn how to use the LoginStatus control in a Web site by performing the following steps:
1. Open Visual Studio 201 12.
2. NewProject option from the menu bar. The New Project dialog box appears.
Select FILE
3. Templates
Select Installed Visual C# Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Loginstatuscontrol in the Name text box to specify the name of the application, and enter
an appropriate location for the application in the Location combo box.
6. Click the OK button. The Loginstatuscontrol application is created.
7. Add a Web form to the Loginstatuscontrol application.
Similarly, add another Web form to the Loginstatuscontrol application and the Label control.
8. Open the Properties window of Label1 control and set the Text property as Welcome!
9. Drag and drop the LoginName control on the WebForm2 (Fig.ASP-6.22).
10. Drag and drop the LoginStatus control on the WebForm2 (Fig.ASP-6.22).
11. Click the smart tag (>) button of the LoginStatus control, the LoginStatus Tasks appears
(Fig.ASP-6.22).
12. Select the Logged In option from the Views drop-down list, as shown in Fig.ASP-6.22:
12
Fig.ASP-6.22
The text on the LoginStatus control changes to Logout on the Web form, as shown in Fig.ASP-6.23:
Fig.ASP-6.23
13. Open the Properties window of the LoginStatus control and set the LogoutAction property to
Redirect, as shown in Fig.ASP-6.24.
14. Click the ellipse button of the LogoutPageUrl property of the Login control, as shown in Fig.ASP-6.24:
14
Fig.ASP-6.24
185
ASP.NET 4.5 in Simple Steps
15
16
Fig.ASP-6.25
186
Login Controls
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Welcome!"></asp:Label>
<asp:LoginName ID="LoginName1" runat="server" /><br />
<asp:LoginStatus ID="LoginStatus1" runat="server" LogoutAction="Redirect"
LogoutPageUrl="~/WebForm1.aspx" />
</form>
</body>
</html>
0. Press the F5 key to execute the application (Fig.ASP-6.26).
20
21. Enter the user name in the User Nam me text box (Fig.ASP-6.26).
2. Enter the password in the Passworrd text box (Fig.ASP-6.26).
22
3. Select the Remember me next time
23 e check box (Fig.ASP-6.26).
4. Click the Log In button, as shown in Fig.ASP-6.26:
24
24
Fig.ASP-6.26
The WebForm2.aspx form appears with message containing user name (Fig.ASP-6.27).
5. Click the Logou
25 ut link to view the Webform1.aspx, which is the Login form, as shown in
Fig.ASP-6.27:
25
Fig.ASP-6.27
187
ASP.NET 4.5 in Simple Steps
188
Login Controls
Similarly, add another Web form to the Loginviewcontrool application and the Labe
el control.
8. Drag and drop the LoginVie ew control on the WebForm2.aspx Web form (Fig.ASP-6.28).
9. Click the smart tag (>) button. The LoginView Taskks appears (Fig.ASP-6.28).
0. Select the LoggedInTemplatte from the drop-down list of the View
10 ws option, as shown in
Fig.ASP-6.28:
10
Fig.ASP-6.28
1. Add a Labe
11 el control, a LoginNam
me control, and a LoginStatu
us control in the LoginVie
ew control.
2. Open the Propertie
12 es window of the Labell1 control and set the Texxt property as Welcome!, as you
have don
ne earlie
e r.
3. Click the smart tag(>) button of the LoginStatu
13 us control, and select Logged In option from the
LoginStatu
us Taskks.
4. Open the Propertie
14 es window of the LoginStatu us control, and set the LogoutActio
on property to
Redirecct and the LogoutPageUrrl property of the Logiin control as WebForm
m1.a
asp
px.
The WebForm2.aspx Web form now appears, as shown in Fig.ASP-6.29:
Fig.ASP-6.29
189
ASP.NET 4.5 in Simple Steps
19
Fig.ASP-6.30
20
Fig.ASP-6.31
190
Login Controls
Now, you learn how to use the PasswordRecoverry control in a Web site by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
191
ASP.NET 4.5 in Simple Steps
5. Enter Passwordrecoverycontrool in the Namme textbox to specify the name of the application, and
enter an appropriate location for the application in the Locatio
on combo box.
6. Click the OK button. The Passwordrecoverycontro
ol application is created.
7. Add a Web form to the Passwordrecoverycontro
ol application.
Similarly, add another WebForm2.aspx form in the Passwordrecoverycontro
ol application.
8. Drag and drop the Passwordrecoverry control on the WebForm2.aspx form, as shown in Fig.ASP-6.32:
Fig.ASP-6.32
Fig.ASP-6.33
13
Fig.ASP-6.34
192
Login Controls
15
Fig.ASP-6.35
16
17
Fig.ASP-6.36
193
ASP.NET 4.5 in Simple Steps
21
Fig.ASP-6.37
22
23
24
25
26
27
28
Fig.ASP-6.38
The message SMTP settings have been saved appears in the Configure SMTP Setting
gs pane
(Fig.ASP-6.39).
9. Click the OK button, as shown in Fig.ASP-6.39:
29
194
Login Controls
29
Fig.ASP-6.39
195
ASP.NET 4.5 in Simple Steps
33
Fig.ASP-6.40
35
Fig.ASP-6.41
The Questio
on page appears (Fig.ASP-6.42).
6. Enter the answer in the Answe
36 er text box (Fig.ASP-6.42).
7. Click the Submiit button, as shown in Fig.ASP-6.42:
37
37
Fig.ASP-6.42
The success window appears, displaying the message Your password has been sent to yo
ou, as shown in
Fig.ASP-6.43:
Fig.ASP-6.43
196
Login Controls
the old as well as the new passwords, then the new password becomes the existing password. The
ChangePassworrd control has the following components:
Titlle: Refers to the title of the ChangePassworrd control. This appears at the top of the control and
is by default Change Your Passworrd.
Password label and textbo
ox: Refers to the label and textbox that appear for entering the existing
password of a user.
New Password label and textbo
ox: Refers to the label and textbox that appear for entering the new
password.
Confirm New Password label and textbo ox: Refers to the label and textbox that appear for entering
the new password for the purpose of confirming the change in password. An error message (in red
just below the Confirm New Password label and textbox) appears when there is a mismatch
between the password entered in the New Password and Confirm New Password textbox.
Change Password butto
on: Refers to the button that, when clicked, allows the password change.
Cancel butto
on: Refers to the button that allows you to cancel any password changes that you
have made.
Table 6.14 lists the public properties of the ChangePassword class:
Table 6.14: Public Properties of the ChangePassword Class
Property Description
CancelButtonText Obtains or sets the text displayed on the Cancel button
CancelDestinationPageUrl Retrieves or sets the URL of the Web page that the user is shown after
clicking the Cancel button in the ChangePassword control
ChangePasswordButtonImageUrl Retrieves or sets the URL of an image displayed next to the Change
Password button on the ChangePassword control, if the Change
Password button is configured by the ChangePasswordButtonType
property to be an image button
ChangePasswordButtonText Retrieves or sets the text displayed on the Change Password button
ChangePasswordFailureText Retrieves or sets the message that is shown when the user’s password is
not changed
ChangePasswordTitleText Retrieves or sets the text displayed at the top of the ChangePassword
control in the Change Password view
ConfirmNewPassword Retrieves the duplicate password entered by the user
ConfirmNewPasswordLabelText Retrieves or sets the label text for the ConfirmNewPassword text box
ConfirmPasswordCompare Retrieves or sets the message that is displayed when the new password
ErrorMessage and the duplicate password entered by the user are not identical
ConfirmPasswordRequired Retrieves or sets the error message that is displayed when the Confirm
ErrorMessage New Password textbox is left empty
ContinueButtonImageUrl Retrieves or sets the URL of an image to be used for the Continue
button on the Success view of the ChangePassword control, if the
197
ASP.NET 4.5 in Simple Steps
You can create an application to view the usage of the ChangePassword control by performing the
following steps:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
198
Login Controls
5. Enter Changepasswordcontro ol in the Namme text box to specify the name of the application, and
enter an appropriate location for the application in the Locatio
on combo box.
6. Click the OK button. The Changepasswordcontro
ol application is created.
7.. Add a Web form to the Changepasswordcontro ol application.
Similarly, add another Web form in the application.
8. Add a Labe el control to the WebForm2.aspx form and set its Texxt property as You have logged in
Successfullly!.
9. Add a LoginNam me control to view the user name in the WebForm2.aspx form (Fig.ASP-6.44).
0. Drag and drop a ChangePassworrd control on the WebForm2.aspx form (Fig.ASP-6.44).
10
The WebForm2.aspx form now appears, as shown in Fig.ASP-6.44:
Fig.ASP-6.44
11. Open the WebForm1.aspx form and add a Logiin control on it.
12. Create a user account using Asp.net Web Site Administration Too
ol.
Listing 6.8 shows the source code of the WebForm1.aspx form after setting the properties of the control:
Listing 6.8
8: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Changepasswordcontrol.WebForm1" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/WebForm2.aspx">
</asp:Login>
</div></form>
</body>
</html>
Listing 6.9 shows the source code of the WebForm2.aspx form after setting the properties of the control.
Listing 6.9
9: Code ofWebForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="Changepasswordcontrol.WebForm2" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
199
ASP.NET 4.5 in Simple Steps
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="You have logged in
Successfully!"></asp:Label> <asp:LoginName ID="LoginName1" runat="server" />
<br />
<asp:ChangePassword ID="ChangePassword1" runat="server">
</asp:ChangePassword>
</div>
</form>
</body>
</html>
13. Press the F5 key to execute the application in the browser (Fig.ASP-6.45).
14. Enter the User Nam
me and Passworrd in the text boxes (Fig.ASP-6.45).
15. Select the Remember me next tim
me checkbox and click the Log in button, as shown in
Fig.ASP-6.45:
15
Fig.ASP-6.45
The WebForm2.aspx form appears, displaying the message You have logged in Successfullly
along with the user name (Fig.ASP-6.46).
6. Enter the old password in the Passworrd text box (Fig.ASP-6.46).
16
7. Enter the new password in the New Passworrd text box (Fig.ASP-6.46).
17
8. Enter the same new password in the Confirm New Passworrd text box (Fig.ASP-6.46).
18
9. Click the Change Passworrd button, as shown in Fig.ASP-6.46:
19
16
17
18
19
Fig.ASP-6.46
The message Change Password Complette, Your password has been changed appears, as shown in
Fig.ASP-6.47:
Fig.ASP-6.47
200
Login Controls
201
ASP.NET 4.5 in Simple Steps
202
Login Controls
You can create an application to view the usage of CreateUserWizarrd control by performing the
following steps:
1. Open Visual Studio 20112.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
3.. Templates
Select Installed Visual C# Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Createuserwizardcontrol in the Name text box to specify the name of the application, and
enter an appropriate location for the application in the Location combo box.
6. Click the OK button. The Createuserwizardcontrol application is created.
7. Add a Web form to the Createuserwizardcontrol application.
8. Drag and drop the CreateUserWizard control from the Toolbox on the WebForm1.aspx form
(Fig.ASP-6.48).
The WebForm1.aspx form now appears, as shown in Fig.ASP-6.48:
Fig.ASP-6.48
Listing 6.10 shows the source code of the WebForm1.aspx form after setting the properties of controls:
Listing 6.10: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Createuserwizardcontrol.WebForm1" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CreateUserWizard ID="CreateUserWizard1" runat="server">
203
ASP.NET 4.5 in Simple Steps
<WizardSteps>
<asp:CreateUserWizardStep runat="server" />
<asp:CompleteWizardStep runat="server" />
</WizardSteps>
</asp:CreateUserWizard>
</form>
</body>
</html>
9. Press the F5 key to execute the application (Fig.ASP-6.49).
10. Enter your details in the text boxes on the WebForm1.aspx form (Fig.ASP-6.49).
11. Click the Create Use er button, as shown in Fig.ASP-6.49:
11
Fig.ASP-6.49
The message Your account has been successfully created appears, as shown in Fig.ASP-6.50:
Fig.ASP-6.50
With this, you have come to the end of this chapter. Let’s now summarize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
The user accounts in a Web application
The Login control and its implementation in a Web application
The LoginName control and its implementation in a Web application
The LoginStatus control and its implementation in a Web application
The LoginView control and its implementation in a Web application
The PasswordRecovery control and its implementation in a Web application
The ChangePassword control and its implementation in a Web application
The CreateUserWizard control and its implementation in a Web application
204
CHAPTER 7
WebParts Controls
Introduction
In the previous chapters, we have discussed features of the ASP.NET to develop Web sites. Nowadays,
websites are becoming more and more user driven in the sense that users of Web sites have the option
of choosing the content of their choice. This is known as personalization of Web sites as per the end-
user’s requirement. To build a modular Web site that can be customized dynamically at run time,
ASP.NET provides a set of server controls called the WebPartts controls.
The WebPartts controls were first introduced with ASP.NET 2.0, and are now available with the advance
versions of ASP.NET, such as ASP.NET 3.0, ASP.NET 3.5, and ASP.NET 4.5, also. The W ebPartts controls
are controls that enable you to add rich and personalized content and layout to your website, and also
edit that content and layout at runtime.
The WebPartts controls are objects of WebParts class on which the end-user can perform multiple
functions, such as open, close, or minimize a WebPart, according to the requirement of the end-user.
You can also create Web pages with multiple WebPartts controls.
Now, let’s start our discussion with an overview of the WebParts controls.
Now, let’s discuss some of the most important and commonly used WebParts controls in detail.
206
WebParts Controls
Enables you to toggle between different views of a Web page. Toggling between different views
simplifies certain tasks, such as modifying page layout and editing controls.
Enables you to define and raise the life-cycle events associated with a WebParts control. The life-
cycle events keep track of a control to determine when it is inserted, moved, connected, or
removed from a Web page.
Table 7.2 lists the properties of the WebPartManager class:
Table 7.2: Public Properties of the WebPartManager Class
Property Description
ClientIDMode Indicates how the ClientID should be generated for the control
CloseProviderWarning Confirms the closing a WebPart
DeleteWarning Displays a warning message to the user whenever they delete the control
EnableClientScript Retrieves or sets a value that specifies whether or not client-side scripting
is enabled on the WebParts page containing WebPartManager controls
EnableViewState Indicates whether the control automatically saves its state for use in
round-trips
ExportSensitiveDataWarning Retrieves or sets the text for a warning message that is displayed when a
user exports data from a WebParts control
Personalization Retrieves a reference to the object containing the data needed to
personalize a WebParts page
Table 7.3 lists the noteworthy public methods of the WebPartManager class:
Table 7.3: Public Methods of the WebPartManager Class
Methods Description
AddWebPart Adds WebParts to a particular zone on the Web page
CloseWebPart Closes a WebParts control so that it is not rendered on a Web page, but
can be reopened on it
ConnectWebParts Connects two WebParts controls, which exist in the WebPartZoneBase
zone
CreateWebPart Provides WebParts control functionality to the server control that is not a
WebParts control
DeleteWebPart Deletes a WebParts control dynamically
DisconnectWebParts Removes the connection between the two WebParts controls from a
specific zone
ImportWebPart Imports an Extensible Markup Language (XML) description file
containing state and property data for a WebParts control
MoveWebPart Changes the location of a Web server control from one
207
ASP.NET 4.5 in Simple Steps
208
WebParts Controls
Fig.ASP-7.1
209
ASP.NET 4.5 in Simple Steps
To use a CatalogZone control in a Web application, you must include CatalogPart controls in it.
CatalogPart controls are controls that provide catalogs of controls that a user can add to or remove
from a Web page. Following are the three types of CatalogPart controls:
DeclarativeCatalogParrt: Allows users to modify the functionality of a Web page by displaying a
list of WebParts controls from which they can add controls to the Web page. The
DeclarativeCatalogPart control is an object of the DeclarativeCatalogPart class. It
is available in the WebParts tab of the Toolbox. You can add the DeclarativeCatalogPart
control to a Web page by dragging the control from the Toolbox and dropping inside the
CatalogZone control in the Designer window of the Web page. Before adding a
DeclarativeCatalogPart control to a Web page, you must ensure that the Web page
contains a CatalogZone control, because the DeclarativeCatalogPart control can be
added only to a specific control zone.
PageCatalogParrt: Provides a catalog for storing the references of all the closed WebParts controls
on a Web page. This control enables users to close and reopen the closed WebParts controls
back on the Web page. A control is said to be closed when:
It is hidden on the Web page
It is not rendered in the Web page
It does not take part in the Web page life cycle
The PageCatalogPart control provides a list of check boxes of closed WebParts controls. To open
or add these closed WebParts controls to the Web page again, select the check boxes as well as
the zone where the controls have to be added, and then click the Add button in the
PageCatalogPart control on the Web page.
ImportCatalogParrt: Helps users to import the description file (the .WebPart file) for a WebParts
control. The .WebPart file describes the settings of WebParts controls, which can be added to a
specified zone on a Web page. The control provides the facility to browse and upload the
.WebPart file.
You can insert the CatalogZone control by dragging it from the Toolbox and dropping it on the Design
view of the Web Form.
Fig.ASP-7.2 shows the CatalolgZon
ne control in the Design view:
Fig.ASP-7.2
210
WebParts Controls
Fig.ASP-7.3
The EditorZone control can have various EditorPart controls to customize the WebParts controls. There
are four EditorPart controls, namely, LayoutEditorPart, AppearanceEditorPart, PropertyGridEditorPart,
and BehaviorEditorPart, that are available in ASP.NET 4.5.
Let’s now learn about each of them in detail.
211
ASP.NET 4.5 in Simple Steps
a Web page having the WebParts controls is in the edit mode. In this mode, you also need to select a
particular WebParts control to edit the layout-oriented UI properties. The LayoutEditorPart control
offers the following three options for modifying a Web Part control:
ChromeStatte: Returns or sets the current state of a WebParts control, which can be in normal or
minimized state
Zone:: Returns the WebPartZoneBase zone, which consists of a WebParts control
ZoneIndeex: Returns the index position of WebParts controls, which reside in a WebPartZone
control
The LayoutEditorPart control is added to the EditorZone control, as shown in Fig.ASP-7.4:
Fig.ASP-7.4
212
WebParts Controls
Fig.ASP-7.5
Fig.ASP-7.6
213
ASP.NET 4.5 in Simple Steps
Fig.ASP-7.7
214
WebParts Controls
To add the WebPartZon ne control to a page, drag and drop the WebPartZon ne control from the Toolbox to
the Design view of a Web Form. The WebPartZon ne control in the Design view is shown in Fig.ASP-7.8:
Fig.ASP-7.8
215
ASP.NET 4.5 in Simple Steps
216
WebParts Controls
Fig.ASP-7.9
217
ASP.NET 4.5 in Simple Steps
Fig.ASP-7.10 shows the PageCatalogPart control is added inside the CatalogZone control in the Design
view:
218
WebParts Controls
Fig.ASP-7.10
219
ASP.NET 4.5 in Simple Steps
Fig.ASP-7.11
Listing 7.1 shows the source code of the WebForm1.aspx form after adding the controls and setting the
properties,
Listing 7.1
1: Showing the Code of the WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Webpartscontrol.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:WebPartManager ID="WebPartManager1" runat="server">
</asp:WebPartManager> <br />
<asp:LinkButton ID="LinkButton1" runat="server">Catalog</asp:LinkButton>
<asp:LinkButton ID="LinkButton2" runat="server">Edit</asp:LinkButton>
<asp:WebPartZone ID="WebPartZone1" runat="server">
<ZoneTemplate>
<asp:Calendar ID="Calendar1" runat="server"></asp:Calendar> </ZoneTemplate>
</asp:WebPartZone>
<asp:WebPartZone ID="WebPartZone2" runat="server"> <ZoneTemplate>
<asp:LinkButton ID="LinkButton3" runat="server">LinkButton</asp:LinkButton>
</ZoneTemplate>
</asp:WebPartZone>
<asp:CatalogZone ID="CatalogZone1" runat="server">
<ZoneTemplate>
220
WebParts Controls
23
Fig.ASP-7.12
221
ASP.NET 4.5 in Simple Steps
Fig.ASP-7.13
You can again add the LinkButtoon control from the WebPartZone1 control to the WebPartZone2
control in the same manner as aforementioned, as shown in Fig.ASP-7.14.
5. Click the smart tag beside the Untitled[2
25 2] pane in the WebPartZone
e2 control (Fig.ASP-7.14).
6. Click the Closse option, as shown in Fig.ASP-7.14:
26
25
26
Fig.ASP-7.14
The LinkButto
on control in WebPartZone2 control disappears (Fig.ASP-7.15).
222
WebParts Controls
27
Fig.ASP-7.15
28
30
29
Fig.ASP-7.16
223
ASP.NET 4.5 in Simple Steps
31
Fig.ASP-7.17
32
Fig.ASP-7.18
3. Click the smart tag near the Calendar control in the WebPartzone1 control (Fig.ASP-7.19).
33
4. Select the Ediit option from the drop-down list, as shown in Fig.ASP-7.19:
34
224
WebParts Controls
33
34
Fig.ASP-7.19
35
36
Fig.ASP-7.20
225
ASP.NET 4.5 in Simple Steps
Fig.ASP-7.21
With this, you have come to the end of this chapter. Let’s now memorize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
WebPartts controls and their implementation
Creating WebParts page in a Web application by using the WebPartss controls
226
CHAPTER
8
Database Controls
Introduction
A database is a collection of records or information that is stored in a computer in a systematic way, so
that a computer program can access the information easily whenever required. Structured Query
Language (SQL) is used to work with databases, such as retrieving, storing, deleting, and updating the
records stored in the tables. An application performs the various functions on databases such as
displaying the data in a tabular format after retrieving the records from the database; displaying the
data after processing the record retrieved from the database, such as calculating the service duration of
each employee and then displaying the records; processing the fetched data and updating them in the
database; and deleting the records from the database depending on the choice or condition specified
by the user of the application.
Working with any database is a complex task that involves many components, such as recognizing a
database server, authenticating users of the database, and using SQL to retrieve records from the
databases.
Your application can work with database objects by using ADO. The ActiveX Data Objects (ADO)
technology of .NET Framework is dedicated to facilitate working with the databases. The ADO.NET data
access technology equips .NET applications with the capability of simple yet robust data integration. In
this chapter, you learn about the Connected Data Access, ADO.NET, The SQLDataSource control, the
ObjectDataSource control, the XmlDataSource control, the LinqDataSource control, the
AccessDataSource control, and the Introduction to Data-Bound controls.
ASP.NET 4.5 in Simple Steps
ADO.NET
As you have learned earlier that when a database is accessed by multiple users over multiple networks,
all the data server resources are consumed quickly, which ultimately leads to congestion in the networks.
The database handling mechanisms in the .NET development environment define a methodology to
create a copy of the database objects, such as tables, views, relations, and data types, in the local
memory of the ASP.NET application. The application works on the copy of data stored in the local
memory of the application. This shows that the application process works in a detached mode with the
database. The actual connection with the database is made only when the final read, write, or update
operations are performed on the database. This is how ADO.NET preserves the resources.
ADO is the strongest feature of.NET Framework. Any windows or Web application developed in the
.NET Framework uses ADO objects to work with databases. Creating an application that provides
access to databases is a cumbersome task. ADO.NET provides a group of classes that helps to make
the cumbersome task easier. Incorporating ADO.NET features in the applications has been made very
simple in the .NET Framework.
228
Database Controls
ADO.NET Objects
ADO.NET is a new evolution of the ADO technology. In ADO, you remain connected to a database as long
as you manipulate the data in the database. Once data manipulation is over, you must close the connection
to the database. This process develops problems with the increase in the number of users, which, in turn,
increases the load on the database server, thereby affecting the performance of the database. To overcome
this problem, the ADO.NET technology is introduced, which is a kind of a disconnected model. It connects to
the database when required, retrieves information, and then gets disconnected.
The ADO.NET technology uses the following objects to manipulate the data in a database:
Connection objectss: Connects you with the database. A data adapter needs a connection to a data
source to read and write the data. For this purpose, it uses the OleDbConnection, OdbcConnection,
OracleConnection, or SqlConnection objects to communicate with a data source.
DataAdapter objectt: Enables you to communicate between a data source and a dataset. You can
configure a data adapter with SQL to execute against the data source. The available data adapters
are the OleDbDataAdapter, OdbcDataAdapter, OracleDataAdapter, AccessDataAdapter, and
SqlDataAdapter objects.
Command objectt: Requires reading, adding, updating, and deleting records in a data source.
For each of these operations, the data adapter contains a command object. Data adapters
support four types of command objects: SelectCommand, InsertCommand, UpdateCommand,
and DeleteCommand.
DataSet objectt: Stores data in a disconnected cache. The structure of a dataset is similar to that
of a relational database. The Dataset object represents a complete set of data including the
related tables, constraints, and relationships. Datasets are supported with DataSet objects.
DataTable object: Uses to store a data table from a dataset. DataTable object contains two
important properties, namely, Columns and Rows. The Columns property is a collection of the
DataColumn objects that represent the columns of data in a table. The Rows property is a
collection of the DataRow objects that represent the rows of data in a table.
229
ASP.NET 4.5 in Simple Steps
DataReader objectt: Holds a read-only, forward-only set of data from a database. The use of a
data reader can increase the speed with which the data is retrieved from the database, because
only one row of the data remains in memory at a time.
DataView objectt: Represents a customized view of a single table that can be filtered, searched, or
sorted. A data view, supported by the DataView class, is a data snapshot that takes up few
resources.
Constraint objectt: Checks data integrity. A constraint, supported by the Constraint class, is a rule that
can be used when rows are inserted, updated, or deleted to check the affected table after performing
the operation. Constraints are of two types: unique constraints and foreign-key constraints.
DataRelation objectt: Specifies a relationship between the parent and child tables based on a key
that is shared by both the tables.
DataRow objectt: Corresponds to a particular row in a data table. You use the Item property to
get or set a value in a particular field in the row.
DataColumn object: Represents the columns in a table. Each object has a DataType property
that specifies the kind of data each column contains, such as integers or string values.
Now, let’s know about the SQLDataSource control.
Table 8.2 lists some noteworthy public methods of the SqlDataSource class:
230
Database Controls
You can create a Web site to view the usage of SQLDataSource control by performing the following
steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
Visual Studio 2012.
The Start Page of Microsoft Visual Studio 2012 appears.
2. Select FILENewWeb Site option from the menu bar on the Start Page.
The New Web Site dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog
box.
5. Click the Browse button for location, and enter name of the Web site, such as
Sqldatasourcecontrol, in the text box to specify the location and name of the Web site.
6. Click the OK button.
The Sqldatasourcecontrol Web site is created.
7. Open the Solution Explorer window and right-click the Web site name. In our case, we are right-
clicking the Sqldatasourcecontrol Web site.
8. Select the Add New Item option from the context menu.
The Add New Item dialog box appears.
Visual C# option in the left pane and Web Form in the middle pane of the
9. Select the Installed
Add New Item dialog box.
10 Click the Add button.
10. The Default.aspx form is added to the Sqldatasourcecontrol Web site.
Download Northwind database from the Internet, which is freely available, and install it on
your computer. It is by default installs in C: drive of your computer.
11. Drag and drop the GridView control and SqlDataSource control from the Data tab in the Toolbox
on the Web page (Fig. ASP-8.1).
12. Click the smart tag on the SqlDataSource control (Fig. ASP-8.1).
The SqlDataSource Tasks appears (Fig.ASP-8.1).
13. Select the Configure Data Source from the SqlDataSource Tasks, as shown in Fig.ASP-8.1:
231
ASP.NET 4.5 in Simple Steps
13
Fig.ASP-8.1
14
Fig.ASP-8.2
19
Fig.ASP-8.3
232
Database Controls
20
Fig.ASP-8.4
21
Fig.ASP-8.5
The Save the Connection String to the Application Configuration File page of the Configure Data
Sourcce dialog box appears, which prompts you for saving the connection string (Fig.ASP-8.6).
2. Click the Nexxt button, as shown in Fig.ASP-8.6:
22
233
ASP.NET 4.5 in Simple Steps
22
Fig.ASP-8.6
The Configure the Select Statementt page of the Configure Data Source e dialog box appears,
which prompts you for selecting the columns that you want to show on the Web page in the
GridVieww control (Fig.ASP-8.7).
23. Select the Specify columns from a table or vie
ew radio button (Fig.ASP-8.7).
24. Select the column names that you want to display in the GridView w control. In our case, we are
selecting the ProductIID, ProductNam me, UnitPricce, UnitsInStocck, and UnitsOnOrde er columns
(Fig.ASP-8.7).
25. Click the Nexxt button, as shown in Fig.ASP-8.7:
23
24
25
Fig.ASP-8.7
The Test Querry page of the Choose Data Sourcce dialog box appears (Fig.ASP-8.8).
26. Click the Test Queryy button (Fig.ASP-8.8).
The data appears in the Test Query pane (Fig.ASP-8.8).
234
Database Controls
27
Fig.ASP-8.8
29
Fig.ASP-8.9
Listing 8.1 shows the source code of efault.aspx Web form after adding the controls and setting
their properties:
Listing 8.1
1: Code of the Default.aspx Web form in the Sqldatasourcecontrol application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title></title></head>
<body><form id="form1" runat="server"><div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataKeyNames="ProductID" DataSourceID="SqlDataSource1">
<Columns><asp:BoundField DataField="ProductID" HeaderText="ProductID"
InsertVisible="False" ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
SortExpression="ProductName" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
235
ASP.NET 4.5 in Simple Steps
SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder"
SortExpression="UnitsOnOrder" /></Columns></asp:GridView> </div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server”
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of
roducts]"></asp:SqlDataSource></form></body></html>
Fig.ASP-8.10
236
Database Controls
Table 8.4 lists some noteworthy public methods of the ObjectDataSource class :
Table 8.4: Noteworthy Public Methods of the ObjectDataSource Class
Method
ds Description
n
Databind Allows you to bind a Data Source to the ObjectDataSource control
Select Allows you to retrieve the records or data from the object to which the
ObjectDataSource control is pointing
Insert Allows you to insert the records or data into the object to which the
ObjectDataSource is pointing
You have learned that the ObjectDataSourcce control accepts data from any business logic compiled as
an object. Now, let’s create an application to learn the use of the ObjectDataSourcce control by
performing the following steps:
1. Open Visual Studio 201
12.
2. Select FILENewWeb Sitte option from the menu bar on the Start page. The New Web Site
dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog
box.
5. Click the Browse button for location, and enter the name of the Web site such as
Objectdatasourcecontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create the Objectdatasourcecontrol Web site.
7. Add a Web Form to the Objectdatasourcecontrol Web site.
8. Drag and drop a GridView and an ObjectDataSource control from the Data tab in the Toolbox
to the Web Form, as shown in Fig.ASP-8.11:
Fig.ASP-8.11
237
ASP.NET 4.5 in Simple Steps
11
Fig.ASP-8.12
de folder and select Add Add New Item. The Add New Item dialog box
2. Right-click the App_Cod
12
appears (Fig.ASP-8.13).
Visual C# φρομ τηε left pane and select Class from the middle pane of the Add
13. Select Installed
New Item dialog box (Fig.ASP-8.13).
14. Click the Add
d button, as shown in Fig.ASP-8.13:
13
14
Fig.ASP-8.13
15. Include two namespaces System.Data and System.Data.SqlClient in the Class file.
16. Add the following code snippet in the Class file:
public DataSet getinfo()
{
SqlConnection con = new SqlConnection("Data Source=DEBOLEENA-PC;Initial
Catalog=Northwind;Integrated Security=True");
SqlDataAdapter da = new SqlDataAdapter("Select * from Products",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
238
Database Controls
17
Fig.ASP-8.14
8. Open the Defalut.aspx form and select the Configure Data Sourcce option available on the
18
ObjectDataSource
e Tasks that appears on clicking the smart tag, as shown in Fig.ASP-8.15:
18
Fig.ASP-8.15
19
Fig.ASP.8.16
239
ASP.NET 4.5 in Simple Steps
20
0. Select the method from the Choose a metho od drop-down list (Fig.ASP-8.17).
21
1. Click the Finissh button, as shown in Fig.ASP-8.17:
20
21
Fig.ASP-8.17
Fig.ASP-8.18
Listing 8.2 shows the source code of the Default.aspx Web form after adding the controls and setting the
properties:
Listing 8.2: Code of the Default.aspx Web form of the Objectdatasourcecontrol Web site
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head>
<body> <form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource1">
</asp:GridView> <div> </div>
<asp:ObjectDataSource ID="ObjectDataSource1"runat="server"
SelectMethod="getinfo" TypeName="Class1"></asp:ObjectDataSource></form></body></html>
3. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.19:
23
240
Database Controls
Fig.ASP-8.19
241
ASP.NET 4.5 in Simple Steps
Let’s create an application thatt uses an XmlDataSourcce control to retrieve data into a Web application
from an XML file and a GridVie ew control to query the XmlDataSourcce control to display the data on the
Web page, by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWeb Site e option from the menu bar on the Start page. The New Web Sitte dialog
box appears.
3. Select InstalledTemplates Visual C# Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog box.
5. Click the Browse button for location, and enter the name of the Web site such as
XMLdataSourcecontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create the XMLdataSourcecontrol Web site.
7. Add a Web Form to the XMLdataSourcecontrol Web site.
8. Drag and drop one XmlDataSource and GridView control from the Data tab of the Toolbox on the
Web Form.
9. Right-click the Web site name and select Add Add New Item option from the context menu.
The Add New Item dialog box appears (Fig.ASP-8.20).
Visual C# from the left pane and XML File from the middle pane of the Add
10. Select Installed
New Item dialog box (Fig.ASP-8.20).
11. Click the Addd button, as shown in Fig.ASP-8.20:
10
11
Fig.ASP-8.20
242
Database Controls
3. Click the smart tag of the XmlDataSource controll and click the Configure Data Sourcce option in
13
the XmlDataSource Tasks, as shown in Fig.ASP-8.21:
13
Fig.ASP-8.21
18
Fig.ASP-8.22
Listing 8.3 shows the source code of the Default.aspx Web form after adding the controls and setting the
properties:
Listing 8.3:: Code of the Default.aspx Web form of the XMLdatasourcecontrol Web site
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head><body>
<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" DataSourceID="XmlDataSource1">
</asp:GridView> <div> </div>
<asp:XmlDataSource ID="XmlDataSource1" runat="server" DataFile="~/XMLFile.xml">
</asp:XmlDataSource>
</form>
</body></html>
243
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.23
244
Database Controls
Let’s create an Web application to learn the usage of the LinqDataSource control with a data-bound
control by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWeb Site
e option from the menu bar. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog
box.
5. Click the Browse button for location, and enter the name of the Web site such as
Linqdatasourcecontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create the Linqdatasourcecontrol Web site.
7. Add a Web Form to the Linqdatasourcecontrol Web site.
8. Drag and drop one LinqDataSource and GridView control from the Data tab of the Toolbox on
the Web Form.
9. Open the Server Explorer window (Fig.ASP-8.24).
10. Right-click the Data Connections (Fig.ASP-8.24).
11. Select the Add Connection option from the context menu, as shown in Fig.ASP-8.24:
11
Fig.ASP-8.24
245
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.25
15
16
Fig.ASP-8.26
The Microsoft Visual Studio message box prompts you to put LINQ to SQL Classes in the
App_Code folder (Fig.ASP-8.27).
17. Click the Yes button, as shown in Fig.ASP-8.27:
246
Database Controls
17
Fig.ASP-8.27
Fig.ASP-8.28
20
0. Close the DataClasses.dbmml file and click the smart tag of the LinqDataSourcce control. Then select the
Configure Data Sourcce option from the LinqDataSource Taskks, as shown in Fig. ASP-8.29:
20
Fig.ASP-8.29
247
ASP.NET 4.5 in Simple Steps
22. Select context object from the Choose your context objecct drop-down list and click the Nexxt
button, as shown in Fig.ASP-8.30:
22
Fig.ASP-8.30
3. Select the column name that you want to display on the Web Form from the Configure Data
23
Sectio
on in the Select pane, similar to how you have done earlier (Fig.ASP-8.31).
4. Click the Finissh button, as shown in Fig.ASP-8.31:
24
24
Fig.ASP-8.31
25
5. Click the smart tag of the Gridvie
ew control and select the LinqDataSource
e1 option from the
Choose Data Sourcce drop-down list.
Listing 8.4 shows the source code of the Default.aspx Web form after adding the controls and setting
their properties:
248
Database Controls
Listing 8.4
4: Code of the Default.aspx Web form of the Linqdatasourcecontrol Web site
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
DataSourceID="LinqDataSource1"> <Columns>
<asp:BoundField DataField="ProductID" HeaderText="ProductID"
ReadOnly="True" SortExpression="ProductID" />
<asp:BoundField DataField="ProductName" HeaderText="ProductName"
ReadOnly="True" SortExpression="ProductName" />
<asp:BoundField DataField="QuantityPerUnit" HeaderText="QuantityPerUnit"
ReadOnly="True" SortExpression="QuantityPerUnit" />
<asp:BoundField DataField="UnitPrice" HeaderText="UnitPrice"
ReadOnly="True" SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
ReadOnly="True" SortExpression="UnitsInStock" />
</Columns> </asp:GridView> </div>
<asp:LinqDataSource ID="LinqDataSource1" runat="server"
ContextTypeName="DataClassesDataContext" EntityTypeName=""
Select="new (ProductID, ProductName, QuantityPerUnit, UnitPrice, UnitsInStock)"
TableName="Products"> </asp:LinqDataSource> </form></body></html>
25 Press the F5 key to execute the Web site, as shown in Fig.ASP-8.32:
Fig.ASP-8.32
249
ASP.NET 4.5 in Simple Steps
The applicatioon uses an AccessDataSourcce control to retrieve data into the Web application from an
access file. This example uses a GridVie
ew control to query the AccessDataSourcce control to display the
data on the Web page by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWeb Site
e option from the menu bar. The New Web Sitte dialog box appears.
For selecting Accessdatasource control, you need to downgrade the .NET Framework 4.5 to
.NET Framework 4.0.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template option in the middle pane of the New Web Site
dialog box.
5. Click the Browse button for location, and enter the name of the Web site such as
Accessdatasourcecontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create Accessdatasourcecontrol Web site.
7. Add a Web form to the Accessdatasourcecontrol Web site.
250
Database Controls
8. Drag and drop one AccessDataSource controll and GridVie ew control from the Datta tab of the
Toolboxx on the Web form.
9. Create an MS Access file, name it as student.accd
db, and save it, for example, on the Desktop.
0. Right-click the application name and select the Add Existing Ite
10 em from the context menu.
11
1. Browse to the location where the Access file is saved. In this case, we have selected the student
file which is saved at the Desktop.
2. Click the Add button.
12
The file appears in the Solution Explore
er window, as shown in Fig.ASP-8.33:
Fig.ASP-8.33
13. Click the smart tag of the AccessDataSourcce control and select the Configure Data Sourcce option,
as shown in Fig.ASP-8.34:
13
Fig.ASP-8.34
251
ASP.NET 4.5 in Simple Steps
16
Fig.ASP-8.35
17
Fig.ASP-8.36
8. Click the Test Querry button. You can see the columns ID, Studname, Rolln
18 no and Classs
(Fig.ASP-8.37).
252
Database Controls
19
9. Click the Finissh button, as shown in Fig.ASP-8.37:
18
19
Fig.ASP-8.37
20
Fig.ASP-8.38
Listing 8.5 shows the source code of the Default.aspx Web form after adding the controls and setting
their properties:
Listing 8.5
5: Code of the Default.aspx Web form of the Accessdatasource application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div> <asp:GridView ID="GridView1" runat="server"
AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="AccessDataSource1">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False"
253
ASP.NET 4.5 in Simple Steps
DataFile="~/student.accdb"
SelectCommand="SELECT [ID], [Studname], [Rollno], [Class] FROM [Studtable]">
</asp:AccessDataSource> </form></body></html>
1. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.39:
21
Fig.ASP-8.39
254
Database Controls
255
ASP.NET 4.5 in Simple Steps
Let’s create an application to see how to work with the DataList control by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWeb Sitte option from the menu bar. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template template in the middle pane of the New Web
Site dialog box.
5. Click the Browse button for location, and enter the name of the Web site such as Datalistcontrol
in the text box to specify the location and name of the Web site.
6. Click the OK button to create Datalistcontrol Web site.
7. Add a Web Form to the Datalistcontrol Web site.
8. Drag and drop a DataList control and a SqlDataSource control on the Web Form from the Data
tab of Toolbox on the Web form, as shown in Fig.ASP-8.40.
9. Configure the SqlDataSource control with the Northwind database.
10. Click the smart tag of the DataList control and select the data source as SqlDataSource1 from the
Choose Data Source drop-down list, as shown in Fig.ASP-8.40:
10
Fig.ASP-8.40
11. Click the smart tag of DataList control and select the Auto Format option in the DataList Tasks, as
shown in Fig.ASP-8.41:
11
Fig.ASP-8.41
256
Database Controls
13
Fig.ASP-8.42
Listing 8.6 shows the source code of the Default.aspx Web form after adding the controls and setting
their properties:
Listing 8.6
6: Code of the Default.aspx Web form of the Datalistcontrol Web site
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html ><html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title></head><body> <form id="form1" runat="server"> <div>
<asp:DataList ID="DataList1" runat="server" CellPadding="4"
DataKeyField="ProductID" DataSourceID="SqlDataSource1" ForeColor="#333333">
<AlternatingItemStyle BackColor="White" />
<FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" />
<ItemStyle BackColor="#FFFBD6" ForeColor="#333333" />
<ItemTemplate> ProductID:
<asp:Label ID="ProductIDLabel" runat="server" Text='<%#Eval("ProductID") %>'/> <br />
ProductName:
<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Eval("ProductName") %>' />
<br /> UnitPrice:
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />
<br /> UnitsInStock:
<asp:Label ID="UnitsInStockLabel" runat="server" Text='<%# Eval("UnitsInStock") %>' />
<br /> UnitsOnOrder:
<asp:Label ID="UnitsOnOrderLabel" runat="server" Text='<%# Eval("UnitsOnOrder") %>' />
257
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.43
258
Database Controls
13
Fig.ASP-8.44
Listing 8.7 shows the source code of the Default.aspx Web form after adding the controls and setting
their properties:
259
ASP.NET 4.5 in Simple Steps
Listing 8.7
7: Code of the Default.aspx Web form of the Formviewcontrol Web site
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head><body>
<form id="form1" runat="server"><div>
<asp:FormView ID="FormView1" runat="server" AllowPaging="True"
BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None"
BorderWidth="1px"
CellPadding="3" CellSpacing="2" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1" GridLines="Both">
<EditItemTemplate>
ProductID:
<asp:Label ID="ProductIDLabel1" runat="server"
Text='<%# Eval("ProductID") %>' /><br />
ProductName:
<asp:TextBox ID="ProductNameTextBox" runat="server"
Text='<%# Bind("ProductName") %>' /><br />
UnitPrice:
<asp:TextBox ID="UnitPriceTextBox" runat="server"
Text='<%# Bind("UnitPrice") %>' /> <br />
UnitsInStock:
<asp:TextBox ID="UnitsInStockTextBox" runat="server"
Text='<%# Bind("UnitsInStock") %>' /> <br />
UnitsOnOrder:
<asp:TextBox ID="UnitsOnOrderTextBox" runat="server"
Text='<%# Bind("UnitsOnOrder") %>' /><br />
<asp:LinkButton ID="UpdateButton" runat="server" CausesValidation="True"
CommandName="Update" Text="Update" />
<asp:LinkButton ID="UpdateCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</EditItemTemplate>
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" />
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" />
<HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" />
<InsertItemTemplate> ProductName:
<asp:TextBox ID="ProductNameTextBox" runat="server"
Text='<%# Bind("ProductName") %>' /> <br />
UnitPrice: <asp:TextBox ID="UnitPriceTextBox" runat="server"
Text='<%# Bind("UnitPrice") %>' /> <br />
UnitsInStock:
<asp:TextBox ID="UnitsInStockTextBox" runat="server"
Text='<%# Bind("UnitsInStock") %>' /> <br />
UnitsOnOrder:
<asp:TextBox ID="UnitsOnOrderTextBox" runat="server"
Text='<%# Bind("UnitsOnOrder") %>' /> <br />
<asp:LinkButton ID="InsertButton" runat="server" CausesValidation="True"
CommandName="Insert" Text="Insert" />
<asp:LinkButton ID="InsertCancelButton" runat="server"
CausesValidation="False" CommandName="Cancel" Text="Cancel" />
</InsertItemTemplate>
<ItemTemplate> ProductID:
<asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>' />
<br /> ProductName:
260
Database Controls
Fig.ASP-8.45
261
ASP.NET 4.5 in Simple Steps
262
Database Controls
263
ASP.NET 4.5 in Simple Steps
Now, let’s create a Web application to learn the usage of the DetailsView control that display data
from a database by performing the following steps:
1. Open Visual Studio 20112.
2. Select FILENewWeb Sitte option from the menu bar. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Click the Browse button for location, and enter the name of the Web site such as
Detailsviewcontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create Detailsviewcontrol Web site.
7. Add a Web Form to the Detailsviewcontrol Web site.
8. Drag and drop a DetailsView control and a SqlDataSource control from the Data tab of the
Toolbox on the Web form, as shown in Fig.ASP-8.46:
Fig.ASP-8.46
9. Configure the SqlDataSource1 control to Northwind database as you have done earlier. The
SqlDataSource1 control now binds with the datasource (Fig.ASP-8.47).
264
Database Controls
10
Fig.ASP-8.47
265
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.48
266
Database Controls
The DataPager control is used to provide paging functionality to the data-bound controls, such as the
ListView control.
Table 8.18 lists some noteworthy properties of the DataPager class:
Table 8.18: Noteworthy Properties of the DataPager Class
Propertty Description
n
MaximumRows Obtains the maximum number of records that are displayed for each page of
data.
PagedControlID Obtains or sets the ID of the control that contains the data that will be paged by
the DataPager control.
PageSize Obtains or sets the number of records that are displayed for each page of data.
QueryStringField Obtains or sets the name of the query string field.
StartRowIndex Obtains the index of the first record that is displayed on a page of data.
TotalRowCount Obtains the total number of records that are retrieved by the underlying data
source object. This data source object is referenced by the associated data-bound
control.
Table 8.19 lists some noteworthy methods of the DataPager class:
Table 8.19 : Noteworthy Methods of the DataPager Class
Method
ds Description
n
DataBind Allows you to bind a DataPager control and all its child controls to a data
source
267
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.49
268
Database Controls
10
Fig.ASP-8.50
12
Fig.ASP-8.51
13
Fig.ASP-8.52
Listing 8.9 shows the source code of the Default.aspx Web form after adding the controls and setting their
properties:
269
ASP.NET 4.5 in Simple Steps
9: Code of the Default.aspx Web form of the Listview and Datapager control Web site
Listing 8.9
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head><form id="form1" runat="server">
<div>
<asp:ListView ID="ListView1" runat="server" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1">
<AlternatingItemTemplate>
<li style="background-color: #FFFFFF;color: #284775;">ProductID:
<asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>'
/><br />
ProductName:
<asp:Label ID="ProductNameLabel" runat="server"
Text='<%# Eval("ProductName") %>' /><br />
UnitPrice:
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%#
Eval("UnitPrice") %>' /><br /> UnitsInStock:
<asp:Label ID="UnitsInStockLabel" runat="server"
Text='<%# Eval("UnitsInStock") %>' /><br />
UnitsOnOrder:
<asp:Label ID="UnitsOnOrderLabel" runat="server"
Text='<%# Eval("UnitsOnOrder") %>' /><br /> </li>
</AlternatingItemTemplate>
<EditItemTemplate>
<li style="background-color: #999999;">ProductID:
<asp:Label ID="ProductIDLabel1" runat="server"
Text='<%# Eval("ProductID") %>' /> <br />
ProductName:
<asp:TextBox ID="ProductNameTextBox" runat="server"
Text='<%# Bind("ProductName") %>' /><br />
UnitPrice:
<asp:TextBox ID="UnitPriceTextBox" runat="server"
Text='<%# Bind("UnitPrice") %>' /><br />
UnitsInStock:
<asp:TextBox ID="UnitsInStockTextBox" runat="server"
Text='<%# Bind("UnitsInStock") %>' /><br />
UnitsOnOrder:
<asp:TextBox ID="UnitsOnOrderTextBox" runat="server"
Text='<%# Bind("UnitsOnOrder") %>' /><br />
<asp:Button ID="UpdateButton" runat="server" CommandName="Update"
Text="Update" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Cancel" /> </li>
</EditItemTemplate>
<EmptyDataTemplate>
No data was returned.
</EmptyDataTemplate>
<InsertItemTemplate>
<li style="">ProductName:
<asp:TextBox ID="ProductNameTextBox" runat="server"
Text='<%# Bind("ProductName") %>' /> <br />UnitPrice:
<asp:TextBox ID="UnitPriceTextBox" runat="server"
Text='<%# Bind("UnitPrice") %>' />
<br />UnitsInStock:
<asp:TextBox ID="UnitsInStockTextBox" runat="server"
Text='<%# Bind("UnitsInStock") %>' />
<br />UnitsOnOrder:
<asp:TextBox ID="UnitsOnOrderTextBox" runat="server"
Text='<%# Bind("UnitsOnOrder") %>' /> <br />
<asp:Button ID="InsertButton" runat="server" CommandName="Insert"
270
Database Controls
Text="Insert" />
<asp:Button ID="CancelButton" runat="server" CommandName="Cancel"
Text="Clear" /> </li>
</InsertItemTemplate>
<ItemSeparatorTemplate><br />
</ItemSeparatorTemplate>
<ItemTemplate>
<li style="background-color: #E0FFFF;color: #333333;">ProductID:
<asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>'
/>
<br /> ProductName:
<asp:Label ID="ProductNameLabel" runat="server"
Text='<%# Eval("ProductName") %>' /> <br />
UnitPrice:
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>' />
<br />
UnitsInStock:
<asp:Label ID="UnitsInStockLabel" runat="server" Text='<%#
Eval("UnitsInStock") %>' />
<br />
UnitsOnOrder:
<asp:Label ID="UnitsOnOrderLabel" runat="server" Text='<%#
Eval("UnitsOnOrder") %>'
/><br /></li>
</ItemTemplate>
<LayoutTemplate>
<ul ID="itemPlaceholderContainer" runat="server"
style="font-family: Verdana, Arial, Helvetica, sans-serif;">
<li runat="server" id="itemPlaceholder" />
</ul>
<div style="text-align: center;background-color: #5D7B9D;font-family:
Verdana, Arial, Helvetica, sans-serif;color: #FFFFFF;"></div>
</LayoutTemplate>
<SelectedItemTemplate>
<li style="background-color: #E2DED6;font-weight: bold;color:
#333333;">ProductID:
<asp:Label ID="ProductIDLabel" runat="server" Text='<%# Eval("ProductID") %>'/>
<br />
ProductName:
<asp:Label ID="ProductNameLabel" runat="server"
Text='<%# Eval("ProductName") %>' />
<br />
UnitPrice:
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Eval("UnitPrice") %>'/> <br />
UnitsInStock:
<asp:Label ID="UnitsInStockLabel" runat="server"
Text='<%# Eval("UnitsInStock") %>' /><br />
UnitsOnOrder:
<asp:Label ID="UnitsOnOrderLabel" runat="server"
Text='<%# Eval("UnitsOnOrder") %>' /><br />
</li>
</SelectedItemTemplate>
</asp:ListView>
<asp:DataPager ID="DataPager1" runat="server" PagedControlID="ListView1">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="True"
ShowNextPageButton="False" ShowPreviousPageButton="False" />
<asp:NumericPagerField />
<asp:NextPreviousPagerField ButtonType="Button"
ShowLastPageButton="True”
ShowNextPageButton="False" ShowPreviousPageButton="False" />
</Fields>
</asp:DataPager> </div>
271
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.53
272
Database Controls
Let’s create a Web application to learn how to display data using the Repeater control by performing the
following steps:
1. Open Visual Studio 201
12.
2. Select FILENewWe eb Sitte option from the menu bar. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog
box.
5. Click the Browse e button for location, and enter name of the Web site such as Repeatercontrol in
the text box to specify the location and name of the Web site.
6. Click the OK button to create the Repeatercontrol Web site.
7. Add a Web Form to the Repeatercontrol Web site.
8. Drag and drop a Repeater control and a SqlDataSource control from the Data tab of the Toolbox
on theWeb Form (Fig.ASP-8.54).
9. Configure the SqlDataSource control to a Northwind database, similar to how you have done
earlier.
10. Click the smart tag of the Repeater control (Fig.ASP-8.54).
11. Select the data source as SqlDataSource1 from the Choose Data Source drop-down list, as
shown in Fig.ASP-8.54:
10
Fig.ASP-8.54
12. Replace the code in the source view of the Default.aspx page with the code given in Listing 8.10:
Listing 8.10: Code of the Default.aspx Web form of the Repeatercontrol application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title></head>
<body>
273
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.55
274
Database Controls
Fig.ASP-8.56
275
ASP.NET 4.5 in Simple Steps
Table 8.22 lists the some noteworthy events of the Chart class:
Table 8.22: Noteworthy Events of the Chart Class
Eventts Descriptio
on
Click Invokes when the control is clicked
Customize Invokes before the chart Image is drawn
DataBound Invokes when the control is DataBound
Disposed Invokes when the control is disposed
PostPaint Invokes when the chart element is painted
Table 8.23 lists the some noteworthy methods of the Chart class:
Table 8.23: Noteworthy Methods of the Chart Class
Method
ds Descriptio
on
CopyBaseAttributes Copies the properties that are not encapsulated by the style object from the
specified Web server control to the Web server control that this method is called
from .This method is primarily used by the control developers.
MergeStyle Copies any nonblank elements of the specified style to the Web control, but will
not overwrite any existing style elements of the control. This method is primarily
used by the control developers.
Paint Draws the chart image in the graphics.
RenderBeginTag Writes the opening tag of the specified markup element to the output stream.
RenderEndtag Writes the end tag of a markup element to the output stream.
Let’s create an application to learn the usage of the chart control by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWe
eb Sitte option from the menu bar. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C#
Web option in the left pane of the New Web Site dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Web Site dialog
box.
5. Click the Browsee button for location, and enter name of the Web site such as Chartcontrol in the
text box to specify the location and name of the Web site.
6. Click the OK button to create the Chartcontrol Web site.
7. Add a Web Form to the Chartcontrol Web site.
8. Drag and drop a Chart control and a SqlDataSource control from the Data tab of the Toolbox on
the Web Form (Fig.ASP-8.57).
9. Add two Label control to the Web Form and set the Text property of Label1 as UNITS ON ORDER
and Label2
2 as UNITS IN STOCK, as shown in Fig.8.57:
276
Database Controls
Fig.ASP-8.57
10.. Configure the SqlDataSourcce control to a Northwind database, similar to how you have done
earlier.
11. Click the smart tag of the Charrt control and select the data source as SqlDataSource
e1 from the
drop-down list beside the Choose Data Source e in the Chart Taskks (Fig.ASP-8.58).
12. Select X Value Membe er drop-down list as UnitsOnOrde er and Y Value Memberrs drop-down list as
UnitsInStocck in the Series1 Data Memberrs pane in the Chart Taskks. You can select type of chart
from the Chart Typ pe drop-down list, as shown in Fig.ASP-8.58:
12
Fig.ASP-8.58
Listing 8.11 shows the source code of the Default.aspx Web form after adding the controls and setting the
properties:
Listing 8.11
1: Code of the Default.aspx Web form of the Chartcontrol application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<%@ Register assembly="System.Web.DataVisualization, Version=4.5.0.0, Culture=neutral,
PublicKeyToken=31bf3856ad364e35" namespace="System.Web.UI.DataVisualization.Charting"
tagprefix="asp" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"> <title></title></head>
277
ASP.NET 4.5 in Simple Steps
Fig.ASP-8.59
Similarly, you can create different charts based on different styles and columns values. With this, you
have come to the end of this chapter. Let’s now summarize what you have learnt in this chapter.
SUMMARY
In this chapter, you have learnt about:
Concept of a database access by using SQL and integrating databases with .NET applications
How to use the ADO.NET features in ASP.NET Web applications
How to configure and use various data-source controls, such as the SqlDataSourcce, XmlDataSourcce,
ObjectDataSourcce, and LinqDataSourcce controls, in a Web application
Various data-bound controls, such as the DataLisst, FormVie ew, ListVie
ew, Charrt control, and
DataPage er controls, for displaying the data from the database
278
CHAPTER 9
Master Pages and Themes
Introduction
The real-world Web applications, such as applications for online banking, shopping, and reservation,
should accommodate a consistent look and feel, which enriches users’ experience of visiting Web sites.
In ASP.NET 4.5, master pages, themes, and Cascading Style Sheet (CSS) are available, which facilitate
developers in giving a consistent look and feel to Web applications.
Master pages help to incorporate visual consistency in Web applications. Earlier, we used to add
controls and layout on each and every page manually, which was a time-consuming process. Now, with
the help of master pages, we can define the layout of a Web page once and all the other pages of the
Web application can inherit that layout in addition to possessing their own content. A template page is
created in the master page, based on which all the other pages of a Web application are derived. This
helps to maintain consistency in terms of look and feel across all the Web pages of a Web application
or website. In ASP.NET 4.5, you can also use CSS and themes to maintain consistency in design of your
Web application. CSS and themes are generally used to give efficient appearance to Web pages.
Need for master page, themes, and CSS arises when you want to create Web pages that contain some
common elements. For example, you want to create a website for your company in which all the Web
pages must have a header showing the logo of the company. You can create this website by using the
concept of master pages. In this chapter, you learn about master pages, themes, and CSS.
Let’s start by learning about master pages.
Fig.ASP-9.1
The master and content pages are combined together to generate a single page called combined page
that inherits the properties from both the pages.
Now, let’s learn how to use master pages in a website. Before using a master page, you first need to
learn how to add it in the application. Let’s perform the following steps to open a master page and then
use it in a Web application:
1. Open Visual Studio 201 12.
New
2. Select FILE Web Site. The New Web Site dialog box appears.
280
Master Pages and Themes
Templates
3. Select Installed Visual C# option in the left pane and select the ASP.NET Empty
Web Site template in the middle pane of the New Web Site dialog box.
4. Enter Mymaster as the name of the ASP.NET Empty Web Site in the Web location field and click
the OK button.
5. Right-click Mymaster in the Solution Explorer window and select the Add New Item option from
the context menu.
The Add New Item dialog box appears (Fig.ASP-9.2).
6. Select Visual C# in the left pane and Master Page in the middle pane of the Add New Item
dialog box (Fig.ASP-9.2).
7. Click the Add
d button, as shown in Fig.ASP-9.2:
Fig.ASP-9.2
The MasterPage.master master page appears in the Solution Explorer window, as shown in
Fig.ASP-9.3:
Fig.ASP-9.3
8. Add a Label control in the master page and set its Text property to WELCOME TO ASP.NET4.5.
9. Right-click MasterPage.master in the Solution Explorer window and select the Add Content Page
option from the context menu, as shown in Fig.ASP-9.4:
281
ASP.NET 4.5 in Simple Steps
Fig.ASP-9.4
12
Fig.ASP-9.5
13
Fig.ASP-9.6
After adding the control and setting its properties, Listing 10.1 shows the Source code of the
MasterPage.maste e r:
Listing 10.1
1: Showing the Code of MasterPage.master
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs"
Inherits="MasterPage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
282
Master Pages and Themes
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
<asp:Label ID="Label1" runat="server" Text="WELCOME TO
ASP.NET4.5"></asp:Label>
</asp:ContentPlaceHolder>
</div>
</form>
</body>
</html>
4. Press F5 to execute the Web application in a browser, as shown in Fig.ASP-9.7:
14
Fig.ASP-9.7
The text of Labeel control which is present on the master page appears on Default.aspxx. Any changes
made on the master page appear on its default pages or content pages.
Let’s discuss nested master pages.
Fig.ASP-9.8
Now, let’s perform the following steps to learn to create nested master pages:
1. Open Visual Studio 201
12.
2. Select FILENewWeb Site e option. The New Web Sitte dialog box appears.
Templates
3. Select Installed Visual C# option in the left pane and select the ASP.NET Empty
Web Site template in the middle pane of the New Web Site dialog box.
4. Enter Nestedmasterpage as the name of the ASP.NET Empty Web Site in the Web location field
and click the OK button.
283
ASP.NET 4.5 in Simple Steps
Do not add the preceding code snippet in the ContentPlaceHolder tag of MasterPage.master.
15
Fig.ASP-9.9
16. Press the F5 key to execute the Nestedmasterpage Web application, as shown in Fig.ASP-9.10:
Fig.ASP-9.10
284
Master Pages and Themes
Fig.ASP-9.11
Exploring Themes
Themes help you to maintain a consistent look and feel across all or several pages of your website.
Themes are used when you want to keep the style and layout information files separate from other
website files. A theme is a collection of settings that define the look of controls and Web pages. You can
apply a theme on all the pages of your Web application to maintain a consistent appearance. Themes
can include images and skin files; the skin files set the visual properties of ASP.NET controls.
285
ASP.NET 4.5 in Simple Steps
A skin file is a file with the .skin extension that contains property settings for individual controls, such
as butto
on, textbox, or labe el. You can either define styles for each control in different skin files or for all
the controls in a single skin file. Themes are of two types, which are as follows:
Page theme e: Contains the skins of a control, style sheets, graphic files, and other resources inside
the subfolders of the App_Theme folder that is present in the Solutio on Explorerr window. It is
applied to a single page of a Web application. For different themes, separate subfolders are
created in the App_Theme folder.
Global themee: Refers to a theme that is applied to all the Web applications on a Web server and
includes property settings, style sheets settings, and graphics. This theme allows you to maintain
all the Web applications on the same Web server and define the same style for all the Web
pages. Global themes are stored in the Themes folder and can be accessed by any website.
Let’s now learn how to use themes in a Web application.
Using Themes
In this section, we create a Web application to learn the use of themes. Let’s perform the following steps
to create a Web application and use themes in it:
1. Open Visual Studio 20112.
New
2. Select FILE Web Site option.
Templates
3. Select the Installed Visual C# option in the left pane and select the ASP.NET Empty
Web Site template from the middle pane of the New Web Site dialog box.
4. Enter Themewebsite as the name of the ASP.NET Empty Web Site in the Web location field and
click the OK button.
5. Add a Web form Default.aspx to the Themewebsite Web application.
6. Right-click the Themewebsite Web application in the Solution Explorer window and select
AddAdd ASP.NET FolderTheme from the context menu to add the App_Themes folder in the
Solution Explorer window, as shown in Fig.ASP-9.12:
Fig.ASP-9.12
A subfolder named Theme1 is automatically created inside the App_Themes folder. In our case,
we have renamed the Theme1 folder to Themecontrol (Fig.ASP-9.13).
7. Right-click the Themecontrol folder and select the AddAdd New Item option from the context
menu, as shown in Fig.ASP-9.13:
286
Master Pages and Themes
Fig.ASP-9.13
Fig.ASP-9.14
12
Fig.ASP-9.15
After setting the properties and adding the controls, Listing 10.2 shows the source code of the
Default.aspx Web form:
Listing 10.2
2: Showing the Code of the Default.aspx Web Form
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" Theme="Themecontrol" %>
287
ASP.NET 4.5 in Simple Steps
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" />
</div>
</form>
</body>
</html>
The style properties of the skin file are not visible at design time (you can see them only at runtime).
3. Press the F5 key to execute the Web application in a browser, as shown in Fig.ASP-9.16:
13
Fig.ASP-9.16
Fig.ASP-9.16 shows that the style properties of the skiin file are incorporated in the Default.asp
px page.
Fig.ASP-9.17
288
Master Pages and Themes
289
ASP.NET 4.5 in Simple Steps
12
Fig.ASP-9.18
13. Click the Inversse link to change the theme, as shown in Fig.ASP-9.19:
13
Fig.ASP-9.19
Using CSS
In this section, we create a Web application to learn of the use of CSS. Let’s perform the following steps
to create a Web application and use CSS in it:
1. Open Visual Studio 201 12.
New
2. Select FILE Web Site option.
Templates
3. Select Installed Visual C# option in the left pane and select the ASP.NET Empty
Web Site template in the middle pane of the New Web Site dialog box.
290
Master Pages and Themes
4.. Enter CSSwebsitte as the name of the ASP.NET Empty Web Sitte in the Web locatio on field and click
the OK button.
5.5 Add a Web Form to the CSSwebsitte Web application.
6. Right-click the CSSwebsitte Web application and select the Add New Ite em option from the context
menu. The Add New Ite em dialog box appears.
7. Select Visuaal C# in the left pane and Stylle Sheett in the middle pane of the Add New Ite
em dialog
box.
8. Click the Add button.
9. Add the following code snippet in StyleSheet.css:
.body
{
background-color:Gray;
}
.txt
{
background-color:Yellow;
border-color:Black;
font-style:italic;
font:Bold;
}
.btn
{
font-size: small;
font-style: oblique;
color: #800080;
font-family: 'Gill Sans MT';
text-decoration: underline;
background-color: #96CFFA
}
.lbl
{
background-color: #96CFFA;
border: thin dashed #008080;
font-family: 'Times New Roman' , Times, serif;
font-size: smaller;
}
0. Add the code, given in Listing 10.4, in Default.aspx Web form:
10
Listing 10.4: Showing the Code of the Default.aspx Web Form
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="StyleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server" class="body">
<div>
<br />
<br />
<br />
<asp:Label ID="Label1" runat="server" Text="Enter your First name:"
CssClass="lbl"></asp:Label>
<asp:TextBox ID="TextBox1" runat="server" CssClass="txt" Width="196px"
Height="24px"></asp:TextBox><br/><br/>
<asp:Label ID="Label2" runat="server" Text="Enter your Last Name:"
CssClass="lbl"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server" CssClass="txt" Width="196px"
Height="25px"></asp:TextBox>
291
ASP.NET 4.5 in Simple Steps
11
Fig.ASP-9.20
292
CHAPTER 10
Introducing ASP.NET AJAX
Introduction
You are already familiar with the Web applications that use the postback model to refresh the page
content. This postback model has been in use since the beginning of the Internet. However,
considering today’s scenario, developers program Web sites that do not require the postback model.
The developers update the Web page information faster, without page flicker and without interrupting
user interactions, which was not possible when the postback model is used. This is possible with the
help of Asynchronous Javascript and XML (AJAX). In AJAX, a request made to a server to update the
Web page information takes place in the background; the user does not even get a hint of when a new
data is retrieved from the server. The user just gets the new content on the Web page. The call that takes
place in the background is called an Asynchronous call. Moreover, AJAX updates only a
particular portion of a Web page where the updation of information is required; this helps in updating
information on the Web pages faster.
In this chapter, you learn about ASP.NET AJAX controls approach and its comparison with traditional
controls approach of creating Web sites. You then go through the AJAX Extension controls in Visual
Studio 2012 and create an AJAX-enabled Web site.
ASP.NET AJAX
ASP.NET AJAX, formerly code-named as Atlas, is a completely new approach for developing Web sites.
It is developed by Microsoft and available with ASP.NET 4.5 for implementing AJAX functionalities.
Using a set of client-script libraries, ASP.NET allows the developers to create AJAX-enabled Web sites
that communicate with the server asynchronously and are also capable to update only a specified
portion of the Web page without refreshing the whole page. The transfer of data from the server is
ASP.NET 4.5 in Simple Steps
carried out through the Extensible Markup Language/Hypertext Transfer Protocol (XMLHTTP) in the form
of packets by using XML and JavaScript Object Notation (JSON), which are platform-independent
standards for exchanging data over the network.
294
Introducing ASP.NET AJAX
In the preceding code snippet, you can observe that two Button controls are activated.
295
ASP.NET 4.5 in Simple Steps
296
Introducing ASP.NET AJAX
297
ASP.NET 4.5 in Simple Steps
In this chapter, the ScriptManagerProxy control is not discussed, as it requires some advance
programming techniques.
298
Introducing ASP.NET AJAX
4. Specify the location and name of the application in the Web location combo box. In our case, we
have provided the name as AJAXExample.
5. Click the OK button to save the settings.
6. Open the Solution Explorer window and right-click the application name.
7. Select the Add New Item option from the context menu.
The Add New Item dialog box appears.
8. Select the Visual C#Web Form option from the middle pane in the dialog box.
9. Click the Add button in the dialog box.
10. Replace the source file of the Default.aspx Web form, as given in Listing 11.1, to set the AJAX
controls on the Web form:
Listing 11.1: Code of the Default.aspx Web form in a AJAXWebSite application
299
ASP.NET 4.5 in Simple Steps
11
Fig.ASP-11.1
12. Add the following code snippet in the Click event of the Button1 control:
protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(5000);
Label1.Text = "Demonstration on UpdateProgress Control taken place last time at" +
System.DateTime.Now.ToLongTimeString();
}
13. Press the F5 key to run the Web site. The output is shown in Fig.ASP-11.2.
14. Click the Get Time button (Fig.ASP-11.2).
The UpdateProgress control appears, displaying the message as Updation is in progress, as shown in
Fig.ASP-11.2:
14
Fig.ASP-11.2
As soon as the system’s current time displays on the Web page, the UpdationProgress control
disappears, as shown in Fig.ASP-11.3:
Fig.ASP-11.3
Moreover, you can notice that there is no page refresh to display the time on the Web page. This
happens because of AJAX functionality, which calls servers asynchronously to update the page content.
300
Introducing ASP.NET AJAX
You have to download and include the jquery-1.3.2.js library to run the application. We
have included this library in the Scripts folder of this application.
7. Replace the code with the following code in the Source view of the Web form (Default.aspx).
Listing 11.2 shows the source code:
Listing 11.2: Code of Default1.aspx of the JQuerywebapplication
<script type="text/javascript">
$("input").focus(function () { $(this).css("background-color", "green"); });
$("input").ready(function () { alert("Welcome to the world of jquery"); });
$('#Button1').click(function () { $(this).css('background-color',
'red').animate({ width: '100px', height: '80px' }) });
$('h2').css('font-size', '40px').fadeOut(5000);
</script>
</div>
</form>
</body>
</html>
301
ASP.NET 4.5 in Simple Steps
8. Press the F5 key to view the output of the Web application (Fig.ASP-11.4).
The alert box appears (Fig.ASP-11.4).
9. Click the OK button, as shown in Fig.ASP-11.4:
Fig.ASP-11.4
You can see that the text starts fading out from the Web form, as shown in Fig.ASP-11.5:
Fig.ASP-11.5
10
11
Fig.ASP-11.6
With this, we have come to the end of this chapter. Let’s now summarize the points you have learned in
this chapter.
SUMMARY
In this chapter, you have learned about:
How does an AJAX works and its implementation in ASP.NET
The difference between a traditional Web site and an AJAX-enabled Web site
The new features of AJAX Extension controls shipped with Visual Studio 2012
The implementation of AJAX and jQuery in a Web applications
302
CHAPTER 11
Working with Silverlight
Applications
Introduction
Initially, the content in the Web pages was mostly static, as Web sites were developed by using only
Hypertext Markup Language (HTML). Gradually, with the advent of other new technologies and
languages, such as Cascading Style Sheets (CSS), Extensible Hypertext Markup Language (XHTML),
Adobe Flash, and JavaScript, the development of interactive Web pages has been made possible.
However, some of these technologies are expensive to deploy, and have inadequate performance and
also insufficient compatibility with different platforms. To overcome these limitations, Microsoft
introduced a new Web application framework known as Silverlight, which is an inexpensive small plug-
in software that can work in a cross-platform, cross-browser, and cross-device environment.
Silverlight is a Web-based technology that allows you to develop Web applications that contain high
multimedia content and eye-catching visual effects. Silverlight is an integration of the rich user interface
(UI) of desktop applications and the Web languages, such as HTML and JavaScript. The first version of
Silverlight introduced by Microsoft was Silverlight 1.0 and was released in 2007, which was based on
the JavaScript application model. You could incorporate the functionality of Silverlight 1.0 in the .NET
framework 2.0 and Visual Studio 2005 applications. The Silverlight 2.0 version is supported by Visual
Studio 2008 Service Pack 1 (SP1). The Silverlight 3.0 and 4.0 versions are supported by Visual Studio
2010. The latest version of Silverlight is Silverlight 5.0, which is fully supported by Visual Studio 2012.
In this chapter, you will learn about scenarios where Silverlight can be used, the new features of
Silverlight, and its architecture. You will also learn how to develop an application by using Silverlight
framework.
Controls
Some new controls and enhancements in the previous controls in Silverlight 5 are as follows:
Pivot Vieweer: Allows you to display a massive quantity of data at a time. This control enables you
to visualize data in a way so that you can observe trends and patterns present in the data.
Moreover, it makes browsing of data easier and faster.
Drawing Surface:: Specifies an area that is used for rendering as well as composing 3D graphics.
304
Working with Silverlight Applications
Items Control Text Search:: Allows you to search a list of items in ListBox or ComboBox entered
using Keyboard. You can set the TextPath property to identify an item in the ListBox or
ComboBox. The list will scroll to find the specified item.
Dialog Changes:: Allows you to have improvements in controls, such as OpenFileDialo og and
SaveFileDialoog that were present in the previous versions of Silverlight. For example, the new
property named InitialDirectorry can be used to provide initial directory while opening a file and
another new property named DefaultFileNam me can be used to specify a default name for a file
when the file is saved.
Media
Silverlight 5 includes new changes in the section of Media which are as follows:
Sound Effectss: Include new classes in Silverlight 5. These new classes can be used by including
the Microsofft.X
Xna.F
Frameworrk.A
Audiio namespace in the application. You can use the SoundEffect
class for low-latency sound.
Variable Playback Ratte: Allows you to control the playback rate of any media using a property
and an event, such as PlaybackRate and RateChanged, respectively.
Application-Restricted Media:: Ensures the usage of content only by the authorized Silverlight
applications. It ensures the content by keeping it under Digital Rights Management (DRM).
Key Rotation
n: Provides support for Live TV scenarios having policies and licenses.
Remote Control Support:: Allows the controlling of playback of media.
Graphics
Silverlight 5 includes new changes in the section of graphics which are as follows:
3D graphicss: Include improvements in the architecture of graphics stack to include new features,
such as 3D drawn controls, data visualizers, 3D charts, scatter points, geographical overlays, and
3D games and simulations. It also includes support for hardware accelerated 3D graphics.
Silverlight 5 now includes libraries of the XNA Games Studio 4.0 graphics to speed up the
process of 3D graphics programming. Rendering of targets, XNA built-in effects, and surface
composition settings for depth/stencil buffers and multi-sample anti-aliasing are included in this
library.
Text
Silverlight 5 includes new changes in the section of Text, which are as follows:
Character Spacing:: Support for increasing and decreasing character spacing by using the
CharacterSpacing property, which is available in the TextBlock, TextElement, and
Control classes.
Inter-line Spacing:: Support for increasing and decreasing line spacing by using the LineHeight
and LineStackingStrategy properties, which are available in the TextBox, Block,
RichTextBox, and TextBlock classes.
RichTextBlock and Displaying Overflow Content:: Support for displaying rich text by using the
RichTextBlock control. Sometimes, the RichTextBlock control is inadequate for holding
305
ASP.NET 4.5 in Simple Steps
the content that you want to display. In such cases, you can use the RichTextBlockOverflow
control for displaying the content.
Text Clarity:: Includes features that improve text clarity. For example, it supports OpenType fonts
and pixel-snapped text. The OpenType font provides a rich collection of advanced typographic
features, such as stylistic alternates and swashes. Using pixel-snapping, blurred and semi-
transparent edges of text are removed to improve text clarity.
Trusted Applications
Silverlight 5 provides improved support for trusted applications, which are as follows:
Access File Syste
em: Allows accessing of local file system without requiring any special permission.
Multiple Windowss: Allows creation of multiple windows for an application when running outside
the browser by creating instances of the Window class (in the previous versions of Silverlight,
trusted applications used to have only one window).
In-Browseer: Allows running of trusted application inside the browser which simplifies enterprise
deployment and application updates. It also allows you to use some previous features of out-of-
browser inside the browser which includes Web Browser and Notification Window classes.
Call Windows APIs:: Enables you to call unmanaged code and libraries from the managed code.
Printing
Silverlight 5 includes support of vector printing, thereby improving performance as well as quality of
printing.
User Interface
An improvement in user interface is as follows:
Detecting Double-Clickss: Allows detection of double-click of mouse by using the ClickCount event
data property. Two consecutive mouse clicks can be considered as a double-click only when the
mouse button is pressed twice within some defined time duration, say 2 seconds. This time
duration can be adjusted by a user by changing operating system settings. The ClickCount
property detects double-clicks based on a time duration, which is defined within the operating
system settings.
Data
The improvements in Silverlight 5 in data section are as follows:
Data Binding g: Supports for specifying breakpoints in a program that includes data binding. This
feature makes it easier to locate and remove errors that might be present in a data binding. A
break is introduced in a program at every breakpoint. At the break, you can use the BindingState
property (in Locals window) to examine the complete state information of a binding, such as
BindingExpression, data source, and current binding. You can also specify a test condition that
can be evaluated and checked to decide where and when to introduce a breakpoint in the
program. Silverlight 5 also includes some data-binding enhancements, which allows you to do
the following:
Allows you to use styles in data binding by using the Setter.Valu
ue property.
306
Working with Silverlight Applications
Allows you to bind to ancestors in the visual tree by setting the Binding.RelativeSourcce
property to FindAncesto
or.
Allows you to relate bound objects implicitly to data templates by specifying type instead of
specifying template name explicitly. This can be done by setting the DataTemplate.DataTyp pe
property. This property is set for each implicit template instead of specifying x:Ke
ey values.
Allows you to bind to dynamically generated properties by implementing the
ICustomTypeProviderr interface.
Allows you to detect change in the data context for an element by using the
FrameworkElement.DataContextChange ed event.
Allows you to bind data with TextBox easily. For this purpose, an
UpdateSourceTrigger.PropertyChange ed enumeration is added in Silverlight. Using this
enumeration you can detect modifications before the focus is lost from the TextBox.
XAML
Silverlight 5 includes enhancements in XAML by providing features, such as support for creating custom
markup extensions by implementing the IMarkupExtension<T> interface and the ProvideValue()
method. These custom markup extensions can be understood by Silverlight XAML parser. In Silverlight 5,
you can implement a same markup extension actions to the x:Type markup extension related to WPF
XAML. Moreover, in Silverlight 5, the structures, such as CornerRadius, Thickness, Size, and Rect support
attribute syntax on properties unlike the previous version of Silverlight.
Performance Improvements
The improvements help in enhancing the performance of Silverlight applications are as follows:
Supports 64-bit browsers, such as Safari and Firefox.
Provides a background thread for networking that decreases network delays and improves
performance.
Supports for the Just-In-Time (JIT) compiler with multiple cores.
Advancements in XAML parser for user controls and resource dictionaries.
Increased performance of hardware decoding and presentation of H.264 media for unprotected
content.
Silverlight Architecture
You know that the primary components of Silverlight include HTML, JavaScript, XAML, and .NET framework.
While developing Silverlight applications, you will be using a combination of varied features of these
components. These individual components are incorporated in Silverlight, as shown in Fig.ASP-11.1:
307
ASP.NET 4.5 in Simple Steps
Fig.ASP- 11.1
Fig.ASP-11.1 shows that Silverlight 5 is a blend of different technologies and features. Silverlight has two
main components, namely, .NET framework for Silverlight and the core presentation framework.
Now, let’s discuss about these two components in detail in the following:
The .NET framework for Silverligh ht: Offers some of the basic functionalities, such as common
type system, type checking, debugging, and garbage collection. The .NET framework for
Silverlight component also offers certain class libraries that allow you to work with strings,
collections, generics, reflection, and I/O. Some of the class libraries of Silverlight also provide a
wide range of Windows Presentation Foundation (WPF) controls, such as Button, TextBox, and
RadioButton. The .NET framework for Silverlight component also allows you to integrate data in
Silverlight applications through XML, LINQ, and XLINQ, and manipulate it through serialization.
The .NET framework in Silverlight component also enables you to easily access data and services
at remote locations through Windows Communication Foundation (WCF). In addition, you can
use Hypertext Transfer Protocol Secure (HTTPS) objects, cross-domain HTTP requests, Really
Simple Syndication (RSS) feeds, JavaScript Object Notation (JSON), and Simple Object Access
Protocol (SOAP) services in the Silverlight applications.
The Core Presentation frameworkk: Offers the features and services for designing the UI of
Silverlight applications through controls, styles, templates, 2D vector graphics, animations, and
multimedia. This component also allows you to incorporate user input and interactivity through
various input devices, such as the mouse and the keyboard. It also allows you to bind data with
various controls, and specify the UI layout of the Silverlight applications. Moreover, you can also
manage the digital rights of the multimedia content used in your Silverlight applications through
this component. The XAML parser for processing the XAML content in Silverlight applications is
also provided by the core presentation framework.
308
Working with Silverlight Applications
5
6
Fig.ASP-11.2
309
ASP.NET 4.5 in Simple Steps
Fig.ASP-11.3
11
Fig.ASP-11.4
310
Working with Silverlight Applications
12
13
Fig.ASP-11.5
15
Fig.ASP-11.6
311
ASP.NET 4.5 in Simple Steps
16
Fig.ASP-11.7
7. Add the MediaElement control from the Toolbox and set the x:Nam
17 me property as Mediaplayer,
Sourcce as Wildlife.wmv, AutoPla
ay as False, Margiin as 28,28,36,34, and HorizontalAlignmen
nt as
Center in the Properties window.
8. Add the three button controls and set the Conten
18 nt property of the Button
n1 control as Pla
ay, Button
n2
control as Pausse, and Button
n3 control as Sto
op in the Properties window.
9. Double-click the button1 control and add the following code snippet in the Click event:
19
privatevoid button1_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Play();
}
0. Double-click the button2 control and add the following code snippet in the Click event:
20
privatevoid button2_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Pause();
}
1. Double-click the button3 control and add the following code snippet in the Click event:
21
privatevoid button3_Click(object sender, RoutedEventArgs e)
{
MediaPlayer.Stop();
}
Listing 11.1 shows the source code of the MainPage.xaml page after adding the controls and setting
their properties:
312
Working with Silverlight Applications
Listing 11.1
1: Code of the MainPage.xaml Page in the Silverlight video application
<UserControl x:Class="Silverlightvideoapplication.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400">
</UserControl>
2. Press the F5 key to view the output in the browser, as shown in Fig.ASP-11.8:
22
Fig.ASP-11.8
You can click the Play, Pause, and Stop button to play, pause, and stop the video, respectively.
313
ASP.NET 4.5 in Simple Steps
With this, you have come to the end of this chapter. Let’s now summarize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
Introduction of Silverlight and its architecture.
New features of Silverlight 5.0 in ASP.NET 4.5.
Creating a Silverlight application in ASP.NET 4.5.
314
CHAPTER 12
Windows Presentation
Foundation
Introduction
Earlier, you needed to add separate functionalities in your operating system to display two-dimensional
(2D) and three-dimensional (3D) graphics in your Web application. To overcome this problem,
Microsoft introduced Windows Presentation Foundation (WPF), which acts as a common foundation for
displaying all the multimedia elements. One of the biggest advantages of WPF is that you can easily
separate the Design view from the Code view. As WPF is based on what you see is what you get
principle, you can directly view your code in the Design view. WPF applications can only be created
using the Extensible Application Markup Language (XAML) language and are also known as
XAML browser applications. The XAML also allows you to work with controls in a WPF
application, such as adding controls, equipping them with additional functionalities, and
defining the hierarchical structure of the controls.
The controls in WPF are user-interactive elements and are derived from the System.Windows.Controls,
Microsoft.Win32, and System.Windows.Documents namespaces. The base classes of WPF controls are
the FrameworkElement class and the Control class. The Control class is a public base class derived from
the FrameworkElement class. Unlike the controls of Windows applications, you can modify the look of a
WPF control by just changing their respective XAML code. WPF applications can only be created using
the XAML language; they are also known as XAML browser applications.
In this chapter, you will learn about new features included in WPF 4.5 in ASP.NET 4.5. You will also
learn how to create an XAML browser application using various WPF controls. The chapter then
discusses the technique of typography, which is used to apply various styles and formats to the content
in WPF. You will next learn about some WPF controls in ASP.NET 4.5 and their usage in a WPF
application.
Let’s begin with new features of WPF 4.5.
ASP.NET 4.5 in Simple Steps
316
Windows Presentation Foundation
Moreover, it provides support for validating cross-property errors, entity-level errors, and multiple errors
for a single property.
317
ASP.NET 4.5 in Simple Steps
thread. Therefore, a non-UI thread can be used in the background to process the data collection
received from a data source. While displaying data, using a non-UI thread in the background makes
the UI thread more responsive and improves its performance.
318
Windows Presentation Foundation
319
ASP.NET 4.5 in Simple Steps
New
2. Select FILE Project option from the menu bar.
The New Project dialog box appears (Fig.ASP-12.1).
Templates
3. Select Installed Visual C# Windows option in the left pane of the New Project
dialog box (Fig.ASP-12.1).
4. Select WPF Browser Application template in the middle pane (Fig.ASP-12.1).
5. Enter WPFbrowserapplication in the Name text box to specify the name of the application
(Fig.ASP-12.1).
6. Enter an appropriate location for the application in the Location combo box (Fig.ASP-12.1).
7. Click the OK button, as shown in Fig.ASP-12.1:
5
6
Fig. ASP-13.1
8. Add two radio button controls, three label controls, two text box controls, and a button control to
the design surface from the Toolbox.
9. Set the content property of radioButton1 as Mr, radioButton2 as Miss, label1 as Enter First name,
label2 as Enter Last name, and button1 as CLICK HERE in the Properties window.
The Page1.xaml page appears, as shown in Fig.ASP-12.2:
Fig.ASP-12.2
320
Windows Presentation Foundation
0. Double-click the button control and add the following code snippet in the Page1.xaml.cs file
10 e in
the click event of the button1 control:
private void button1_Click(object sender, RoutedEventArgs e)
{
if (radioButton1.IsChecked ==true)
{
label3.Content = radioButton1.Content+" "+ textBox1.Text + " " + textBox2.Text;
}
else
{
label3.Content = radioButton2.Content + " " + textBox1.Text + " " +
textBox2.Text;
}
}
After adding the controls and setting their properties, Listing 12.1 shows the source code of the
Page1.xam ml page:
Listing 12.1
1: Source Code of the Page1.xaml Page in WPFbrowserapplication
<Page x:Class="WPFbrowserapplication.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid Height="289" Width="554">
<Button Content="CLICK HERE" Height="23" HorizontalAlignment="Left"
Margin="107,164,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
<RadioButton Content="Mr" Height="16" HorizontalAlignment="Left"
Margin="107,26,0,0" Name="radioButton1" VerticalAlignment="Top" />
<RadioButton Content="Miss" Height="16" HorizontalAlignment="Left"
Margin="156,26,0,0" Name="radioButton2" VerticalAlignment="Top" />
<Label Content="Enter First name" Height="28" HorizontalAlignment="Left"
Margin="0,66,0,0" Name="label1" VerticalAlignment="Top" />
<Label Content="Enter last name" Height="28" HorizontalAlignment="Left"
Margin="0,106,0,0" Name="label2" VerticalAlignment="Top" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="98,66,0,0"
Name="textBox1" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="98,111,0,0"
Name="textBox2" VerticalAlignment="Top" Width="120" />
<Label Height="28" HorizontalAlignment="Left" Margin="12,228,0,0" Name="label3"
VerticalAlignment="Top" Width="235" />
</Grid>
</Page>
1. Run the application by pressing the F5 key. The output of the application appears (Fig.ASP-12.3).
11
122. Select a radio button, fill the text boxes, and click the CLIC
CK HER
RE button on the Web page. In
our case, we have selected the Mr radio button (Fig.ASP-12.3).
The output appears on the label3 control, as shown in Fig.ASP-12.3:
321
ASP.NET 4.5 in Simple Steps
12
Fig.ASP-12.3
322
Windows Presentation Foundation
323
ASP.NET 4.5 in Simple Steps
Fig.ASP-12.4
Fig.ASP-12.5
324
Windows Presentation Foundation
namespace Datagridbrowserapplication
{
/// <summary>
/// Interaction logic for Page1.xaml
/// </summary>
public partial class Page1 : Page
{
public Page1()
{
InitializeComponent();
}
public class Books
{
public int ID { get; set; }
325
ASP.NET 4.5 in Simple Steps
});
authors.Add(new Books()
{
ID = 1002,
BName = "Programming",
BookTitle = "Programming C#",
DOP = new DateTime(2006, 12, 2),
});
authors.Add(new Books()
{
ID = 1003,
BName = "Designing",
BookTitle = "HTML",
DOP = new DateTime(2010, 4, 24),
});
return authors;
}
}
}
0. Double-click the button
10 n1 control and add the following code in the Clicck event.
private void button1_Click(object sender, RoutedEventArgs e)
{
Northwindgrid.ItemsSource = LoadBooksData ();
}
After adding the controls and setting their properties, Listing 12.4 shows the source code of the
Page1.xaml fille:
Listing 12.4
4: Code of the Page1.xaml File in the Datagridbrowserapplication Application
<Page x:Class="Datagridbrowserapplication.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid>
326
Windows Presentation Foundation
12
Fig.ASP-12.6
327
ASP.NET 4.5 in Simple Steps
Fig.ASP-12.7
9. Double-click the Submiit button and add the following code snippet in the Clicck event:
private void button1_Click(object sender, RoutedEventArgs e)
{
label5.Content = "English: " + datePicker1.Text + ", " + " Hindi: " + datePicker2.Text
+ ", " + " Maths: "+ datePicker3.Text;
}
After adding the controls and setting their properties, Listing 12.5 shows the source code of the
Page1.xaml fille:
Listing 12.5:: Code of the Page1.xaml File in the Datepickerbrowserapplication Application
<Page x:Class="Datepickerbrowserapplication.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid>
<Label Content="TIME SCHEDULE" Height="28" HorizontalAlignment="Left"
Margin="93,0,0,0" Name="label1" VerticalAlignment="Top" Width="101" />
<Label Content="English" Height="28" HorizontalAlignment="Left"
Margin="10,48,0,0" Name="label2" VerticalAlignment="Top" />
<Label Content="Hindi" Height="28" HorizontalAlignment="Left" Margin="10,86,0,0"
Name="label3" VerticalAlignment="Top" />
<Label Content="Maths" Height="28" HorizontalAlignment="Left"
Margin="10,124,0,0" Name="label4" VerticalAlignment="Top" />
<Label Height="40" HorizontalAlignment="Left" Margin="10,248,0,0" Name="label5"
VerticalAlignment="Top" Width="278" />
<Button Content="Submit" Height="23" HorizontalAlignment="Left"
Margin="44,219,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
<DatePicker Height="25" HorizontalAlignment="Left" Margin="135,87,0,0"
Name="datePicker1" VerticalAlignment="Top" Width="115" />
328
Windows Presentation Foundation
11
Fig.ASP-12.8
12. Click the Submiit button. The output appears, as shown in Fig.ASP-12.9:
12
Fig.ASP-12.9
329
ASP.NET 4.5 in Simple Steps
Fig.ASP-12.10
9. Double-click the Submit button and add the following code snippet in the Click event:
private void button1_Click(object sender, RoutedEventArgs e)
{
label3.Content = "Your Birthday is on:: " + calendar1.SelectedDate.ToString();
}
After adding the controls and setting their properties, Listing 12.6 shows the source code of the
Page1.xaml file:
Listing 12.6: Code of the Page1.xaml File of the Calendarbrowserapplication Application
<Page x:Class="Calendarbrowserapplication.Page1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
330
Windows Presentation Foundation
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300"
Title="Page1">
<Grid Height="300" Width="333">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="242*" />
<ColumnDefinition Width="46*" />
<ColumnDefinition Width="45*" />
</Grid.ColumnDefinitions>
<Calendar Height="170" HorizontalAlignment="Left" Margin="125,58,0,0"
Name="calendar1" VerticalAlignment="Top" Width="180" Grid.ColumnSpan="3" />
<Button Content="Submit" Height="23" HorizontalAlignment="Left"
Margin="39,230,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
<Label Content="Calendar Control" Height="28" HorizontalAlignment="Left"
Margin="80,12,0,0" Name="label1" VerticalAlignment="Top" Width="154" />
<Label Content="Select Your Birth date:" Height="28" HorizontalAlignment="Left"
Margin="0,76,0,0" Name="label2" VerticalAlignment="Top" />
<Label Height="41" Margin="10,259,12,0" Name="label3" VerticalAlignment="Top"
Grid.ColumnSpan="3" />
</Grid>
</Page>
10. Press the F5 key to view the output in the browser (Fig.ASP-12.11).
11. Select the date from the Calenda
ar control and click the Submiit button, as shown in Fig.ASP-1311:
11
Fig.ASP-12.11
331
ASP.NET 4.5 in Simple Steps
Fig.ASP- 14.12
Fig.ASP-12.13
332
Windows Presentation Foundation
After adding reference of the Ribbon control, add the following XAML code in the RibbonControl
application. Listing 13.7 shows the source code of the MainWindow.xaml fille:
Listing 12.7
7: Code of the MainWindow.xaml File of the RibbonControl Application
<Window x:Class="RibbonControl.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
</Grid>
</Window>
0. Press the F5 key to view output in the browser, as shown in Fig.ASP-12.14:
10
Fig.ASP-12.14
333
ASP.NET 4.5 in Simple Steps
334
CHAPTER 13
Web, WCF, and Cloud Service
Introduction
A Web service may be defined as an independent and self-sustained unit of a software application
hosted on the Internet. Web services implement specific functionalities to execute the business logic of
the commercial application. Suppose that you want to host a Web site on the Internet that calculates the
simple interest. You can use a Web service to host the Web site for calculating simple interest. In this
scenario, a Web service is advantageous in the sense that you do not need to write the code in the Web
site for calculating the simple interest. Instead, all you have to do is simply to use the Web service that
provides this functionality.
A Web service allows a Web site to communicate with other Web sites irrespective of the programming
languages in which they are created. As a Web service complies with common industry standards, it can
be accessed by any Web application, regardless of the software and hardware platforms on which the
application runs. The standards to which a Web service must comply with is Simple Object Access
Protocol (SOAP)) that allows Web services to communicate with other Web applications over the Internet.
SOAP specifies a format for Extensible Markup Language (XML) messages, which are used by Web
applications to request for and receive a Web service from a Web server. These messages are also
called SOAP messages. The other standard is Web Services Description Language (WSDL),, which is an
XML-based language that defines Web services. Every Web service consists of a corresponding WSDL
document that specifies the location of the Web service and lists all the functions that it can perform.
Earlier, it was difficult to create the applications that can be used to communicate between a client and
a server. It was because we need to use a number of technologies, such as ASP.NET Web Service (ASMX
Web service), Web Service Enhancements (WSE), and Microsoft Message Queuing (MSMQ) to perform
this task. Some of the services provided by these technologies are ASMX Web servicce that allows sharing
of information in a way that enables it to be accessed from any platform, .NET Remoting servicce that
allows transferring of data from a client to a server on the Windows operating system, and MSMQ
servicce that allows queuing of messages that helps in sending and receiving messages even when the
server is disconnected.
ASP.NET 4.5 in Simple Steps
Since different functionalities are offered by different technologies to develop a distributed application, a
developer has to master each of the aforementioned technologies. Microsoft introduced the Windows
Communication Foundation (WCF) technology to overcome the developer’s task of mastering the
different technologies. WCF brings together the functionalities of all the aforementioned technologies
under a unified programming model, thereby simplifying the process of developing a distributed
application. WCF is a set of .NET technologies that act as a platform for creating and distributing
connected applications. It is also used to develop and deploy services on Windows and provides a
unified framework for rapidly building service-oriented applications. With the help of these applications,
it is easy to build and consume secure and reliable applications through the simplified model of WCF.
Let’s now learn to create and use Web services.
336
Web, WCF, and Cloud Service
10
11
Fig.ASP- 15.1
2. Add the following code snippet in the WebService.cs file for creating a Web service and build the
12
application:
[WebMethod]
public string Add(int a, int b)
{
return Convert.ToString(a + b);
}
13. Right-click the application name in the Solution Explore
er window to open the context menu
(Fig.ASP-13.2).
14. Select the Add Service Referencce option from the context menu, as shown in Fig.ASP-13.2:
14
Fig.ASP-13.2
337
ASP.NET 4.5 in Simple Steps
15
Fig. ASP-15.3
16
Fig.ASP-13.4
338
Web, WCF, and Cloud Service
17
Fig.ASP-13.5
18
Fig.ASP-13.6
339
ASP.NET 4.5 in Simple Steps
9. Click the Add link in the WebService page of the dialog box, as shown in Fig.ASP-13.7:
19
19
Fig.ASP-13.7
20. Enter values in the two textboxes and click the Invokke button, as shown in Fig.ASP-13.8:
20
Fig.ASP-13.8
340
Web, WCF, and Cloud Service
Fig.ASP-13.9
22
Fig.ASP-13.10
3. Add three textboxes, three label controls, and one button control on the Default.asp
23 px Web Form.
4. Set the Texxt property of La
24 abell1 control as Enter First numbe
er, Labell2 control as Enter Second
Numbe er, Label3 as Result, and Button
n1 as ADD.
5. Double-click the Button
25 n1 control and add the following code snippet in the Click event:
protected void Button1_Click(object sender, EventArgs e)
{
localhost.WebService ws = new localhost.WebService();
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
TextBox3.Text = ws.Add(a, b);
}
Listing 13.1 shows the source code of the Default.aspx Web Form after adding the controls on the Web
Form and setting their properties:
Listing 13.1
1: Code of the Default.aspx Web Form of the Webserviceapplication Application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
341
ASP.NET 4.5 in Simple Steps
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div> <br /> <br /><br />
<center>
<asp:Label ID="Label1" runat="server" Text="Enter First
number"></asp:Label> <asp:TextBox
ID="TextBox1" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label2" runat="server" Text="Enter Second Number"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"> </asp:TextBox> <br /> <br />
<asp:Button ID="Button1" runat="server" Text="ADD" Width="99px"
onclick="Button1_Click" /> <br /><br />
<asp:Label ID="Label3" runat="server" Text="Result"></asp:Label><asp:TextBox
ID="TextBox3" runat="server"></asp:TextBox></center> </div>
</form>
</body>
</html>
26. Press the F5 key to execute the Web application (Fig.ASP-13.11).
27. Click the ADD button, as shown in Fig.ASP-13.11:
Fig.ASP-13.11
Let’s now learn the usage of WCF service in the next section.
342
Web, WCF, and Cloud Service
3. Select the InstalledTemplatesVisua al C#WC CF Servicce option in the left pane (Fig.ASP-13.12).
4. Set the location andd enter nam
me as WCFapplicatio
on in the Web location combo box (Fig.ASP-13.12).
5. Click the OK button, as shown in Fig.ASP-13.12:
Fig.ASP-13.12
Fig.ASP-13.13
343
ASP.NET 4.5 in Simple Steps
8. Add the following code snippet in the IServicce interface in the IServicce.ccs file and save it:
[OperationContract]
int Add(int a, int b);
9. Right-click the Service.svvc file in the Solution Explore
er window and select View in Browser (Internet
Explorer)) option from the context menu. The Service.svvc page appears (Fig.ASP-13.14).
0. Close the Service.svvc page, as shown in Fig.ASP-13.14:
10
Fig.ASP-13.14
12
Fig.ASP-13.15
344
Web, WCF, and Cloud Service
13
14
Fig.ASP-13.16
15. Double-click the Servicce option in the Services pane. The Service node opens (Fig.ASP-13.17).
16. Select the IServicce child node in the Services pane (Fig.ASP-13.17).
17. Click the OK button, as shown in Fig.ASP-13.17:
16
17
Fig.ASP-13.17
345
ASP.NET 4.5 in Simple Steps
18. Add a Web Form in the application, similar to how you have done earlier, and add three Label
controls, three textboxes, and a Button control to it.
19. Set the text property of Label1 control as Enter First number, Label2 control as Enter Second
Number, Label3 as Result, and Button1 as ADD.
20. Double-click the ADD button and add the following code snippet in the Click event:
protected void Button1_Click(object sender, EventArgs e)
{
ServiceReference1.ServiceClient ws = new ServiceReference1.ServiceClient();
int a = Convert.ToInt32(TextBox1.Text);
int b = Convert.ToInt32(TextBox2.Text);
TextBox3.Text = ws.Add(a,b).ToString();
}
Listing 13.2 shows the source code of the Default.aspx Web Form after adding the controls and setting
their properties:
Listing 13.2
2: Code of the Default.aspx Web Form of the WCFapplication Application
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<body>
</div>
</form>
</body>
</html>
346
Web, WCF, and Cloud Service
The result will appear in the Result text box as shown in Fig.ASP-13.18:
22
Fig.ASP-13.18
Cloud Service
The Cloud service is a service that is used to build Cloud applications. The advantage of Cloud
application is that it provides the facility of using the Cloud application without installing it on the
computer. It reduces the maintenance and support of the application as compared to those applications
that are not developed using Cloud service. In ASP.NET 4.5, the Cloud service or applications are
created using Windows Azure platform. This platform provides Windows-based compute and storage
service for Cloud applications. Different kinds of users can use the application from the Cloud service,
which may be public or private application. The Windows Azure platform helps developers to build
highly useful applications for clients. Some important features of the Cloud service are as follows:
Accessing and managing of commercial software.
Centralizing the activities of management of software in the Web environment.
Developing applications capable of managing many clients.
Centralizing the updation feature of software that eliminates the need of downloading the
upgrades.
There are three kinds of deployment models in a Cloud service, which are as follows:
Community Cloud d: Used when many organizations that have common need and requirements
are ready to share the benefits of the Cloud service. This model is quite expensive, but it has
number of benefits such as privacy and security.
Hybrid Cloudd: Consists of multiple service providers. This model integrates various Cloud services
for Hybrid Web hosting.
Private Cloud
d: Based on the usage of services by a single client on private network. The benefits
of this model are data security, corporate governance, and reliability concerns. The disadvantage
of this model is that the users have to take care about the management of the Cloud service.
Some of the advantages of Cloud service are as follows:
347
ASP.NET 4.5 in Simple Steps
The Cloud service is cost-saving. It helps in the utilization of investment in the corporate
sector.
The applications that are developed using the Cloud service are scalable and robust. Earlier
the scaling used to take months, but nowadays the scaling takes less time.
The Cloud applications are time-saving in terms of deployment and maintenance.
You have to install Windows Azure SDK for .NET to develop a cloud application in ASP.NET 4.5.
6
Fig.ASP-13.19
The New Windows Azure Cloud Service dialog box appears (Fig.ASP-13.20). In this dialog box,
you need to select roles for creating your application. For example, the ASP.NET Web Role
creates an application with a Web user interface. Similarly, the Worker Role creates the
background processing application.
7. Select the ASP.NET Web Role and Worker Role options from the .NET Framework 4.5 roles group and
click the forward arrow button to add the roles in the Windows Azure Cloud Service solution group.
348
Web, WCF, and Cloud Service
8. Rename ASP.NET Web Rolle to WebRolle and Worker Rolle to WorkerRolle (Fig.ASP-13.20).
9. Click the OK button, as shown in Fig.ASP-13.20:
9
Fig.ASP-13.20
13
Fig.ASP-13.21
349
ASP.NET 4.5 in Simple Steps
With this, you have come to the end of this chapter. Let’s now summarize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
Introduction to Web services and WCF services.
Creating and using Web services.
Creating and using WCF services.
Cloud service and its features.
350
CHAPTER 14
Introduction to MVC
Introduction
An application usually provides different sets of information to its users. The content of the Web
application is presented to users on different Web pages in different formats. Different users may require
multiple types of interfaces, such as HyperText Markup Language (HTML) for Web customer, a Wireless
Markup Language (WML) for wireless customers, and Java or .NET for administrators and XML-based
Web service for suppliers. Therefore, in an application, we may need to create multiple Views for a
single Model. When developing a small application, it sounds logical to interweave data access,
business logic, presentation logic, and control logic together. However, for a large enterprise-level
application, interweaving makes code files more complex; therefore, it will be difficult to manage files
while implementing changes in future. This results in duplication of data access and business logic code
in the application at various points. As a result, the implementation, testing, and maintenance efforts are
also duplicated. It is always a good idea to reduce duplication to save time and resources by separating
presentation logic, business logic, and control logic as different components, which can easily be
reused. The idea comes in the form of a Model–View–Controller (MVC) design pattern, which separates
data access, business logic, and presentation logic, and enables the creation of a number of Views
accessing the same aforementioned enterprise-level application model.
In this chapter, you will learn about MVC architecture, ASP.NET MVC Framework, new features in
ASP.NET MVC 4, and creating an MVC application. Now, let’s learn about the ASP.NET MVC
architecture.
Fig.ASP-14.1
When there is a requirement to support only one type of client with one type of interface, it is always a
good idea to combine client-specific data and business logic with the interface-specific logic. If Web
applications require interaction with multiple types of clients, then different applications are required to
support each type of client. This leads to the repetition of non-interface-specific code in each interface-
specific code, which further leads to increased effort in designing, debugging, and maintenance of an
application.
The solution of the aforementioned problem is the use of MVC architecture while designing an
application. The idea behind the MVC architecture is to separate the core business model functionality
of the Web application from the presentation and control logic of the interface-specific application. With
this sort of arrangement, it is possible to see multiple Views of the same data model of the Web
application. Under this architecture, data (Model) and user interface (View) are separated from each
other so that any change in the user interfaces does not affect the data in the database and vice versa.
The three components of MVC – the Model, the View, and the Controller – must communicate to each
other if the application needs to manage a coherent interaction with the user. The View and the
Controller communicate to each other directly because these two components are specifically designed
to work together. However, the Model communicates whenever it is required by the Controller.
Microsoft provides built-in support for developing Web applications by using an MVC-based architecture
in ASP.NET 4.5. Now, let’s learn about the MVC Framework associated with ASP.NET 4.5.
352
Introduction to MVC
ASP.NET MVC Framework is a lightweight, extremely testable presentation framework that is appended
to the existing ASP.NET features, such as master pages and membership-based authentication. MVC
Framework resides inside the System.Web.Mvc namespace. This namespace is an elementary supported
part of the System.Web namespace, which forms the basis of any Web application. An MVC Framework
consists of the following components:
Model in MVC Frameworrk: Represents the data and the business logic of an application, and is
not related to the presentation of the application. The Model components focus on keeping track
of the state of your application. The business logic required for your application is maintained
here. The Model components contain the data that needs to be displayed on the Web page, but
is not exposed to the information about the View and the manner in which the data is to be
displayed. It also does not know about the View actions that are used to manipulate the data.
However, the data is accessed and manipulated through methods that are independent of the
View. A Model can be considered as the foundation of the MVC architecture. Its core is
composed of business logic and data access code. For example, if an application has to find out
the gross salary of employees, the computation part is performed in the Model layer. It is the
Model that defines what the application exactly does. The View and Controller interact with the
Model for performing any task, such as displaying and querying data. In the MVC architecture,
the Model layer is self-contained and functions independent of the View and Controller layers.
Therefore, the core application code, which is based on the Model, can be used with multiple
UIs.
View in MVC Frameworkk: Provides the UI for the Model by using Web form. The user interacts
with the application through a View. It represents the information based on the Model and allows
the user to alter the data. Typically, this UI is created from the Model data. The main
responsibilities of a View are as follows:
Responsible for representing any kind of information in a form understandable to the user.
Requests the Model to provide the changed-state information, such as if the Model manages
the database whose content can be changed frequently. Any change in the database must
be represented to the user as early as possible.
Sends user inputs to the Controller when the user wants to modify the content of the Model,
as user does not communicate with the Model directly. The user communicates through View,
which further communicates with the Controller about the user input. The Controller then
makes changes in the Model according to the users’ requirements and notifies all the other
associated Views.
Allows the Controller to select the View in the Web application. The data might have different
Views to different users. View allows the Controller to determine which View is suitable for
which user and provides them accordingly.
Controller in MVC Frameworkk: Handles all the Views associated with a Model, and ultimately
select a View that displays UI. When the user interacts with the View and tries to update the
Model, the Controller invokes methods to update the Model. The Controller controls the data
flow and transformation between the Model and the View. Its main responsibilities are as follows:
Mapping the user actions into Model updates. Input from the user is not fed directly to the
Model. Instead, the Controller first provides this input, which further updates the Model.
Selecting the View for responses. The application provides multiple Views of itself. The
Controller selects the most appropriate View in the application and delivers it to the user.
353
ASP.NET 4.5 in Simple Steps
The interaction between the three components of MVC architecture – Model, View, and Controller – is
shown in Fig.ASP-14.2:
Fig.ASP-14.2
Each user may get different Views that display required information customized for the value and layout
according to that particular user. The application updates all the Views as soon as any change in the data
takes place. If the user wishes to change the data, it sends a request to the Controller, which further consults
the Model to update all the Views. Note that the View does not communicate directly with the Model. Rather
this communication takes place through the Controller. The control flow consists of the following steps:
1.. The user sends a request through a UI provided by the View, which further passes this request to
the Controller.
2.. The Controller receives the input request coming from the user through the interface provided by the
View and processes the request according to the Controller logic. If access to the Model is not
required, the Controller moves to step 4; otherwise, the Model is accessed and its state is changed.
3.. If the Model is accessed and modified, then all the associated Views are notified of the changes
in the Model.
4.. The Controller then selects the new View to be displayed in the Web application.
5.. The View presents a UI according to the Model. The View data is also contained within the
Model. The View queries about the state of the Model to show the current data.
The View remains idle after the current interaction and waits for the next interaction to begin. The entire
algorithm is repeated when a new request is serviced in the same way and is also followed for other requests.
The features of ASP.NET MVC Framework are as follows:
Separates the application tasks (input logic, business logic, and UI logic) and TDD by default. TDD
is a method of software development in which unit testing is repeatedly done on the source code.
Consists of customized components. ASP.NET MVC Framework also supports the use of Dependency
Injection (DI) and Inversion of Control (IoC) container Models. DI allows you to inject objects into a
354
Introduction to MVC
class. IoC states that when an object needs another object, the first object should acquire the second
object from an outside source, such as a configuration file to make testing easier.
Supports for markups in the existing ASP.NET page (.aspx files), user control (.ascx files), and
master page (.master files) markup files as View templates. The existing ASP.NET features can be
used with ASP.NET MVC Framework as an add-on, such as nested master pages, declarative
server controls, templates, data binding, localization, in-line expression and so on.
Supports the existing features of ASP.NET, such as forms authentication and Windows
authentication, Uniform Resource Locator (URL) authorization, membership and roles, output
and data caching, session and profile state management, health monitoring, configuration
system, and the provider architecture.
Now, let’s learn about new features of ASP.NET MVC 4.
355
ASP.NET 4.5 in Simple Steps
Add Controller to any project folder:: Specifies the inclusion of Controller from any project folder
in your MVC project.
Bundlin
ng and Minificatio
on: Allows you to decrease the number of HTTP requests that a Web page
requires to make by integrating individual files, that is bundling of files for combining scripts and
CSS. On the other hand, minification includes activities, such as eliminating whitespace to
shorten names of variables and collapsing of CSS selectors on the basis of their semantics.
Enablin
ng Login
ns fro
om Faceboo
ok and othe
er site
es: Specifies the support for OAuth and OpenID
login by the default templates in ASP.NET MVC 4 Internet Project template using the
DotNetOpenAuth library.
5
6
Fig.ASP-14.3
The Razor option must be selected in the View engine drop-down list.
356
Introduction to MVC
Fig.ASP-14.4
11
10
Fig.ASP-14.5
357
ASP.NET 4.5 in Simple Steps
15
16
Fig.ASP-14.6
17
18
Fig.ASP-14.7
9. Replace the ActionResult Index(() method in the BooksController.ccs file with the following code
19
snippet:
public ActionResult Index()
{
FirstMvcApplication.Models.ClassBooks bs = new
FirstMvcApplication.Models.ClassBooks();
bs.BName = "Simple Steps";
bs.BEdition = "ASP.NET 4.5";
bs.BPrice = "400";
bs.BISBN = "111-2222";
bs.publisher = "Kogent Learning Solutions";
return View(bs);
}
0. Open the Solution Explorer window.
20
21. Right-click the View
ws node in the Solution Explore
er window.
2. Select the AddNew Folde
22 er option and name it as Bookks.
3. Press the F5 key to execute the application.
23
The Home Pag ge appears (Fig.ASP-14.8).
24. Close the Home Pag
ge, as shown in Fig.ASP-14.8:
358
Introduction to MVC
Fig.ASP-14.8
27
28
29
30
Fig.ASP-14.9
359
ASP.NET 4.5 in Simple Steps
33
Fig.ASP-14.10
With this, you have come to the end of this chapter. Let’s now summarize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
MVC Architecture that separates the core business Model functionality of the Web application from
the presentation and control logic in the Web application.
MVC Framework that provides an alternative choice to the developer while designing and
developing a Web application.
New Features of ASP.NET MVC 4.
Creating and using an MVC application in ASP.NET 4.5 Framework.
360
CHAPTER 15
Web Application Deployment
Introduction
After the successful development of a Web application, testing and debugging, the next phase is to
deploy it. The purpose of deploying an application is to ensure a simple and easy installation of
application files on a client computer. The .NET Framework provides you some easy ways to deploy a
Web application on a Web server. You can deploy a Web application by using three different methods,
by copying its contents to the destination, by publishing it, or by using Web installer.
Deploying a Web application by copying the content of the Web application to the destination
implies copying the actual source code to the destination; so it does not provide any protection to
your source code.
Deploying a Web application by publishing implies providing protection to your source code up
to some limit, as it does pre-compilation of source code before sending it to the destination.
Deploying a Web application by using Web installer implies providing the maximum protection to
your source code, as it enables you to create fully configurable setup projects for your Web
application. These projects are sent to the destination machine instead of the actual source code
of the Web application that you have developed.
In this chapter, we learn about the options available for application deployment. We can deploy an
application by using the Copy Web Site utility, by publishing a Web site, by using the XCOPY command,
and by using one-click Publish. You will also learn deployment of an application using InstallShield
Limited Edition.
Project source
e: Contains the solutions of all the application’s contents and references at
development time. The Copy Web Site utility picks all the files for deployment from this location
or folder.
Project destination
n: Deploys the application in the destination folder. This destination directory
can be situated on remote computers or servers, which allow copying the Web application
contents using Front Page Server extensions, or File Transfer Protocol (FTP), or Hypertext
Transfer Protocol (HTTP) implementations for content transfer.
Synchronizing two Web sitess: Means to synchronize two Web sites by copying each other’s files.
The Copy Web Site utility also checks whether or not the latest version of a file is present in the
destination. If files of the most recent version are found at the destination, then the Copy Web Site utility
does not superimpose the older version of the files.
Now, let’s learn the following steps to copy a Web site using the Copy Web Site utility:
All Programs
1. Click Start Microsoft Visual Studio 2012
Visual Studio 2012.
2. Select the FILENew Web Site option from the menu bar.
The New Web Site dialog box appears.
Templates
3. Select the Installed Visual C#
ASP.NET Web Forms Site option in the dialog box.
4. Enter the location and name as Copywebsiteutility in the combo box adjacent to the Browse
button to specify the location and name of the application.
5. Click the OK button(Fig.ASP-15.1).
6. Select the WEBSITECopy Web Site option in the WEBSITE menu, as shown in Fig.ASP-15.1:
Fig.ASP-15.1
362
Web Application Deployment
Fig.ASP-15.2
363
ASP.NET 4.5 in Simple Steps
9
10
11
12
13
14
Fig.ASP-15.3
5. Right-click the Source Web site pane and select the Select All option from the context menu
15
(Fig.ASP-15.4).
6. Click the first arrow in the middle pane of the Wizard, as shown in Fig.ASP-15.4:
16
15
16
Fig.ASP-15.4
17. Close the application; open the browser on your local computer and type the address in the
address bar in the following syntax:
http:// <machine -ipaddress>/ <directory-name|full-directory path>
Now, let’s learn how to publish a Web site.
364
Web Application Deployment
Publishing a Website
Publishing a Website involves a pre-compilation task of the Web site. The pre-compilation process is the
replica of the dynamic compilation of Web pages while rendering them in the browser. During the pre-
compilation task, the compiler checks for all the errors involving syntax matching, type matching,
variables transfer, and calling of subroutines across different application modules. It also checks for the
modules accessing application’s global resources and the local computer resources.
The output of the pre-compilation process is written in any directory of the local drives or external
computer drives by using the FTP or HTTP. Any error(s) in the pre-compilation process is visible as an
error list in the Output windo
ow of the Visual Studio Integrated Development Environment (IDE
E). Post-pre-
compilation task, the Web application will be error free.
Let’s perform the following steps to create and publish a Web site:
1. Open the Visual Studio 201
12.
2. Select the FILENewWeb Sitte option from the menu bar.
The New Web Site dialog box appears.
3. Select the InstalledTemplatesVisual C# option from the left pane and ASP.NET Web Forms
Sitte template from the middle pane.
4. Set the location and enter the name such as Publishwebsitte in the combo box to specify the name
and location for the application.
5. Click the OK button.
6. Select the BUILDPublish Web Sitte option from the menu bar, as shown in Fig.ASP-15.5:
Fig.ASP-15.5
365
ASP.NET 4.5 in Simple Steps
Fig.ASP-15.6
A message appears in the Output window indicating that Publissh has succeeded, as shown in
Fig.ASP-15.7:
Fig.ASP-15.7
366
Web Application Deployment
There are also a large number of arguments not included in the table. However, you can find them by
using the following command at the command prompt:
xcopy /?
Let’s deploy a Web application using the XCOPY deployment technique by following these steps:
1. Open the Visual Studio 201
12.
2. Open the FILENewWeb Site option.
The New Web Site dialog box appears.
3. Enter C:\myweb\deploy\Xcopyutility in the combo box beside browse button to specify the
location and name of the Web site.
4. Click the OK button in the dialog box.
5. Open the Run dialog box by pressing the WINDOWS+
+R keys simultaneously.
6. Type cmd in the Open text box of the Run dialog box and then click the OK button
(Fig.ASP-15.18).
The command prompt appears (Fig.ASP-15.18).
7. Type the following command in the command prompt:
xcopy /i /s c:\myweb\deploy d:\mydeployment
The source folder is placed under the C: drive and the destination folder is placed in the D: drive.
When you execute this command, all the files and folders within the deploy folder are deployed in the
target folder, as shown in Fig.ASP-15.8:
367
ASP.NET 4.5 in Simple Steps
Fig.ASP-15.8
The /i parameter allows the XCOPY command to create the destination folder if it does not exist. Now,
you can easily run your Web application from its new location.
Fig.ASP-15.9
368
Web Application Deployment
10
11
12
Fig.ASP-15.10
The Output window appears with message indicating that Publish has succeeded.
13. Browse the Target Locatio on (Fig.ASP-15.11).
The application files appear in the OnceClickPublissh folder, as shown in Fig.ASP-15.11:
Fig.ASP-15.11
The Visual Studio 2012 replaces the Windows Setup project with InstallShield software that is
used to create setup project for Windows based applications with Visual Studio 2012. To use
InstallShield software with Visual Studio 2012 IDE, you must download and install this
software on your computer.
369
ASP.NET 4.5 in Simple Steps
Let’s learn about InstallShield Limited Edition for Visual Studio 2012.
Fig.ASP-15.12
370
Web Application Deployment
9. Right-click on the MyWindowsAp pp solution name in Solution Explore er window and select
AddNew Project option from the context menu as shown in Fig.ASP-15.13:
Fig.ASP-15.13
10
11
12
Fig.ASP-15.14
371
ASP.NET 4.5 in Simple Steps
Fig.ASP-15.15
Fig.ASP-15.16
14. Specify the company name, application name, version of application and web address of the
company in given textboxes (Fig.ASP-15.17).
15. Click the Installation Requirementts icon, as shown in Fig.ASP-15.17:
372
Web Application Deployment
Fig.ASP-15.17
The Installation Requirementts page appears. On this page, you can specify required software to
run your application. We are using default settings (Fig.ASP-15.18).
16. Click the Application File
es icon, as shown in Fig.ASP-15.18:
16
Fig.ASP-15.18
373
ASP.NET 4.5 in Simple Steps
17
Fig.ASP-15.19
Fig.ASP-15.20
374
Web Application Deployment
19
20
Fig.ASP-15.21
21
Fig.ASP-15.22
375
ASP.NET 4.5 in Simple Steps
Fig.ASP-15.23
22
23
Fig.ASP-15.24
When you click the Open button, a built tag appears on Application Shortcuts page that is the
default shortcut name of the MyWindowsSetup application.
24. Select the built tag on Application Shortcuts page (Fig.ASP-15.25).
376
Web Application Deployment
25
5. Click the Renam
me button to rename the default shortcut name, built. In our case, we have
renamed our application shortcut to MyWindowsApp_Shortcut,, as shown in Fig.ASP-15.25:
24
25
Fig.ASP-15.25
26
6. Select the Creatte shortcut in Start Men
nu check box and Create shortcu
ut on Deskto
op checkboxes on the
Application Shortcu ut page to create shortcut of the WindowsAppSetu
up application (Fig.ASP-15.26).
27
7. Click on the Application Registrry icon, as shown in Fig.ASP-15.26:
26
Fig.ASP-15.26
377
ASP.NET 4.5 in Simple Steps
On the Application Registrry page, you can create registry keys for application configuration
settings. We are not creating any registry key in our case.
28
8. Click on the Installation Intervie
ew icon, as shown in Fig.ASP-15.26:
28
Fig.ASP-15.26
The Installation Interview page appears. On this page, you can specify the License agreement for
your application, prompt the user to provide the company name and user name and allow them
to change the location of the application while installation. In our case we are using default
settings, as shown in Fig.ASP-15.27:
Fig.ASP-15.27
378
Web Application Deployment
29
Fig.ASP-15.28
Now, you have successfully created the WindowsAppSetu up project. Copy the setup file created inside the
WindowsAppSetu up project. You can run the setup file on any computer to install the WindowsAppSetu up
application. When you install the WindowsAppSetu up application on a target computer, the application
appears in the Start menu with a shortcut name MyWindowsApp_Shortcu ut, as we had defined while
creating WindowsAppSetu up project.
You can run the application from the Start menu as shown in Fig.ASP-15.29:
Fig.ASP-15.29
With this, you have come to the end of this chapter. Let’s now summarize what you have learned in this
chapter.
SUMMARY
In this chapter, you have learned about:
Deploying an ASP.NET Web site using Copy Web Site utility
Publishing a Web application in ASP.NET
Using the XCOPY deployment for deploying an application
Deploying a Web application by using One-Click Publish deployment
InstallShield Limited Edition for Visual Studio
379
ASP.NET 4.5 in Simple Steps
380