0% found this document useful (0 votes)
223 views

4.5 in Simple Steps - Nodrm

Uploaded by

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

4.5 in Simple Steps - Nodrm

Uploaded by

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

ASP.NET 4.

Authored by:

Kogent Learning Solutions Inc.

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

ISBN: 978-93-5119-112-4 (ebk)

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

Commenting the Codes ....................................................................................................................51


Creating a Simple Web Application .................................................................................................51

Chapter 2  Web Application in ASP.NET 4.5 57


Usage of Web Applications ..............................................................................................................57
Business Usages of Web Applications ........................................................................................58
Modern Usages of Web Applications.........................................................................................58
Improvements in ASP.NET 4.5 ..........................................................................................................58
ASP.NET 4.5 Core Services ........................................................................................................59
ASP.NET 4.5 Web Forms ...........................................................................................................60
ASP.NET Web Pages 2 ...............................................................................................................62
General Enhancements for Web Development ..........................................................................62
Data-Related Enhancements for Web Development ..................................................................63
IIS Express for Web Development ..............................................................................................64
ASP.NET Web API ......................................................................................................................64
ASP.NET MVC 4, Web API, and ASP.NET Web Pages (Razor) Are Now Open Source .............64
Coding Techniques in Web Application ...........................................................................................65
The Single-File Page Model .......................................................................................................65
The Code-Behind Model ............................................................................................................65

Chapter 3  Standard Controls 67


Introduction to the Control Class ......................................................................................................68
Introduction to the System.Web.UI.WebControl Class .....................................................................70
The TextBox Control .........................................................................................................................71
The Button Control ...........................................................................................................................72
Using the TextBox and Button Controls .....................................................................................73
The Label Control .............................................................................................................................76
Using the Label Controls ............................................................................................................77
The Literal Control ............................................................................................................................78
Using the Literal Control ............................................................................................................79
The Image Control ............................................................................................................................80
Using the Image Control ............................................................................................................80
The ImageButton Control ..................................................................................................................83
Using the ImageButton Controls ................................................................................................84
The ImageMap Control .....................................................................................................................86
Using the ImageMap Control .....................................................................................................87
The DropDownList Control ..............................................................................................................90
Using DropDownList Controls ...................................................................................................90
The CheckBox Control .....................................................................................................................93
The CheckBoxList Control ................................................................................................................94
Using the CheckBox and CheckBoxList Controls .......................................................................94
The RadioButton Control ..................................................................................................................98
The RadioButtonList Control .............................................................................................................98
Using the RadioButton and RadioButtonList Controls ................................................................99
The Table Control ...........................................................................................................................102
The TableRow Class .................................................................................................................103
The TableCell Class..................................................................................................................103
Using the Table Control ...........................................................................................................104
The Panel Control ...........................................................................................................................107
Using the Panel Controls ..........................................................................................................107
The AdRotator Control ....................................................................................................................109

iv
Contents

Using the AdRotator Control ....................................................................................................110


The Calendar Control .....................................................................................................................113
Using the Calendar Controls ....................................................................................................116
The HyperLink Control ...................................................................................................................118
Using the HyperLink Controls ..................................................................................................119
The FileUpload Control ..................................................................................................................121
Using the FileUpload Control ..................................................................................................122
The HiddenField Control ................................................................................................................124
Using the HiddenField Controls ...............................................................................................124
The Wizard Control ........................................................................................................................126
Using the Wizard Control ........................................................................................................127

Chapter 4  Navigation Controls 133


The SiteMapPath Control ................................................................................................................133
Creating the SiteMapPath Control ............................................................................................135
The TreeView Control.....................................................................................................................137
Creating a TreeView Control ....................................................................................................138
The Menu Control ..........................................................................................................................141
Creating Static Menu ................................................................................................................142
Creating Dynamic Menu ..........................................................................................................145
New Improvements ..................................................................................................................148

Chapter 5  Validation Controls 149


The BaseValidator Class.................................................................................................................149
The RequiredFieldValidator Control ...............................................................................................150
The RangeValidator Control ...........................................................................................................153
Using the RangeValidator Control ...........................................................................................153
The RegularExpressionValidator Control ........................................................................................155
Using the RegularExpressionValidator Control ........................................................................156
The CompareValidator Control .......................................................................................................159
Using the CompareValidator Control .......................................................................................159
The CustomValidator Control .........................................................................................................161
Using the CustomValidator Control .........................................................................................162
The ValidationSummary Control ....................................................................................................164
Using the ValidationSummary Control.....................................................................................165
The ValidationGroup Property ........................................................................................................167
Using the ValidationGroup Property ........................................................................................167

Chapter 6  Login Controls 171


The User Accounts .........................................................................................................................172
The Login Control ...........................................................................................................................175
The LoginName Control .................................................................................................................179
The LoginStatus Control ..................................................................................................................184
The LoginView Control ...................................................................................................................187
The PasswordRecovery Control ......................................................................................................191
The ChangePassword Control .........................................................................................................196
The CreateUserWizard Control ......................................................................................................201

v
ASP.NET 4.5 in Simple Steps

Chapter 7  WebParts Controls 205


Overview of the WebParts Controls................................................................................................205
The WebPartManager Control .................................................................................................206
The CatalogZone Control .........................................................................................................209
The EditorZone Control ............................................................................................................211
The WebPartZone Control .......................................................................................................215
The ConnectionsZone Control .................................................................................................216
The PageCatalogPart Control ...................................................................................................217
Creating a Simple WebParts Page ...................................................................................................219

Chapter 8  Database Controls 227


Connected Data Access ..................................................................................................................228
ADO.NET .......................................................................................................................................228
Disconnected Data Architecture ..............................................................................................228
ADO.NET Objects ...................................................................................................................229
The SQLDataSource Control ..........................................................................................................230
The ObjectDataSource Control ......................................................................................................236
The XmlDataSource Control ...........................................................................................................241
The LinqDataSource Control ..........................................................................................................244
The AccessDataSource Control ......................................................................................................250
Introduction to Data-Bound Controls .............................................................................................254
The DataList Control ................................................................................................................254
The FormView Control .............................................................................................................258
The DetailsView Control ..........................................................................................................261
The ListView and DataPager Controls ......................................................................................266
The Repeater Control ...............................................................................................................272
The Chart Control ....................................................................................................................275

Chapter 9  Master Pages and Themes 279


Describing Master Pages.................................................................................................................279
Creating Simple Master Pages ..................................................................................................280
Creating Nested Master Pages ..................................................................................................283
Creating a Web Form Using a Master Page..............................................................................285
Exploring Themes ...........................................................................................................................285
Using Themes ..........................................................................................................................286
Using Multiple Themes ............................................................................................................288
Describing Cascading Style Sheet...................................................................................................290
Using CSS.................................................................................................................................290
Exploring Improvements in CSS ...............................................................................................292

Chapter 10  Introducing ASP.NET AJAX 293


ASP.NET AJAX ................................................................................................................................293
Traditional and ASP.NET AJAX Web Applications..........................................................................294
Exploring Some Important Features of AJAX ...................................................................................294
Live Data Binding ....................................................................................................................294
Declarative Instantiation of Client Components .......................................................................294
The Observer Pattern on JavaScript Objects and Arrays ..........................................................295
ADO.NET Data Services and Data Contexts ............................................................................295
AJAX Server Controls ......................................................................................................................295
The ScriptManager Control ......................................................................................................295

vi
Contents

The UpdatePanel Control.........................................................................................................296


The UpdateProgress Control ....................................................................................................297
The Timer Control ....................................................................................................................298
Creating an ASP.NET AJAX Application..........................................................................................298
Creating jQuery Web Application ..................................................................................................300

Chapter 11  Working with Silverlight Applications 303


Need for Using Silverlight...............................................................................................................303
New Features of Silverlight 5.0 .......................................................................................................304
Controls....................................................................................................................................304
Media .......................................................................................................................................305
Graphics...................................................................................................................................305
Text ..........................................................................................................................................305
Trusted Applications ................................................................................................................306
Printing .....................................................................................................................................306
User Interface ...........................................................................................................................306
Data .........................................................................................................................................306
XAML .......................................................................................................................................307
Performance Improvements .....................................................................................................307
Silverlight Architecture ...................................................................................................................307
Developing a Silverlight Application ..............................................................................................309

Chapter 12  Windows Presentation Foundation 315


New Features in WPF 4.5 ...............................................................................................................316
The Ribbon Control..................................................................................................................316
Support for Validating Data Synchronously and Asynchronously ............................................316
Support for Binding to Types that implement ICustomTypeProvider........................................317
Support for Fetching Binding Information ................................................................................317
Data Binding to Static Properties..............................................................................................317
Support for Access to Collections on a Non-UI Thread ...........................................................317
Support for Automatically Updating a Source of a Data Binding .............................................318
New VirtualizingPanel Features ...............................................................................................318
Support for Implementing Weak Reference to an Event...........................................................318
New Methods Defined in the Dispatcher Class........................................................................318
Support for the Use of Markup Extensions for Events ...............................................................319
Support for Rearrangement of Data on Modification (Live Shaping) ........................................319
Improved Performance when Displaying Large Sets of Grouped Data ....................................319
Support for Validation of DataContext Object .........................................................................319
Exploring XAML Browser Applications ...........................................................................................319
Implementing Typography in WPF .................................................................................................322
Exploring Some Controls in WPF ....................................................................................................324
Using DataGrid Control ...........................................................................................................325
Using DatePicker Control ........................................................................................................327
Using Calendar Control ...........................................................................................................330
The Ribbon Control..................................................................................................................331

Chapter 13  Web, WCF, and Cloud Service 335


Using a Web Service ......................................................................................................................336
Using a WCF Service ......................................................................................................................342
Cloud Service .................................................................................................................................347

vii
ASP.NET 4.5 in Simple Steps

Chapter 14  Introduction to MVC 351


ASP.NET MVC Architecture ............................................................................................................351
ASP.NET MVC Framework .............................................................................................................352
New Features of ASP.NET MVC 4 ..................................................................................................355
Creating an MVC Application .........................................................................................................356

Chapter 15  Web Application Deployment 361


Deploying ASP.NET Website by Using the Copy Web Site Utility .................................................361
Publishing a Website ......................................................................................................................365
Using XCOPY Deployment.............................................................................................................366
Deploying by Using One-Click Publish ..........................................................................................368
InstallShield Limited Edition for Visual Studio 2012 .......................................................................370

Bonus Chapters Available with the book for Download

Chapter 1: Dynamic Data Controls


Chapter 2: Introducing Language-Integrated Query
(Companion code to download this chapter: ASP-9990-SS-364
URL: http://www.dreamtechpress.com/TitlePage.aspx?x=978-93-5004-999-0

viii
CHAPTER 1
Introducing Visual Studio 2012

What you will learn in this chapter?


 U nde rsta nding .N E T F ra me work
 G e tting S ta rte d with V isua l S tudio 2012
 Insta lling IIS 7.5
 V isua l S tudio 2012 Inte gra te d D e ve lopme nt E nvironme nt
 N e w F e a ture s in V isua l S tudio 2012 ID E
 V isua l C # 2012
 T he U sing S ta te me nt
 C omme nting the C ode s
 C re a ting a S imple W e b A pplica tion

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. .

Understanding .NET Framework


To understand ASP.NET T in depth, first, we have to understand .NET Frameworrk. The .NET Frameworkk is
a development and execution environment that allows developers to develop Windows applications as
well as Web applications. A program that is written to run under Microsoft Windows operating system is
called a Windows application. Web applications generally refer to programs that run on the Web server.
The .NET Frameworkk provides common platform to develop all types of applications, that is, Windows
applications or Web applications, by using a common set of tools, and also enables easy integration of
modules.

Need for .NET Framework


.NET Frameworkk was designed to achieve the following programming goals/objectives:
 Interoperabilityy: Supports communication between new and existing applications; and therefore,
.NET provides ways to use the functionalities that are present in programs and execute as
unmanaged code.
 Cross-Platform Supportt: Provides interoperability when each .N
NET compatible language, such as
VB.NET and C# #, provides its own compiler to compile code to Microsoft Intermediate Language
(MSILL). When the code is converted to MSIIL, the common runtime engine compiles the MSIIL to
native code with the help of the Just-In-Tim
me (JJIT) compiler, and then runs the application, as
shown in Fig.ASP- 1.1:

 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.

Components of .NET Framework


.NET Frameworkk provides an environment for building (or compiling), deploying, and running all types
of applications, such as Window ws, Web, and Consolle applications. Without .NET Framework, you
cannot develop different kinds of applications. The .NET Framework consists of many components, each
having its own importance. Some of the components are as follows:
 Common Language Runtime
 Assemblies
 Metadata
 Just-In-Time (JIT) Compiler
 Base Class Library (BCL)
Now, let’s discuss all the components of .NET Framework in detail.

Common Language Runtime


The Common Language Runtim me, popularly known as CLR, is the most important and main component
of .N
NET Frameworrk. Before explaining the CLR, let’s understand what a runtim me is? A runtimme is a
componen nt that a computer must have to execute programs written in a particular programming
language. The runtime of a language provides the basic features needed by the programs written in that
language to be executed successfully. When a program is executed, it links to the runtime of the
language in which it is written to get the basic functionality it requires.
For example, to execute a program written in Visual C# #, the computer executing the program must
have Visual C# runtime installed on it. This requirement of different runtimes for different programming
languages has made the task of the developers very tough. Developers cannot share the code written in
different programming languages; therefore, interoperability cannot be achieved.

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

The CLR provides the following services:


 Loading and execution of progra
am: Loads a program in the memory and executes it.
 Memory isolation for application ns: Performs the separation and allocation of memory for various
applications.
 Verification of type safetty: Verifies the data type of the variable.
 Compilation of MSIL to native cod
de: Compiles the intermediate language (IL) files into executable
code.
 Providing metadatta: Provides additional information about the assemblies in .NET applications.
 Interoperability with other system
ms: Supports communication with other systems or languages.
 Managing exceptions and errorrs: Reports the exceptions and errors in the code.
 Support for tasks, such as debugging and profilin ng: Supports debugging of the code written in
any language provided by the .NET framework.
Fig.ASP- 1.3 shows a flowchart of CLR activities that are carried out when an application is executed:

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

Base Class Library


.NET Frameworkk provides a huge set of the Frameworrk Class Libraryy (FCL) for common tasks. FCL contains
several classes to enable users to access the Windows AP PI and perform common functions, such as string
manipulation, common data structures, Input/output (IO), Web programming, and data access.

Versions of .NET Framework


The first version of .NET was released in 2002. Since then, Microsoft has continuously upgraded the
.NET framework and released new versions. The different versions of .NET framework are as follows:
 .NET Framework 1.0
 .NET Framework 1.1
 .NET Framework 2.0
 .NET Framework 3.0
 .NET Framework 3.5
 .NET Framework 4.0
 .NET Framework 4.5
Now, let’s learn about VS 2012.

Getting Started with Visual Studio 2012


To develop a .NET application, you must install the VS 2012 software on your computer, which enables
programmers to develop various types of applications including Console applications, Windows
applications, Web applications, and Web services. However, before you start the installation process;
several issues should be taken care in advance to minimize the chances of encountering problems, such
as the system requirements. After you have completed the installation process, you can further take
additional steps, such as registering the product and installing optional components.
In this section, you will learn about the system requirements for installing VS 2012, the different editions
of VS 2012, installing IIS 7.5, installing VS 2012, and opening VS 2012.

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

Table 1.1: System Requirements for Installing VS 2012


Hardware and Software Requirements
Random-Access Memory (RAM) Minimum: 1 GB RAM (1.5 GB, if running in a virtual machine)
Hard disk Minimum: 10 GB of available hard disk space
Hard disk performance 600 MB of available hard disk space (language pack)
5400 RPM hard drive
Digital Versatile Disc (DVD)-ROM Required
Drive
Display Video card that support DirectX 9
1024 × 768 display resolution or higher
Mouse Microsoft mouse or compatible pointing device

Editions of Visual Studio 2012


VS 2012 has been introduced in the market with different editions. Each edition has its own set of
features for different users. The various editions of VS 2012 are discussed as follows:
 Visual Studio 2012 Ultimatte: Provides an integrated environment of tools and the server that
simplifies the entire application development process. This edition of Visual Studio 2012 gives
results using productive, predictable, customizable processes. It increases transparency and
traceability throughout the Web page lifecycle. It lets you target different platforms and
technologies, including cloud computing and Windows Phone.
 Visual Studio 2012 Premiu um: Offers an environment that simplifies application development. It
contains advanced tools to solve the most difficult problems. In this edition, there are advanced
code analysis tools that help you avoid creating any run time error during the coding phase of
the application. In addition, advanced testing and debugging tools present in this edition let you
find and remove any run time error quickly. This edition manages the testing environment of the
application effectively. Moreover, you will be able to track every task and role in your business
and development teams.
 Visual Studio 2012 Professiona al: Simplifies the basic tasks of creating, debugging, and deploying
applications. It enhances creativity with powerful design surfaces and targets number of
platforms, such as Silverlight, SharePoint, and cloud applications. It also provides powerful, design-
centric tools such as CSS3 and HTML5.
 Visual Studio 2012 Test Professiona al: Simplifies the development of complex applications by
integrating the testers, product managers, and stakeholders in the development process. It
manages and executes test cases, defines requirements, retrieves customer’s feedback and traces
everything in the project till the final deployment.
 Visual Studio Tea am Foundatio
on Server 201 12: Provides sound communication among teams,
application lifecycle management tools to make that your application should be built fast and
accurate.

7
ASP.NET 4.5 in Simple Steps

Installing IIS 7.5


Before installing VS 2012, you need to install Internet Information Services (IIS) from the Control Panel.
IIS is required for the better performance of ASP.NET Web applications. IIS enhances the security,
reliability, and manageability of the Web application. Let’s perform the following steps to install IIS 7.5:
1. Click StartControl Pane
el, as shown in Fig.ASP- 1.4:

 Fig.ASP- 1.4

The Control Paneel window appears (Fig.ASP- 1.5).


2. Click the Program
ms option in the Control Pane
el window, as shown in Fig.ASP- 1.5:

 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

The Windows Feature es dialog box appears (Fig.ASP- 1.7).


4. Select the Internet Information Service
es check box (Fig.ASP- 1.7).
5. Click the OK button to start installing IIS in your system, as shown in Fig.ASP- 1.7:

 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.

Installing Visual Studio 2012


The installation process for VS 2012
2 is very easy. You have to follow some simple steps to complete the
installation successfully.
Let’s perform the following steps to install VS 201
12:
1. Insert the DVD-ROM of VS 2012 in the DVD-ROM drive. The set up file vs_ultimatte appears
(Fig.ASP- 1.9).

9
ASP.NET 4.5 in Simple Steps

2. Double-click the vs_ultimatte file, as shown in Fig.ASP- 1.9:

 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

98. Click the LAUNC


CH button to start the Visual Studio Ultimate 201
12, as shown in Fig.ASP- 1.16:

 Fig.ASP- 1.16

Opening Visual Studio 2012


After the installation process of VS 2012
2 is completed, you can open it by performing the following steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012, as shown in
Fig.ASP- 1.17:

 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

After the user settings are loaded, the Start Pag


ge of Microsoft VS 2012 appears.

Visual Studio 2012 Integrated Development Environment


The VS 2012 2 IDE provides an interface for developing various kinds of applications. The IDE is a
centralized location for developing these applications or components of applications as projects, which
provides the facility of writing code in .N
NET-compliant languages for these projects. The IDE supports
writing of accurate code in a faster way through code editors.
The VS 2012 IDE consists of the basic windows, which include:
 The Start Page
 The Toolbars

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.

The Start Page


The Start Page
e is the default page of VS 201
12, as shown in Fig.ASP- 1.20:

 Fig.ASP- 1.20

The Start Page


e displays the following panes and tabs:
 Starrt: Displays various hyperlinks—O Open Projecct hyperlink is used for opening an existing project,
the New Projecct hyperlink is used for creating a new project, and Connect to Team Foundation
Serveer hyperlink is used to connect to Team Foundation Server (TFS S) using Visual Studio 2012 ID
DE.
 Recent:: Displays a list of the most recent projects you opened with Visual Studio 2012 ID
DE. You
can open the projects by clicking the hyperlink having the project’s name.

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.

The Server Explorer Window


The Server Explore
er window shows a list of available servers in the network, as shown in Fig.ASP- 1.23:

 Fig.ASP- 1.23

The Server Explore


er window can be viewed by performing either of the following:
 Selecting VIEWServer Explorerr from the menu bar.
 Pressing the key combination Ctrl+Alt+
+S.
The list of services registered on each server and their status can be viewed by expanding the drop-
down hierarchical tree view through this window. The Server Explore er window also shows various event
logs that are used for performance checking and error tracking.
The toolbar of the Server Exploreer window contains the following buttons:
 Refreshh: Refreshes the Server Explorer window. It shows the list of the recently connected servers
whenever you click it. If a particular server or its services have stopped, then its name is not
reflected in the Server Explore
er window.
 Stop Refresh
h: Allows you to stop the refresh process.
 Connect to Database e: Enables developers to establish a connection to a database listed in the
Server Explore
er window through code.
 SharePoint Connectionns: Contains the URLs of all the sharepoint sites.
 Connect to Serverr: Enables developers to connect to a running server process listed in the Server
Explore
er window.

17
ASP.NET 4.5 in Simple Steps

The Solution Explorer Window


The Solution Exploreer window lists the solution name, the project name, and all the forms and modules
that are used in the project. A developer can open a particular file just by double-clicking its name.
The Solution Exploreer window is shown in Fig.ASP- 1.24:

 Fig.ASP- 1.24

The Solution Explore


er window can be viewed by performing either of the following:
 Selecting VIEWSolution Explorerr from the menu bar.
 Pressing the key combination Ctrl+Alt+
+L.

The Class View Window


The Class View window contains a hierarchical tree view representing the projects at the top-level node and
displaying the classes, methods, and properties associated with a particular project. It helps in finding a
member of a class that you want to work with. The Class Vie
ew window is shown in Fig.ASP- 1.25:

Object Pane

Member
Pane

 Fig.ASP- 1.25

The Class View


w window can be viewed by perform either of the following:
 Selecting VIEWClass Vie
ew from the menu bar.
 Pressing the key combination Ctrl+Shift+
+C.
The Class Vie
ew window is divided into two panes:
 Object pan ne: Displays an expandable tree of symbols, where the top-level nodes represent the
project references. This hierarchical view specifies the tree structure of the files or namespaces
included in the application.
 Member pan ne: Displays the list of members such as namespaces present in the application.

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.

The Properties Window


The Visual Studio 2012 IDE makes the task of designing a User Interface (UI) for Windows and Web
applications very easy by providing the Propertie
es window. Fig.ASP- 1.26 shows the Properties window:

 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.

The Document Outline Window


The Document Outlin
ne window displays an outline view of elements and scripts in the current document.
You can use this window to view the logical structure of your document. Fig.ASP- 1.27 shows the
Document Outline window:

 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.

The Object Browser Window


The Object Browser window is used to examine and find out objects, such as namespaces, classes,
structures, types, interfaces, enums, along with their members, such as properties, methods, events,
variables, constants, enum items. You can find these objects from the projects in your solution, the
referenced components added in the projects, and some external components. The Object Browser
window is shown in Fig.ASP- 1.28:

20
Introducing Visual Studio 2012

 Fig.ASP- 1.28

The Object Browse


er window can be viewed in either of the following:
 Selecting VIEWObject Browser from the menu bar.
 Pressing the key combination Ctrl+Alt+J.
In Fig.ASP- 1.28, you may notice that there are three different panes available in the Object Browser.
 Objects pane: Displays the ordered list of members of the hierarchical structures such as .NET
framework, COM components, namespaces, type libraries, interfaces, and classes. The
components and namespaces represent the top-level node in the object pane. To expand these
nodes, click the “|>” sign placed beside the node.
 Members pane: Displays the members of the item that you select in the Object pane. The
Members pane contains members such as properties, methods, events, constants, variables, and
enum values.
 Description pane: Displays the description of the item that you select in the Object pane. The
Description pane displays detailed information about an object or member that is currently
selected.

The Code Editor


The Visual Studio IDE provides a built-in and very advanced editor for writing the code for the .N
NET
projects. The Code Editor window supports the keywords and identifiers of the Visual Studio
environment. If Visual C# is chosen as the programming language for a .N NET project, then the Code
editor for this project only supports Visual C# syntax and not those of any other .NET programming
language.
This is true for other .N
NET programming languages also. By choosing a language option at the time of
creating a project, the Visual Studio 2012 IDE recognizes the language-compatible Code Editor that is
provided to the developer.
The Code editor recognizes keywords and identifiers of the programming language in use, and applies
proper colour-coding schemes and layout indenting to them. It checks and warns the developer for
syntax errors, incorrect initialization of variables, invalid declarations, and unrecognized procedure calls
by appropriately highlighting them.

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

The Code edito


or is accessed in any of the following ways:
 Double-clicking the control or the form in the Design view.
 Pressing the F7 key in the Design view or in the Source view.

The Design View


The Design
n view of VS2012 ID
DE allows a developer to design a user-friendly and customized Web Form,
as shown in Fig.ASP- 1.30:

 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.

The Source View


You can access the Source
e view of a Web page by clicking the Source tab present at the bottom of the
Visual Studio 2012 IDE. This view contains the Hypertext Markup Language (HTML) definition for the
Web Form and all the controls present in it. A sample code snippet of the Source view in which only the
presence of the Web Form is marked is shown here:
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
In the preceding code snippet, the Web Form is assigned a unique identity document (ID) (fo
orm
m1) to the
ID attribute of the <form> tag.
For example, if you drag and drop a Button n and a Labeel control on the Web Form either in the Design
view or in the Source vie
ew, you see that their equivalent HTML tags are induced into the Source vieew.
You can also see that the previous code snippet in the <body> </body> tag is now transformed as
shown here:
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</div>
</form>
</body>
In the preceding code snippet, a unique ID was assigned for the Buttoon and the Labe
el controls. VS 2012
provides this ID automatically. In addition, a default text is also provided for each control. You can
change the default text of the controls.
As you customize a control’s appearance by setting different properties through the Properties window,
these are reflected in the HTML tag for that control in the Sourcce view. The following is the sample
Source vie
ew code snippet that shows the effect of setting various properties for these controls, such as
changing their position on the Web Form, redefining border colour and style, and changing back colour
and fore colour:
<asp:Button ID="Button1" runat="server" Text="Button" style="z-index: 102;

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 shows the Source vie


ew of the Web Form:

 Fig.ASP- 1.31

The Output Window


The Output window displays the result of building and executing applications. To view the Output
window, select VIEWOutpu ut. An alternate way of opening the Output window is by pressing the
CTRL+ALT+O keys together. Fig.ASP- 1.32 displays the Output window:

 Fig.ASP- 1.32

The Error List Window


The Error List window helps you to accelerate application development by displaying all the errors in a single
window such as syntax errors noted by IntelliSense. Whenever you edit and compile the code, the errors,
warnings, and messages that occur are displayed in the Error List window. By double-clicking any error
message entry, you can open the file where the error has occurred, and move to the error location. You can
EW  Error Lisst or by pressing the CTRL+E keys together.
view the Error List window by selecting VIE
Fig.ASP- 1.33 shows the Error List window:

24
Introducing Visual Studio 2012

 Fig.ASP- 1.33

The Error List toolbar consists of the following buttons:


 Errorrs: Displays the number of errors in the list.
 Warning gs: Displays the number of warnings in the list.
 Message es: Displays the number of messages in the list.
The various UI elements present below the Toolbar are as follows:
 Categorry: Displays a list of the type of error list entry.
 Default Orde er: Displays the order number in which an entry was generated.
 Descriptio on: Displays the description of the error, warning, or message entry. Lengthy
descriptions are wrapped into additional lines.
 Fille: Shows the file name only or the full path of the file along with the file name.
 Lin
ne: Shows the line number in the code where the error occurred.
 Colum mn: Shows the column number in the line where the error occurred.
 Projecct: Shows the project name in which the error occurred.

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.

New Features in Visual Studio 2012 IDE


The Visual Studio 2012 IDE contains many new features to make the development process faster and
easier. Some useful enhancements are as follows:
 Projects and Solutions
 Window Management
 Search
 Code Editing for C++
 Multibrowser Support
 Page Inspector
 HTML Editor
 CSS Editor
 JavaScript Editor
Let’s learn each of the feature and enhancements done in Visual Studio 2012.

Projects and Solutions


The various enhancements and features included in Visual Studio 2012 are as follows:

Visual Studio 2012 Compatibility


Before the advent of Visual Studio 2012, when an older version of Visual Studio project is opened in a
newer version, Visual Studio automatically opens the Conversion wizard, which upgrades the older
version project to the newer version. After the project is converted to the newer version, it can be easily
opened in the newer version of Visual Studio; however, the same project cannot be opened in the older
version from which it was derived. This backward compatibility issue is removed to some extent in Visual
Studio 2012. This implies that after the conversion, the Visual Studio 2010 project can be opened in
Visual Studio 2012 as well as in Visual Studio 2010. This feat is achieved by Microsoft in Visual Studio
2012 by adding some backward compatibility properties in the converted file, which are given as
follows:
 FileUpgradeFlag gs: Sets a flag for file upgrade. The upgrade process of the project file utilizes this
property, which has no impact on working with the project in Visual Studio 2010 and Visual
Studio 2008.
 UpgradeBackupLocatio on: Upgrades the backup location.
 OldToolsVersio on: Stores the version of Visual Studio for the older version project.
 VisualStudioVersioon: Stores the version of Visual Studio for the newer version project.
 VSToolPatth: Uses the path of MSBuildExtensionsPath32 to find the target file that needs to be
imported.

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.

Browse code in Solution Explorer


In Visual Studio 2012 you can perform the tasks such as browse members in your projects, search symbols,
determine symbol references, and view method’s Call Hierarch hy without interchanging between multiple tool
windows by using the Search box in the Solution Explore
er window as shown in Fig.ASP- 1.35:

 Fig.ASP- 1.35

Install Online Samples


You can download and install samples online from the MSD DN code gallery. These samples help you to
learn about new technologies and allow you to create projects on these new technologies, as shown in
Fig.ASP- 1.36:

 Fig.ASP- 1.36

Solutions Load Asynchronously


In Visual Studio 2012, the projects can now be loaded asynchronously, and the important elements of
the solution get loaded first, to make you work faster.

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

Preview files in the Code Editor


You can preview files in the code editor of Visual Studio 2012 at the time of debugging. You can choose
these files in the Solution Explore
er window in order to preview in the editor. The file preview is shown on
the right side of the document tab, as shown in Fig.ASP- 1.37:

 Fig.ASP- 1.37

Access Frequently Used Files More Easily


You can pin the files that are required frequently on the left side of the editor in tabs using the pin on the
files as shown in Fig.ASP- 1.38:

 Fig.ASP- 1.38

28
Introducing Visual Studio 2012

Arrange Windows on Multiple Monitors More Effectively


The Multi-Monitoor Support feature allows you to slide and split code window, designer window, and
other windows in the IDE. You can drag and slide the IDE windows to any location in a monitor
(Fig.ASP- 1.39). You can do this by right-clicking the form window and selecting the Float option from
the context menu, as shown in Fig.ASP- 1.39:

 Fig.ASP- 1.39

Change the Colour Scheme of the IDE


You can customize the Visual Studio 2012 editor in several ways such as by changing the font style and
colour of the editor. You can change the colour and font style of the editor using the Options dialog box
that can be opened using the TOOLS Options menu as shown in Fig.ASP- 1.40:

 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

Search in Tool Windows


In the Visual Studio 2012, a search box is provided in the Toolbo
ox window in order to search controls in
the Toolboox window. This prevents a developer from opening every node and search for a particular
control. The enhanced Toolbo ox is shown in Fig.ASP- 1.42:

 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

Code Editing for C++


The enhancements done in the code editing for C++ in the Visual Studio 2012 editor are as follows:
 Specify more semantic colourization:
 In Visual Studio 2012, more tokens are made colourful by default and you can also specify more
colourization in the editor.
 Use improved reference highlighting:
 In Visual Studio 2012, you can highlight all the instances of a symbol by using the Ctrl+Shift+Up
Arrow or Ctrl+Shift+Up Arrow keys.
 Choose member functions as you type:
 In Visual Studio 2012, the Intellisense in improved in code editor of C++. The List members List
appears when you enter some text in the code editor.
 Take advantage of C++/CLI IntelliSense:
 The IntelliSense features such as Quick Info, Parameter Help, List Members, and Auto
Completion are now supported in C++/CLI .
 Speed up your coding by using code snippets:
 The code editor of C++ in Visual Studio 2012 now supports code snippets that appear during
the code editing. You can use these code snippets to complete the required logic of a program.

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

Schema Switching Based on Document Type


A schem
ma allows you to determine which elements, attributes, and capitalization are legitimate in that
schema. Visual Studio 2012 allows you to choose schema for the project by providing the Target
Schema for Validatio
on drop-down list box as shown in Fig.ASP- 1.48:

 Fig.ASP- 1.48:

Tag Completion when Renaming Tags


This feature helps you in renaming the matching tag automatically if you try to change the name of any
tag. For example, if you rename the HTM ML <divv> tag to the <headerr> tag, then the corresponding
closing tag also changes automatically at the same time. This feature is very useful as it reduces the
unintentional errors in the document if you forget to rename the matching closing tag. The renaming of
<divv> tag to <headerr> tag is shown in Fig.ASP- 1.49:

 Fig.ASP- 1.49

Extract Selected Markup to a User Control


This feature allows programmers to move individual pieces of a Web page content that can be grouped
together into a logical unit such as user controls. This helps in refactoring the page, increases the
readability of the page, and simplifies the page structure. To use the extract to user control feature while
editing Web Form pages in Source e view, select the text that can be moved into a user control and then
right-click the selected text to display the contexxt menu. Further, select the Extract to User Contro
ol option
from the context menu, as shown in Fig.ASP- 1.50:

 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

Smart Indentation for Empty Elements


This feature puts the insertion point automatically to the correct place after you press the Enter key while
inside the empty HTM ML element. For example, suppose the insertion point is inside the empty <headerr>
element, as shown in Fig.ASP- 1.53:

 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

Event Handler Generation in Source View


This feature generates event handler in Sourcce view and can be bound to event manually. When you
press the equa al to sign (=) after the event name, the IntelliSensse for event handler is displayed
containing the Create New Evennt option, as shown in Fig.ASP- 1.55:

 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:

Auto-reduce Statement Completion


This feature displays a list of options in the IntelliSensse for CSS that matches with the letters typed in the
.ccss file. The individual words matching with the title case of the typed words are also displayed in the
IntelliSensse list. The advantage of the auto-reduce statement completion feature is that it makes
statement completion faster for known properties and values. For example, if you type mw in the body
property, then the IntelliSense list shows the options, max-width and min-width, which match the title
case, as shown in Fig.ASP- 1.58:

 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

CSS Hacks Support


This feature supports the most prevalent CSS hacks, such as validation of star (*) and underscore (_)
hacks. The support uses IntelliSense and performs validation. The IntelliSense for the validation of * and
_ property hacks is shown in Fig.ASP- 1.61:

 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

Commenting and Uncommenting Support


This feature supports commenting and uncommenting of CSS rules. To comment the text, select the text
and press the keyboard shortcut (C Ctrrl+K
K, C), whereas to uncomment the selected text, press the
keyboard shortcut (C
Ctrll + K , U). The same shortcuts can also be used in the code editor for commenting
and uncommenting text. The selected text being commented using the shortcut in the .css file is shown in
Fig.ASP- 1.64:

 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

The code can then be customized according to need.

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.

Let’s now learn about Visual C# 2012.

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.

New Features in Visual C# 2012


C# in VS 2012 is based on dynamic programming, which means that the objects of the programs are
dynamic. The structure and behaviour of objects cannot be called class members with static data type.
The new features of C# are as follows:
 Async and awaitt: Uses .NET Framework 4.5 and Windows Runtime to create async methods. An
async method is used to execute a time-consuming thread without forcing the caller’s thread to
wait. In other words, the caller’s thread can resume its work without waiting for the async method
to finish, while the async method continues to perform its lengthy task in the background. In
addition, an async method returns a task that contains information, such as status, ID, or result,
for the caller thread to use. The method also contains at least one await expression to suspend
the execution of a thread until awaited thread completes. In the meantime, the control is returned
to the caller of the suspended thread. In contrast, the traditional asynchronous coding requires

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.

The Visual C# 2012 Keywords


Keywords are those words whose meanings are predefined to the C# compiler. You cannot use them as
variable names, methods, and properties because their names have already been defined as a special
functionality. These words are reserved for language-specific tasks.
Table 1.2 lists the various keywords present in C#:

41
ASP.NET 4.5 in Simple Steps

Table 1.2: Various Keywords in C#


abstract as base bool Break byte case
catch char checked class const continue decimal
default delegate do double while enum event
else extern false finally fixed float for
foreach goto if implicit in int is
internal lock long Main namespace new null
object operator out override params private protected
public readonly ref return sbyte sealed short
sizeof stackalloc static string struct switch system
throw true try typeof uint ulong unchecked
unsafe ushort using virtual volatile void

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.

Visual C# 2012 Statements


A statement represents a complete instruction in a program. A Visual C# 2012 statement is made up of
the following parts:
 Keywords:: Includes predefined words used to work with the languages such as Visual C#.
 Operators:: Includes the symbols, such as +, −, and *, to perform operations, such as addition,
subtraction, and multiplication, respectively.
 Variables: Includes the words or alphabets that are used for storing the values used in a
program.
 Literals: Represents values such as integer or String.
 Constants: Represents those variables whose values cannot be altered.
 Expressions: Represents the combinations of operator and operand that yield a value. For
example, if the variable marks holds the value 78, then the expression, marks + 4, yields the
value 82.
Each Visual C# statement is one or both of the following:
 A declaration statement that can name and create a variable, constant, or procedure, and can
also specify a data type, such as Boolean, Byte, Char, and Date.
 An executable statement performs an action. These statements execute a method or function or
loop through the code repetitively or can be an assignment statement that assigns a value or
expression to a variable or constant.

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

Table 1.3: Syntax Explanation


Parts Explanation
Read Only Specifies that the variable only can be read and not written.
Variable list Gives a list of variables declared in this statement.

Each attribute in the attribute list must use this syntax:


[attributemodifier] attributename [( attributearguments | attributeinitializer)]
Table 1.4 provides a detailed explanation of the parts of the preceding syntax:
Table 1.4: Attribute List Syntax Explanation
Parts Explanation
Attribute modifier Modifier, such as assembly or modules, required for attributes applied at the
beginning of a source file
Attribute name Name of the attribute.
Attribute arguments List of arguments for this attribute. Separate multiple arguments with commas.
Attribute initializer List of field or property initializers for this attribute. Separate multiple arguments
with commas.

The Using Statement


The Using statemen nt is used to import a namespace, so you do not have to qualify items in that
namespace by listing the entire namespace when you refer to them. For example, to use classes and
methods for file handling, which is present in the System.IO namespace, you just need to include the
namespace System.IO. If you do not include the namespace, the classes and methods referring to
them are not displayed in the code file. The StreamWriter class is only displayed when the System.IO
namespace is included using the statement as follows. The Write method of the StreamWriter class
writes the text in the text file, as shown in the following code snippet:
using System.IO;
protected void Button1_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter("C:/abc.txt");
sw.Write("hello! i am new file");
}

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

const [ <attrlist> ] [ accessmodifier ] constantlist


Some of the keywords of the preceding statement have already been defined in Table 1.3. The
definitions for the remaining are as follows:
 Constant list:: Displays list of constants declared in the statement. Each constant in the constant
list must use the following syntax and parts:
[type] name= initexpr
 Name:: Declares the name of the constant. You can declare as many constants as you like in the
same declaration statement, specifying the name and initexpr parts for each. Multiple
constants are separated by commas.
 Typ
pe: Represents the data type of the constant. It can be Boolean, Byte, Char, Date, Decimal,
Double, Integer, Long, Object, SByte, Short, Single, String, UInteger, ULong, or UShort. It can
also be the name of an enumeration.
 Initexpr:: Represents an initialization expression.
Multiple constants can be separated with the help of commas as shown here:
constant[ , constant ... ]
Here, it is shown how to declare and use a constant. In this case, we create a constant named Pi and
variables named as Area and Radius. We then use the *(multiplication) operator to find the area of a
circle and display the result:
protected void Button1_Click(object sender, EventArgs e)
{
const double Pi = 3.14;
double Radius,Area ;
Radius = 2;
Area = Pi * (Radius * Radius);
Response.Write("Area = " +Area);
}

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

Table 1.5: Variable Prefixes


Date Type Prefix
Object Obj
Single Sng
String Str
User-defined type Udt

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.

Introducing Data Types


A data typ
pe determines the type of data that is stored in a variable. It can be Strin
ng, Intege
er, or Boolea
an.
For creating a new variable, we should first know the range of possible values a particular variable type
allows. Table 1.6 lists the data types of Visual C# 201
12:
Table 1.6: Visual C# 2012 Data Types
Type
e Size Rang
ge
Boolean Depends on True or False
implementing
platform
Byte 1 byte 0 through 255 (unsigned)
Char (single character) 2 bytes 0 through 65535 (unsigned)
Date 8 bytes 0:00:00 (midnight) on January 1, 0001 through
11:59:59 PM on December 31, 9999
Decimal 16 bytes 0 through +/-
79,228,162,514,264,337,593,543,950,335 (+/-
7.9...E+28) with no decimal point; 0 through +/-
7.9228162514264337593543950335 with 28
places to the right of the decimal;
smallest nonzero number is +/-
0.0000000000000000000000000001 (+/-1E-28)
Double (double-precision 8 bytes -1.79769313486231570E+308 through -
floating-point) 4.94065645841246544E-324 for negative values;
4.94065645841246544E-324 through
1.79769313486231570E+308 for
positive values
Int 4 bytes -2,147,483,648 through
2,147,483,647 (signed)

47
ASP.NET 4.5 in Simple Steps

Table 1.6: Visual C# 2012 Data Types


Type
e Size Rang
ge
Long (long integer) 8 bytes -9,223,372,036,854,775,808 through
9,223,372,036,854,775,807 (9.2...E+18) (signed)
Object 4 bytes on 32-bit 8 bytes on 64-bit platform Any type can be stored in
platform a variable of type Object
SByte 1 byte -128 through 127 (signed)
Short (short integer) 2 bytes -32,768 through 32,767 (signed)
Single (single-precision 4 bytes -3.4028235E+38 through -1.401298E-45 for
floating-point) negative values; 1.401298E-45 through
3.4028235E+38 for positive values
String (variable-length) Depends on 0 to approximately 2 billion Unicode characters
implementing
platform
UInt 4 bytes 0 through 4,294,967,295 (unsigned)
ULong 8 bytes 0 through 8,446,744,073,709,551,615 (1.8...E+19
) (unsigned)
User-defined (structure) Sum of the sizes of its members. Each member of the structure has a range
determined by its data type and independent of the ranges of the other
members.
UShort 2 bytes 0 through 65,535 (unsigned)

Converting Data Types


When you have to convert variable of one data type to another, we should first know if the conversion is
possible or not. Conversion between two data types is possible only when they are compatible. Visual
C# 201 12 provides some conversion functions, which are useful for conversion between incompatible
data types, as shown in the following Table 1.7:
Table 1.7: Conversion Methods
Conversion method Description

To Boolean Converts a value to a Boolean value, if possible


To Byte Converts a value to byte
To Char Converts a value to a single character (Unicode), if possible
To DateTime Converts a value to date-time structures
To Decimal Converts a value to decimal values

48
Introducing Visual Studio 2012

Table 1.7: Conversion Methods


Conversion method Description

To Double Converts any value to a double type


To Int16 Converts any value to an int type
To Int32 Converts any value to a long integer
To Int64 Converts any value to a long integer
To Sbyte Converts a given value to a signed byte field
To Single Converts any value to a small floating-point number
To String Converts virtually any value to a string
To UInt16 Converts to an unsigned int data type
To UInt32 Converts to an unsigned long data type
To UInt64 Converts to an unsigned big integer

The Arithmetic Operators


Almost all the computer programs perform arithmetic operationss, such as subtractio
on, multiplicatio
on,
and divisio
on. You must have the knowledge of all the operatorrs used in Visual C#. The list of six
arithmetic operators present in Visual C# is given in Tables 1.8, 1.9, and 1.10.
Table 1.8 shows the use of the plus (+
+) operator for addition and minus (-) operator for subtraction:
Table 1.8: Arithmetic Operators—Addition and Subtraction
Operatio
on Example Resullt
Addition 17 + 2 19

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

Table 1.10: Arithmetic Operators—Integer Division and Modulus


Operatio
on Example Result after divisio
on Final resullt
Integer division 5\2 2; Remainder 1 2

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.

Commenting the Codes


When we want to add some more text besides the program code segment to make it more
understandable for the reader, we can put it as a comment. In simple words, comments provide
additional information to the developer about the code. Comments enhance the understandability of the
code. It is considered as a very good practice to write comments wherever required. Comments in Visual
C# start with a double forward slash (//)), and whatever follows these slashe
es is ignored by the compiler.
This type of comment is called single-line comment. There is also another kind of comment in C# called
multiline comment that is used to comment multiple lines of text or code. The multiline comment starts
with symbols (/*) and ends with symbols (*/). We can write comments in our code as follows:
/*Program to create
new file using namespace*/
protected void Button1_Click(object sender, EventArgs e)
{
//creates a new file abc
StreamWriter sw = new StreamWriter("C:/abc.txt");
//This writes the text in the file.
sw.Write("hello! i am new file ");
}

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#.

Creating a Simple Web Application


ASP.NET promotes rapid development of Web applications. With the help of ASP.NET, creation of Web
applications has been made a very easy task.
Let’s first learn to create a simple Web application using VS 2012 which accepts a user’s name in a
Textbox and displays it on a label after the user clicks a button.
Let’s perform the following steps to create a simple Web site:
1. Click Start  All Programs  Microsoft Visual Studio 2012  Visual Studio 2012. The Start Page
of Microsoft Visual Studio IDE opens (Fig.ASP- 1.70).
2. Click New Project link to create a new Web site, as shown in Fig.ASP- 1.70:

51
ASP.NET 4.5 in Simple Steps

 Fig.ASP- 1.70

The New Projecct dialog box appears (Fig.ASP- 1.71).


 Templates node to expand it (Fig.ASP- 1.71).
3. Click the Installed
A new list of option appears under it (Fig.ASP- 1.71).
4. Click the Visual C# node to expand it (Fig.ASP-1.71).
5. Click the Web option from the list present under the Visual C# node (Fig.ASP- 1.71).
There are two options to create a Web application:
 ASP.NET Web Forms Application
 ASP.NET Empty Web Application
You can use any option to create a Web application.
Here, we are creating Web application by selecting ASP.NET Empty Web Application option for
simplicity.
6. Select ASP.NET Empty Web Application from the middle pane of the window (Fig.ASP- 1.71).
7. Enter a name for the Web application in the Name
e text box (Fig.ASP- 1.71). In this case, we are
taking the default name, WebApplication1.
8. Enter a location to save the Web application in the Location text box (Fig.ASP- 1.71). In this case,
we are selecting D:\Simple Step.
9. Click the OK button to create the Web Application, as shown in Fig.ASP- 1.71:

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

The Source vie


ew of the Web Form displays.
15. Select Desig
gn from the leftmost bottom of the window.
The Design vie
ew of the Web Form appears (Fig.ASP- 1.74).
16. Click Toolbo
ox option on the leftmost side of the window.
The Toolbo
ox window appears (Fig.ASP- 1.74).
17. Double-click the Labe el control to add it on the Web Form (Fig.ASP- 1.74).
Similarly, double-click the TextBo
ox and Butto
on controls to add it on the Web Form (Fig.ASP- 1.74).
8. Click anywhere on the Web Form or outside the Toolbo
18 ox window, as shown in Fig.ASP- 1.74:

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. Set the Texxt property for Button


n1 as CLICK HER
RE, as shown in Fig.ASP- 1.77:

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

The Web application code window (WebForm1.aspx.cs) for C# appears.


23.. Write the code in the WebForm1.aspx.css file as follows:
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text += TextBox1.Text;
}
The Text property of Labell1 is assigned the text contained in the TextBoxx1‘s Text property. To
retain the initial text that is displayed on Labell1, a new text from the TextBoxx1 is appended to
Labell1. You can incrementally assign the text by using the += operator for including a white
space between the previous text on Labell1 and the new text.
4. Execute the application by pressing the F5 key. When the Web Form is loaded in the browser,
24
Labell1 displays the text HELLO WORLD FROM and Button n1 displays CLICK HER RE.
25. Enter a name in the TextBo ox and click the CLICK HER RE button to submit the data.
The text that you have entered in TextBo ox is displayed along with the text HELLO WORLD FROM M :,
as shown in Fig.ASP- 1.79:

 Fig.ASP- 1.79

Now, you have successfully created an ASP.NET Web application.


SUMMARY
In this chapter, you have learned about:
 The .NET Framework that allows developers to develop Windows applications as well as Web
applications.
 Visual Studio 2012, which included installing Visual Studio 2012, to learn how to develop various
types of applications.
 The IDE of Visual Studio 2012 that provides the facility of writing code in .NET-compliant languages.
 The new features in Visual Studio 2012 IDE that make the development process faster and easier.
 Visual C# 2012 that provides new features such as new compiler features, new language constructs,
and improved debugging.
 The procedure to comment the code.
 The procedure to creating a simple Web application that accepts a user’s name in a Textbox and
displays it on a label.

56
CHAPTER 2
Web Application in ASP.NET 4.5

What you will learn in this chapter?


 U sa ge of W e b A pplica tions
 Improve me nts in A S P .N E T 4.5
 C oding T e chnique s in W e b A pplica tion

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.

Usage of Web Applications


In today’s world, Internet plays an important role in our daily life. The free electronic mail (e-mail)
service, which is available on most of the Web sites, has become the most common medium of
communication. People prefer to shop things online because they do not have enough time to visit
market places. In other words, modern men have become totally dependent on the Internet to carry out
activities besides the official work, for example, online bill payment, online railway reservation,
searching for suitable matrimonial pairs, and many more. Even offices nowadays are dependent on the
Internet to get their day-to-day work done. The Internet, serving as the ultimate repository for Web sites
or Web applications, has made our life smooth in this fast-paced world by bringing everything within
our reach.
ASP.NET 4.5 in Simple Steps

Business Usages of Web Applications


Nowadays, most of the application software packages are available over the Internet, whereas earlier,
we had to buy the same software in the form of compact discs (CD). Most of the browser interfaces
support these application software packages and there is no need to install them on the local hard
drive. Therefore, nowadays, companies use such software by paying a monthly or yearly rent to the
application service provider.

Modern Usages of Web Applications


Over the years, Web applications have gone through many changes with new features and
functionalities added to them. With many new enhancements, the concept of the blog
gs and communitty
portals came into picture.
Blog
gs are Web contents, which are the textual, visual, or aural contents that are regularly updated by the
user based on their experience, more similar to a diary or journal created by individuals. The entries
made here on a daily basis are in the order such that the latest entry is on the top. People write blogs to
share their experiences, poems, pictures, links, and so on. Blog gs consist of periodic articles. The
popularity of blog
gs is increasing over the years.
The Communitty porta al is also a medium of interaction. Communities can be of same caste, same
educational institute, same school, same company, and many more topics. There are several
communities available on the Internet. You can also create your own community. Now, let’s move on to
discuss the .NET Framework.
ASP.NET, as we have discussed earlier, is a technology to develop content-rich dynamic and
personalized Web sites. The fundamental component of ASP.NET is a Web Form, which is a Web page
that users can view in a browser. Now, let’s discuss it in more detail.

Improvements in ASP.NET 4.5


Developing ASP.NET Web applications in the .NET Framework is similar to developing Windows
applications. The most important component of ASP.NET is a Web Form. With the release of ASP.NET
4.5, many enhancements have been done to make a Web page more user friendly, secure, and
dynamic, and also to make the Web site development easier and faster. The following is the list of
enhancements and changes done in ASP.NET 4.5:
 ASP.NET 4.5 Core Services
 ASP.NET 4.5 Web Forms
 ASP.NET Web Pages 2
 General Enhancements for Web Development
 Data-Related Enhancements for Web Development
 IIS Express for Web Development
 ASP.NET Web API
 ASP.NET MVC 4, Web API, and ASP.NET Web Pages (Razor) are now Open Source
Let’s discuss about each of them in detail.

58
Web Application in ASP.NET 4.5

ASP.NET 4.5 Core Services


ASP.NET 4.5 core services include features, such as Bundling, Integrated Anti-XSS encoding routines,
and minification. The important ASP.NET core services are as follows:
 Asynchronously reading and writing HTTP requests and responsess: Specifies the capability of
reading a Hypertext Transfer Protocol (HTTP) request entity asynchronously. ASP.NET 4.5 also
allows double buffering of the HTTP request entity which integrates downstream HTTP handlers
with.aspx page and ASP.NET Model View Controller (MVC).
 New ASP.NET request validatio on: Enables you to read invalidated request data even when the
request validation is enabled. ASP.NET 4.5 introduces two features to work with invalidated input
as lazy request validation and access to invalidated request data. In ASP.Net 4.5, by default, all
the requests are validated. However, developers can also configure application to accept request
validation before accessing the actual requested data. This validation is referred to as the lazy
validation and can be enabled by adding the following code in the Web.config file.
<httpRuntime requestValidationMode="4.5" ... />
ASP.NET 4.5 also allows access to invalidated request data. A new Unvalidated collection
property in the HttpRequest class has been added to provide access to requested data such as
Form, QueryString, Cookies, and Url. To use this property first you set the requestValidationMode
= “4.5” in httpRuntime element in the Web.config file as shown above. After that you can use the
HttpRequest.Unvalidated property to read the invalidated form value through the following code
in your code-behind file:
var s = context.Request.Unvalidated.Form["forum_post"];

 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.

ASP.NET 4.5 Web Forms


The Web Forms form an integral part of ASP.NET applications. These have been enhanced several times
since release of ASP.Net. In ASP.NET 4.5, the following new features are introduced for Web Forms
which are as follows:
 Model Binderss: Allows you to bind data controls directly with data-access methods. This feature is
similar to model binding that is used in ASP.NET MVC.

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

ASP.NET Web Pages 2


ASP.NET Web Pages 2 allows developers to easily combine server code with HTML to create lightweight
dynamic web content. ASP.NET Web Pages 2 allows developers to easily connect to database and add
video and link for social networking sites to develop Web sites according to the modern standards.
Let’s explore new features and enhancements in ASP.NET Web Pages 2.
 New and enhanced site templatess: Specifies the inclusion of personal site templates, starter site
templates, and upgradation of Web Pages 1 templates to run on Web Pages 2. The personal site
templates provide Web pages for a blog, photo gallery, and Twitter. On the other hand, the
starter templates have been updated to allow users to sign in to Web sites by using their
Facebook, Twitter, or Windows Live account.
 Razor syntax improvementss: Provide conditional HTML attributes, which reduce the complexity to
render the attributes based on the values that you mention in your code. For example, the ~/
syntax allows you to render links of dynamic path information and URLs.
 Validation
n: It is used for validating user input which includes client-side validation, and it
helps in improving the performance of your Web site. Two new validation classes,
ValidationHelper and Validator, are also included that helps in specifying the validation rules
by writing few lines of code.
 Side-by-side supportt: Allows you to execute the Web Pages 1 applications and Web Pages 2
applications on the same computer.
 Membership and authenticationn: Includes two new authentication providers, OAuth and OpenID,
which allow users to sign in using external sites credentials, such as Facebook, Twitter, and
Windows Live.
 Map helperr: Allows you to use already existing search engines, such as Bing, Google, and
Yahoo, and extracts map on your Web site.
 Mobile display modess: Allows you to create device-specific Web pages, which render
automatically on a mobile device.

General Enhancements for Web Development


The general enhancements done for Web Development by including new features in ASP.NET 4.5 are as
follows:
 Use the most recent Web standardss: Specifies the enhancements done in various editors, such as
HTML editor and CSS editor. Now, the HTML editor fully supports HTML 5 elements and snippets.
Moreover, the CSS editor now also supports CSS3, CSS hacks, and CSS snippets specific to
vendors CSS extensions.
 Test the same page, application, or site in a variety of browserss: Specifies that you can test your
application in multiple browsers.

62
Web Application in ASP.NET 4.5

 Quickly find the source of rendered markup


p: Specifies the opening of file in which the markup
was present by using the Page Inspector. The file gets opened with in Visual Studio IDE on
choosing the rendered element.
 Find snippets and code elements quickly by using improved IntelliSense:: Specifies the display of
list of options on entering the text in the editor, such as CSS editor and HTML editor. This feature
shows options on the basis of the typed text.
 Select markup and extract it to a user control:: Allows you to build markup in order to use them in
more than one location and multiple times.
 Create and edit code and markup more easilyy: Helps you in renaming the matching tag
automatically if you try to change the name of any tag. For example, if you rename the HTML
<div> tag to the <header> tag, then the corresponding closing tag also changes automatically
at the same time.
 Create CSS more efficiently:: Allows you to build CSS in an organized manner by using new
features, such as expansion and collapse of new sections, and use of hierarchical indentation.
Moreover, you can comment and uncomment the blocks of code in CSS editor. It also now
includes a colour selector similar to HTML editor.
 Write JavaScript in the JavaScript editor:: Allows you to create JavaScript code in the JavaScript
editor. The JavaScript editor includes completely new features that improve the working
experience with JavaScript in Visual Studio. The editor provides the features, such as code
outlining, brace matching, Go to Definition, ECMAScript5, DOM IntelliSense, VSDOC
signature overloads, implicit references, set a breakpoint within a single line of code, control
objects available in global scope and View statement completion for identifiers.
 Deploy web application projects more easily:: Helps you in deploying your Web applications
easily. Moreover, you can also import publish settings from hosting providers, such as
specification of transformations of the Web.config file for a publish profile, storage of credentials
that are in encrypted form in the publish profile, specification of the build configuration in the
publish profile, and preview of updates related to deployment of Web application.

Data-Related Enhancements for Web Development


The data-related enhancements made in ASP.NET 4.5 for Web application development are as follows:
 Automate validation for frequently used data types:: Helps you to automate validate for
commonly used data types. You can use DataAnnotation attributes in order to automate data
types, such as e-mail address, telephone number, and so on.
 Deploy incremental database updates:: Allows you to update the database schema deployed with
a project with the new schema automatically on its deployment.

63
ASP.NET 4.5 in Simple Steps

IIS Express for Web Development


IIS Express is provided as a default Web server for testing Web-based projects. It is a lightweight,
independent version of IIS that includes all the essential abilities of the IIS Web server role. However, IIS
Express is still an option to be used as a local Web server during Web development; however, Microsoft
recommends IIS Express.

ASP.NET Web API


ASP.NET Web API is a Framework that allows you to build HTTP services, such as browsers and mobile
devices. It provides an ideal platform for developing Representational State Transfer (RESTful)
applications by using the .NET Framework. Some of the important features of ASP.NET Web API are as
follows:
 Easily build and consume HTTP services that reach a broad range of clients:: Allows easy building
of HTTP services that are accessible by a broad range of clients. These services can be used by
software, such as browsers, mobile applications and hardware, such as tablets and similar kind
of devices. Moreover, these services have inbuilt support for negotiation of content that helps in
determining correct format of data.
 Directly access and manipulate HTTP requests and responses by using a modern HTTP
programming modell: Allows direct access and manipulation of HTTP requests and responses with
the help of modern HTTP programming model that is supported both on the server and on the
client. The Web APIs can be called from any .NET Framework application using new HttpClient API.
 Easily extract data from an HTTP requesst: Allows you to retrieve data from different sections of an
HTTP request by using model binders. This feature is similar to model binding used in ASP.NET
MVC.
 Enjoy a full set of routing capabilities:: Provides supports of full routing capabilities in ASP.NET
MVC and ASP.NET by ASP.NET Web APIs. The routing capabilities include route parameters and
constraints.

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.

Coding Techniques in Web Application


ASP.NET 4.5 coding techniques are the methodologies used for writing code in a Web application.
ASP.NET 4.5 supports two different coding techniques, namely, single-file page model and code-behind
page model. In the single-file coding approach, developers write code directly in the .aspx page of the
application. However, the major drawback of this coding model is that you need to write the code to
implement various functionalities of a Web application and the HTML code in a common (same) file.
This way the code inside the .aspx file becomes quite complex and difficult to manage, especially while
building large applications. To deal with this drawback of the single-file page model, ASP.NET 4.5
includes the code-behind page model, where you need to maintain separate code files for each Web
page. One file stores the code to implement the functionalities of a Web page written in some
programming language, such as VB.NET and C#, and the other file stores the HTML markup of the
Web application.
Let’s discuss the single-file page and code-behind model in detail:

The Single-File Page Model


In the single-file page model, you need to write the language script code to implement the functionalities
of a Web application and the HTML code in the same file, but in separate sections.

The Code-Behind Model


In the code-behind page model, there are two separate files, namely, Default.asp px and either one of
WebForm..aspx.ccs or WebForm..aspx.vvb, for ASP.NET presentation tags and programming logic to
implement the functionalities of a Web application. These two files are then linked together to run the
Web application. By default, all the different versions of ASP.NET – ASP.NET 1.0, ASP.NET 2.0, ASP.NET
3.0, and ASP.NET 3.5 – support this model. The code-behind model in ASP.NET 4.5 is similar to the
code-behind model supported by ASP.NET 4.0.

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

What you will learn in this chapter?


 Introduction to the C ontrol C la ss
 Introduction to the S yste m.W e b.U I.W e bC ontrol C la ss
 T he T e xtB ox C ontrol
 T he B utton C ontrol
 T he La be l C ontrol
 T he Lite ra l C ontrol
 T he Ima ge C ontrol
 T he Ima ge B utton C ontrol
 T he Ima ge Ma p C ontrol
 T he D ropD ownList C ontrol
 T he C he ckB ox C ontrol
 T he C he ckB oxList C ontrol
 T he R a dioB utton C ontrol
 T he R a dioB uttonList C ontrol
 T he T a ble C ontrol
 T he P a ne l C ontrol
 T he A dR ota tor C ontrol
 T he C a le nda r C ontrol
 T he H ype rLink C ontrol
 T he F ile U ploa d C ontrol
 T he H idde nF ie ld C ontrol
 T he W iz a rd C ontrol
ASP.NET 4.5 in Simple Steps

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.

Introduction to the Control Class


The System.Web.UI.Control class is the base class for all Web server controls. This class is derived
directly from the Object class, which resides in the System namespace. The hierarchy of the Control
class is as follows:
System.Object
System.Web.UI.Control
Table 3.1 lists the noteworthy public properties of the Control class:
Table 3.1: Noteworthy Public Properties of the Control Class
Property Description
BindingContainer Obtains or sets a server control that contains the control’s data binding
ClientID Obtains or sets a server control’s identifier generated by ASP.NET
Controls Obtains or sets a ControlCollection object that represents the child controls
for a specified server control in the User Interface (UI)hierarchy
EnableTheming Obtains or sets a value indicating whether themes apply to a server control
EnableViewState Obtains or sets a value indicating whether a server control persists its view-
state, and the view-state of any child controls it contains , to the requesting
client

68
Standard Controls

Table 3.1: Noteworthy Public Properties of the Control Class


Property Description
ID Obtains or sets the programmatic identifier assigned to a server control
NamingContainer Obtains or sets a reference to a server control’s naming container, which
creates a unique namespace to differentiate between server controls with the
same System.Web.UI.Control.ID property value
Page Obtains or sets a reference to the Page instance containing a server control
Parent Obtains or sets a reference to a server control’s parent control in the page
control hierarchy
Site Obtains or sets information about the container that hosts the current server
control when the control is rendered on a design surface
SkinID Obtains or sets the skin to apply to a server control
TemplateControl Obtains or sets a reference to a template that contains the server control
TemplateSourceDirectory Obtains or sets the virtual directory of the page or UserControl that contains
the current server control
UniqueID Obtains or sets the unique, hierarchically qualified identifier for a server
control
Visible Obtains or sets a value that indicates whether or not a server control is
rendered as a UI on a Web page

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

Let’s now discuss the System.Web.UI.WebControl class.

Introduction to the System.Web.UI.WebControl Class


All Web server controls exist within the System.Web.UI.WebControl’s namespace and can be used on
any Web form. The hierarchy of the WebControl class is as follows:
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
Table 3.4 lists the noteworthy public properties of the WebControl class:
Table 3.4: Noteworthy Public Properties of the WebControl Class
Property Description
AccessKey Obtains the access key that allows you to quickly navigate to a server control.
Attributes Obtains a collection of arbitrary attributes (for rendering only) that do not
correspond to properties on a server control.
BackColor Obtains the background color of a server control.
BorderColor Obtains the border color of a server control.
BorderStyle Obtains the border style of a server control.
BorderWidth Obtains the border width of a server control.
ControlStyle Obtains the style of a server control. This property is used primarily by Web
developers.
ControlStyleCreated Gets a value indicating whether or not a Style object is created for the
ControlStyle property of a server control. This property is primarily used by Web
developers.
CssClass Obtains the Cascading Style Sheet (CSS) class rendered by a server control on a
client.

70
Standard Controls

Table 3.4: Noteworthy Public Properties of the WebControl Class


Property Description
Enabled Obtains a value indicating whether or not a server control is enabled.
EnableTheming Obtains a value indicating whether or not themes apply to a server control.
Font Obtains the font properties associated with a server control.
ForeColor Obtains the foreground color (typically the color of the text) of a server control.
HasAttributes Sets a value indicating whether or not a server control has its attributes set.
Height Obtains the height of a server control.
SkinID Obtains the skin to apply to a server control.
Style Obtains a collection of text attributes that is rendered as a style attribute on the
outer tag of a server control.
TabIndex Obtains the tab index of a server control.
ToolTip Obtains the text displayed when the mouse-pointer hovers over a server control.
Width Obtains the width of a Web server control.

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.

The TextBox Control


The TextBoox Web Server control is an input control similar to the Windows TextBo ox control that allows
you to enter text in the control. This control exists within the System.Web.UI.WebControls namespace.
When you add a TextBo ox control in a Web form, the following Hypertext Markup Language (HTML) code
snippet is added to the Web form:
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
You can set the style of the TextBo ox control by using the TextMod de property. By default, the TextMod de
property is set to SingleLin
ne to create a singleline text but it can also be set to MultiLin
ne for a multiline
text box to create multiline text.

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

Table 3.7 lists a noteworthy public event of the TextBox class:


Table 3.7: Noteworthy Public Event of the TextBox Class
Event Description
TextChanged Occurs when a user changes the text of a TextBox control

Let’s discuss the Butto


on control next.

The Button Control


The Buttoon control is used to create a button that sends a request to a Web server. The Butto
on control
exists within the System.Web.UI.WebControls namespace. Web server Button controls post data to the
server when they are clicked.

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.

Using the TextBox and Button Controls


In this section, we first create a Web application and then use the application to show you how to view
and use the TextBox and Button controls.
Perform the following steps to learn the procedure of using the TextBoxx and Butto
on controls in a Web
application:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012.
The Start page of Microsoft Visual Studio 2012 appears.
2. Select FILENewProject option from the menu bar.
The New Project dialog box appears.
3. Select InstalledTemplatesVisual C#Web option from the left pane of the New Project
dialog box.
4. Select ASP.NET Empty Web Application template in the middle pane.

73
ASP.NET 4.5 in Simple Steps

5. Enter Textbox and button contro


ol in the Nam
me text box as the name of the Web application.
6. Enter an appropriate location for the Web application in the Locatio
on combo box.
7. Click the OK button to save the settings.
The Textbox and button contro
ol application is created.
8. Open the Solution Explore er window and then right-click the application name, that is, the
Textbox and button contro
ol application.
A context menu appears.
9. Select AddNew Ite
em option from the context menu.
The Add New Item - Textbo
ox and button contro
ol dialog box appears.
10. Select Web Forrm from the middle pane.
11. Click the Add button
The WebForm1.asp
px form is added to the Textbo
ox and button contro
ol Web application.
12. Open the Design mode of the Web form and drag and drop a TextBo
ox control (T
Textboxx1) on to the
Web form from the Toolbo
ox.
13. Right-click the Textboxx1 control and select the Propertie
es option from the context menu, as
shown in Fig.ASP-3.1:

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.

Let’s now learn about the Labe


el control.

The Label Control


The Labe el control is used to display text that a user cannot edit. This control exists within the
System.Web.UI.WebControlls namespace. The noteworthy non-inherited property of this class is the Texxt
property.
Table 3.10 lists the noteworthy public properties of the Label class:
Table 3.10: Noteworthy Properties of the Label Class
Property Description
AssociatedControlID Obtains or sets the identifier for a server control with which a Label control is
associated
Text Obtains or sets the text content of a Label control

Let’s now learn to use the Label control in a Web application.

76
Standard Controls

Using the Label Controls


In this section, we create a Web application to use of the Labe
el control.
Perform the following steps to learn the procedure of using a Labe el control:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#
Web option from the left pane of the New Project
dialog box.
4. Select ASP.NET Empty Web Application in the middle pane.
5. Enter Label control 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 Label control Web application is created.
7. Add a Web form to the Label control application.
8. Drag and drop two Button controls (B
Button1 and Button2) and a Label control (LLabel1) on to the
Web form from the Toolbox.
9 Set the Textt property of the Button1 control to Click to change label properties and that of
Button2 control to Show / Hide Label.
The Web form appears, as shown in Fig.ASP-3.5:

 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

You can also hide the Labe


el control by clicking the Show/Hide Labe
el button control.
Now, let’s discuss the Litera
al control.

The Literal Control


In ASP.NET 4.5, you can add HTML language in a Web page while using a standard Visual C# IDE
code designer without switching to the .aspx page. You can use a Literall Web server control to edit the
HTML language directly. The Litera al control exists within the System.Web.UI.WebControls namespace.
You can also set text by using the Text property of the Litera
al control.
This control does not have any visual appearance in a Web page.
Table 3.11 lists the noteworthy properties of the Literal class:
Table 3.11: Noteworthy Properties of the Literal Class
Property Descriptio
on
Mode Obtains or sets an enumeration value that specifies how the content in a Literal control is rendered

Text Obtains the caption displayed in a Literal control

Let’s now learn to use the Literal control in a Web application.

78
Standard Controls

Using the Literal Control


Let’s create a Web application to use of the Literal control.
Perform the following steps to learn the procedure of using a Litera
al control:
1. Open Visual Studio 201 12.
2. Select FILENewProjecct from the menu bar. The New Projecct 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 Literal control 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 Literal control application is created.
7. Add a Web form to the Literal control application.
8. Add a Button control to the Web form and set its Text property to Click me in the Properties
window.
9 Add a Literal control to the Web form.
The Web form appears, as shown in Fig.ASP-3.7:

 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

1. Press the F5 key to view the output in the browser (Fig.ASP-3.8).


11
12.. Click the Click me button to view the text on which we have applied HTML tags on a Litera
al
control, as shown in Fig.ASP-3.8:

 Fig.ASP-3.8

Let’s now discuss the Imag


ge control.

The Image Control


The Imagge control, which exists within the System.Web.UI.WebControls namespace, creates an area
used to display an image. You set the URL of the image with the ImageUrl property. The alignment of
the image in relation to the other elements on a Web page is specified by setting the ImageAlign
property.
Table 3.12 lists the noteworthy public properties of the Image class:
Table 3.12: Noteworthy Public Properties of the Image Class
Property Description
AlternateText Obtains or sets an alternate text displayed in an Image control when
the image is not available. Browsers that support the ToolTip feature
display this text as a tooltip.
DescriptionUrl Obtains or sets the location with a detailed description for an image.
Enabled Obtains or sets a value indicating whether or not an Image control is
enabled.
Font Obtains or sets the font properties for the text associated with an Image
control.
GenerateEmptyAlternateText Obtains or sets a value indicating whether an image control generates
an alternate text attribute for an empty string value.
ImageAlign Obtains or sets the alignment of an Image control in relation to the
other elements on a Web page.
ImageUrl Obtains or sets the location of an image to display in an Image control.

Let’s learn to use the Image control in a Web application.

Using the Image Control


You can create a Web application to use the Image control.
Perform the following steps to learn the procedure of using an Imag
ge control:
1. Open Visual Studio 201
12.

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

The Add Existing Item - Imagecontrol dialog box appears.


14. Navigate to the location where the image you want to add is saved. In our case, we navigate to
the Sample Pictures folder.
15. Select the image you want to add. In our case, we select the Tulipss image.
16. Click the Add button, to add the image, as shown in Fig.ASP-3.11:

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

The Select Imag


ge dialog box opens (Fig.ASP-3.13).
18. Select the image es folder in the Project folderrs pane and select Tulips.jp
pg in the Contents of
folderr pane (Fig.ASP-3.13).
19. Click the OK button to save the settings, as shown in Fig.ASP-3.13:

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

Now, let’s learn about the ImageButto


on control.

The ImageButton Control


The ImageButto on control creates a button to display an image instead of text in a Web page. This
control exists within the System.Web.UI.WebControls namespace.
You can use the ImageButto on control to display the images that can also handle click events. This is
particularly useful if you want to create image maps, which are those clickable images that initiate
various actions depending on where you click an image map of an image.

83
ASP.NET 4.5 in Simple Steps

Table 3.13 lists noteworthy public properties of the ImageButton class:


Table 3.13: Noteworthy Public Properties of the ImageButton Class
Property Description
CausesValidation Obtains or sets a value indicating whether or not validation is performed
when an ImageButton control is clicked
CommandArgument Obtains or sets an optional argument of an ImageButton control, which
provides additional information about the CommandName property
CommandName Obtains or sets the command name associated with an ImageButton
control
Enabled Gets or sets a value indicating whether the control is enabled
GenerateEmptyAlternateText Obtains or sets a value indicating whether or not an ImageButton control
generates an alternate text attribute for an empty string value
OnClientClick Obtains or sets the client-side script that executes when an ImageButton
control’s Click event is raised
PostBackUrl Obtains or sets the URL of the page to post to from the current page when
an ImageButton control is clicked
ValidationGroup Obtains or sets the group of controls for which the ImageButton control
performs validation when the control posts back to the server

Table 3.14 lists Noteworthy Public Events of the ImageButton:


Table 3.14: Noteworthy Public Events of the ImageButton Class
Event Description
Click Occurs when an ImageButton is clicked. This event posts back a Web page to the
server.
Command Occurs when an ImageButton is clicked. The Command event occurs
through the control hierarchy in the form of a bubble event (events raised
by child controls handled by the parent control).

Let’s now learn how to use the Imagebutton control in a Web application.

Using the ImageButton Controls


In this section, we create a Web application and use the Web application to demonstrate the use of the
Imagebutton control.
Perform the following steps to learn the procedure of using an ImageButto
on control:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct from the menu bar. The New Projecct dialog box opens.
Templates
3. Select Installed Visual C#
Web option from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.

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

After learning how to use the ImageButto


on control in a Web application, let’s discuss the ImageMa
ap
control.

The ImageMap Control


An image map is an image on a Web page that provides various links, called hotspots, to navigate to
other Web pages, depending on the place where the user clicks on the image. Web designers frequently
use image maps (hotspots) in their websites.
An ImageMa ap control exists within the System.Web.UI.WebControlls namespace. Image maps are
often real maps. For example, you can display the map of USA and define different hotspot regions
for each of its states and then navigate to the corresponding page containing the information for the
selected state.
We can also perform the postback operation to the server on the click event of the selected regions and
execute any code. The ImageMa ap control uses the Imageurrl property to specify the path of the image
needed to be displayed and the HotSpotts property defines a hotspot region on the image.
Table 3.15 lists Noteworthy Public Properties of the ImageMap class:
Table 3.15: Noteworthy Public Properties of the ImageMap Class
Property Description
HotSpotMode Obtains the default behavior for the HotSpot objects of an ImageMap control
when the HotSpot objects are clicked
HotSpots Obtains a collection of HotSpot objects representing the defined hotspot regions
in an ImageMap control
Target Obtains the target window or frame to display a Web page content linked to an
ImageMap control when the control is clicked

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

Let’s now learn to use the ImageMa


ap control in a Web application.

Using the ImageMap Control


You can create a Web application to view the use of the ImageMa ap control.
Let’s perform the following steps to learn the procedure of using an ImageMa ap control:
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 from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.
5. Enter Imagemapcontrol 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 Imagemapcontrol application is created.
7. Add two Web forms to the Imagemapcontrol application.
8. Add two Label controls (LLabel1 and Label2) to the Web form and set the Text property of the
Label1 control to Using Image Map Control.
9. Drag and drop an ImageMap control (IImageMap1) from the Toolbox on to the Web form and
change its Height and Width properties to 105px and 461px, respectively.
10. Add a folder named imagess and add an image to the folder.
11. Open the Properties window of the ImageMap1 control and click the ellipse button of the
ImageUrl property.
The Select Image dialog box appears.
12. Select the images folder from the Project folders pane of the Select Image dialog box.
13. Select the image from the Contents of folder pane.
14. Click the OK button to save the settings.
15. Click the ellipse button of the HotSpots property in the Properties window of the ImageMap1
control, as shown in Fig.ASP-3.17:

15

 Fig.ASP-3.17

The HotSpot Collection Editor dialog box appears.


16. Right-click the Addd button and select the RectangleHotSpot option from the context menu. A
RectangleHotSpot member is added in the Members pane of the HotSpot Collection Editor
dialog box.
Similarly, add two more RectangleHotSpots.
17. Set the Bottom, Left, Right, and Topp properties in the Appearance group of the RectangleHotSpot
properties pane, for each hotspot. In our case, we have set the properties of first hotspot as
Bottom to 50, Left to 10, Right to 150, and Top to 5.

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

The text corresponding to HotSpot2


2 hotspot changes in the Label control, as shown in Fig.ASP-3.21:

 Fig.ASP-3.21

Now, let’s discuss the DropDownLisst control.

The DropDownList Control


The DropDownLisst control displays data as a drop-down list from which you can make a single
selection. This control exists within the System.Web.UI.WebControls namespace. You cannot select
multiple items in this control, because when you make a selection from the list, the list closes
automatically.
After you have selected an item in a drop-down list, you can use the control’s SelectedItem,
SelectedIndex, and SelectedValu
ue properties to work with the selection.
Table 3.17 lists noteworthy public properties of the DropDownlist class:
Table 3.17: Noteworthy Public Properties of the DropDownList Class
Property Description
n
BorderColor Obtains or sets the border color of a DropDownList control
BorderStyle Obtains or sets the border style of a DropDownList control
BorderWidth Obtains or sets the border width for a DropDownList control
SelectedIndex Obtains or sets the index of the selected item in a DropDownList
control

Let’s now create a Web application to learn the use of the DropDownLisst control.

Using DropDownList Controls


Let’s create a Web application and use it to demonstrate the use of the DropDownLisst control.
Perform the following steps to learn the procedure of using the DropDownLisst control:
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 from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.

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. Click the Item


ms property ellipse button in the Properties window of the DropDownList1 control, as
shown in Fig.ASP-3.23:

11

 Fig.ASP-3.23

The ListItem Collection Editorr dialog box appears (Fig.ASP-3.24).


12. Click the Add button to add drop-down list members in the Members pane and set their Texxt and
Valuue properties in the properties pane (Fig.ASP-3.24). In our case, we add the five members
and set their Text and Values properties to Red, Green, Blue, White, and Black, respectively.
13. Click the OK button to save the settings, as shown in Fig.ASP-3.24:

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>

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


<br />
<br />
<asp:DropDownList ID="DropDownList1" runat="server" style="height: 22px"
OnTextChanged="DropDownList1_SelectedIndexChanged" AutoPostBack="True">
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
<asp:ListItem>White</asp:ListItem>
<asp:ListItem>Black</asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:Label ID="Label2" runat="server" Text="Selected Color: "></asp:Label>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>
14. Double-click the DropDownListt1 control in the Desig
gn mode and add the following code snippet
to the SelectedIndexChange
ed event of the control:
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{
TextBox1.Text = DropDownList1.SelectedItem.Text;
}

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.

The CheckBox Control


The CheckBox control creates a check box that you can select by clicking. The CheckBox control exists
within the System.Web.UI.WebControls namespace. Check boxes display checkmarks that allow a user
to toggle between a truue or falsse condition. Table 3.18 lists noteworthy Public Properties of the
CheckBox class:
Table 3.18: Noteworthy Public Properties of the CheckBox Class
Property Description
AutoPostBack Obtains a value indicating whether or not a CheckBox control automatically posts
back to the server according to the state of the control, when the control is clicked
CausesValidation Obtains or sets a Boolean value indicating whether or not validation is performed
when a CheckBox control is clicked
Checked Obtains a value indicating whether or not a CheckBox control is checked
InputAttributes Obtains a reference to a collection of attributes for all the rendered input elements of
a CheckBox control
LabelAttributes Obtains a reference to a collection of attributes for all the rendered label elements of
a CheckBox control
Text Obtains the text label associated with a CheckBox control
TextAlign Obtains the alignment of the text label associated with a CheckBox control
ValidationGroup Obtains or sets a group of controls for which a CheckBox control performs validation
on the control’s postback

Table 3.19 lists a noteworthy public event of the CheckBox class:


Table 3.19: Noteworthy Public Event of the CheckBox Class
Event Description
CheckedChanged Occurs when the value of the Checked property of a CheckBox control changes
among requests to the server

93
ASP.NET 4.5 in Simple Steps

Next, let’s discuss the CheckBoxList control.

The CheckBoxList Control


You can use a CheckBoxLisst control to display a number of check boxes simultaneously as a column of
check boxes. The CheckBoxLisst control exists within the System.Web.UI.WebControls namespace. This
control is useful when you want to bind data from a data source to check boxes.
The CheckBoxLisst control creates a multiselection check box group. You can create these controls at
runtime by binding these controls to a data source. The CheckBoxList control has been enhanced in
ASP.NET 4.5, and the RepeatLayout property has been added to the control. The RepeatLayout property
contains the following four options:
 Table
e: Displays a CheckBoxList control in a tabular format
 Flow
w: Displays the CheckBoxList control in flow format (that is, a format other than the tabular format).
 UnorderedListt: Displays the CheckBoxList control in the form of an unordered list
 OrderedListt: Displays the CheckBoxList control in the form of an ordered list
Table 3.20 lists noteworthy properties of the CheckBoxList class:
Table 3.20: Noteworthy Public Properties of the CheckBoxList Class
Property Description
CellPadding Obtains the distance (in pixels) between the border and content of a cell in a table
CellSpacing Obtains the distance (in pixels) between cells
RepeatColumns Obtains the number of columns to display in a CheckBoxList control
RepeatDirection Obtains a value that indicates whether a CheckBoxList control is displayed vertically or
horizontally on a Web page
RepeatLayout Obtains the layout for a check box in a CheckBoxList control
TextAlign Obtains the text alignment for check boxes within a group in a CheckBoxList control

Let’s create a Web application to learn the use of the CheckBo


ox and CheckBoxLisst controls.

Using the CheckBox and CheckBoxList Controls


You can create a Web application to view the use of the CheckBox and CheckboxList controls.
Let’s perform the following steps to learn the procedure of using the Ch
heckBoxx and CheckBoxLisst controls:
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 from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.
5. Enter checkbox and checkboxlist control 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.

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

The ListItem Collection Editorr dialog box appears (Fig.ASP-3.28).


12. Click the Add button to add CheckBoxList members in the Members pane and set their Texxt and
Valuue properties in the properties pane. In our case, we add the four members and set their Texxt
and Valuue properties to Cheese, Sausage, Tomato, and Ha am, respectively.
13. Click the OK button to save the settings, as shown in Fig.ASP-3.28:

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" />&nbsp;&nbsp;
<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

5. Double-click the CheckBoxx1 control in the Desig


15 gn mode and add the following code snippet to
the CheckedChanged d event of the control:
protected void CheckBox1_CheckedChanged(object sender, EventArgs e)
{
if (CheckBox1.Checked==true)
{
TextBox1.Text += "Selected Bread: Whole wheat ";
}
}
16. Double-click the CheckBoxx2 control in the Desig
gn mode and add the following code snippet to
the CheckedChanged d event of the control:
protected void CheckBox2_CheckedChanged(object sender, EventArgs e)
{
if(CheckBox2.Checked==true)
{
TextBox1.Text += "with sesame seeds";
}
}
17. Double-click the CheckBoxListt1 control in the Desig
gn mode and add the following code snippet
to the SelectedIndexChanged
d event of the control:
protected void CheckBoxList1_SelectedIndexChanged(object sender, EventArgs e)
{
int LoopIndex;
TextBox2.Text = "Filling: ";
for(LoopIndex = 0;LoopIndex<=3;LoopIndex++)
{
if(CheckBoxList1.Items[LoopIndex].Selected)
{
TextBox2.Text += CheckBoxList1.Items[LoopIndex].Value + " ";
}
}
}
8. Press the F5 key to view the output in the browser (Fig.ASP-3.31).
18
9. Select any number of items or options from the Select Brea
19 ad and the Select Fillin
ng section
(Fig.ASP-3.31).
The selected items or options appear in the text boxes corresponding to the Select Brea
ad and the Select
Fillin
ng check boxes, as shown in Fig.3.31:

 Fig.ASP-3.31

97
ASP.NET 4.5 in Simple Steps

Now, let’s discuss the RadioButton


n and RadioButtonLisst controls.

The RadioButton Control


The RadioButtoon control exists within the System.Web.UI.WebControls namespace. Unlike check boxes,
radio buttons form exclusive groups, where only one radio button can be selected at a time. In Windows
Forms, radio buttons are grouped automatically by a container. However, the GroupName property of
all the RadioButto
on controls in a Web form must be the same to associate them into a group.
Table 3.21 lists a noteworthy public property of the RadioButton class:
Table 3.21: Noteworthy Public Property of the RadioButton Class
Property Descriptio
on
GroupName Obtains the name of the group to which a radio button belongs. The radio
button acts in a synchronized manner with the other members of the group.

Table 3.22 lists a noteworthy Public Event of the RadioButton class:


Table 3.22: Noteworthy Public Event of the RadioButton Class
Event Descriptio
on
CheckedChanged Occurs when the Checked property of a RadioButton control is changed

The RadioButtonList Control


The RadioButtonLisst control displays data as a list or column of options and provides you with an easy
way to display a radio button group in which only a single radio button can be selected. The
RadioButtonLisst control exists within the System.Web.UI.WebControls namespace. The SelectedItem
property of the RadioButtonLisst control helps to determine the radio button selected in the control. You
can also determine the index of the selected item from the SelectedIndex property of the control.
The following is a brief description of the various layouts in which a RadioButtonLisst control can be
displayed:
 Table
e: Displays a RadioButtonLisst control in the tabular format
 Flow
w: Displays a RadioButtonLisst control in the flow format, which implies that the control is not
displayed in tabular format
 UnorderedListt: Displays a RadioButtonLisst control in the form of an unordered list
 OrderedList:: Displays a RadioButtonLisst control in the form of an ordered list
Table 3.23 lists the noteworthy public properties of the RadioButtonList class:
Table 3.23: Noteworthy Public Properties of the RadioButtonList Class
Property Descriptio
on
CellPadding Obtains or sets the distance (in pixels) between the border and the content of a table cell.
CellSpacing Obtains the distance (in pixels) between adjacent table cells

98
Standard Controls

Table 3.23: Noteworthy Public Properties of the RadioButtonList Class


Property Descriptio
on
RepeatColumns Obtains the number of columns displayed in a radio button list
RepeatDirection Obtains the direction of a radio button, that is, horizontal and vertical
RepeatLayout Obtains the layout of a radio button within a group
TextAlign Obtains the text alignment for a radio button caption within a group in a
RadioButtonList control

Now, let’s learn to use the RadioButto


on and RadioButtonLisst controls in a Web application.

Using the RadioButton and RadioButtonList Controls


In this section, we create a Web application to demonstrate the use of the RadioButton and
RadioButtonList controls.
Perform the following steps to learn the procedure of using the RadioButto on and RadioButtonLisst
controls:
1. Open Visual Studio 20112.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#
Web option from the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Radiobutton 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 Radiobutton application is created.
7. Add a Web form to the Radiobutton application.
8. Add two Label controls (LLabel1 and Label2) and two TextBox controls (T
TextBox1 and TextBox2) to the
Web form.
9. Set the Text property of the Label1 control to Select Vehicle and the Text property of the Label2
control to Select Color.
10. Drag and drop four RadioButton controls (R RadioButton1, RadioButton2, RadioButton3 and
RadioButton4) and one RadioButtonList control (R
RadioButtonList1) from the Toolbox on to the
Web form.
11. Set the Text properties of the RadioButton1, RadioButton2, RadioButton3, and RadioButton4
controls to Car, Truck, Bus, and Motorcycle, respectively, in the Properties window.
12. Set the AutoPostBack property to True, the GroupName property to Type, and the Checked
property to True, for each RadioButton control in the Properties window.
13. Set the Items property of RadioButtonList1 control by clicking the ellipse button.
The ListItem Collection Editor dialog box appears (Fig.ASP-3.32).
14. Click the Add button to add RadioButtonList members in the Members pane and set their Text
and Value e properties in the properties pane (Fig.ASP-3.32). In our case, we add the six
members and set their Text and Values properties to Blue, Red, Black, Silver, Yellow, and Green
respectively.

99
ASP.NET 4.5 in Simple Steps

15. Click the OK button to save the settings, as shown in Fig.ASP-3.32:

14
15

 Fig.ASP-3.32

16. Set the AutoPostBacck property to True e, the RepeatDirectio


on property to Vertica al, and the
RepeatLayou
ut property to OrderedLisst in the Propertie
es window of the RadioButtonListt1 control.
After adding the controls and setting their properties, the Web form appears, as shown in
Fig.ASP-3.33:

 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" />&nbsp;
<asp:RadioButton ID="RadioButton2" runat="server" Text="Truck"
AutoPostBack="True" oncheckedchanged="RadioButton2_CheckedChanged" />&nbsp;

100
Standard Controls

<asp:RadioButton ID="RadioButton3" runat="server" Text="Bus"


AutoPostBack="True" oncheckedchanged="RadioButton3_CheckedChanged" />&nbsp;
<asp:RadioButton ID="RadioButton4" runat="server" Text="Motorcycle"
AutoPostBack="True" oncheckedchanged="RadioButton4_CheckedChanged" /><br /><br />
<asp:TextBox ID="TextBox1" runat="server" Width="273px"></asp:TextBox><br /><br />
<asp:Label ID="Label2" runat="server" Text="Select Color"></asp:Label><br /><br />
<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"
onselectedindexchanged="RadioButtonList1_SelectedIndexChanged" RepeatLayout="OrderedList">
<asp:ListItem Selected="True">Blue</asp:ListItem>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Black</asp:ListItem>
<asp:ListItem>Silver</asp:ListItem>
<asp:ListItem>Yellow</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
</asp:RadioButtonList> <br />
<asp:TextBox ID="TextBox2" runat="server" Width="273px"></asp:TextBox><br /><br />
</div>
</form>
</body>
</html>
17. Double-click the Web Form (WebForm1.aspx) in the Design mode and add the following code
snippet to the Load event of the form:
protected void Page_Load(object sender, EventArgs e)
{
if (RadioButton1.Checked==true)
{
TextBox1.Text = "You have selected: Car";
TextBox2.Text = "Your vehicle is:Blue " ;
RadioButtonList1.SelectedItem.Value.ToString();
}
}
18. Double-click the RadioButton
n1 control in the Design mode and add the following code snippet to
the CheckedChanged event of the control:
protected void RadioButton1_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "You have selected: Car";
RadioButton2.Checked = false;
RadioButton3.Checked = false;
RadioButton4.Checked = false;
}
19. Double-click the RadioButton
n2 control in the Design mode and add the following code snippet to
the CheckedChanged event of the control:
protected void RadioButton2_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "You have selected: Truck";
RadioButton1.Checked = false;
RadioButton3.Checked = false;
RadioButton4.Checked = false;
}
20. Double-click the RadioButton
n3 control in the Design mode and add the following code snippet to
the CheckedChanged event of the control:
protected void RadioButton3_CheckedChanged(object sender, EventArgs e)
{
TextBox1.Text = "You have selected: Bus";
RadioButton2.Checked = false;
RadioButton1.Checked = false;
RadioButton4.Checked = false;
}

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

Now, let’s learn about the Table control.

The Table Control


The Tablle control is used to create an HTML table. This control is useful when you want to present data
in a tabular format. The Tablle control exists within the System.Web.UI.WebControlls namespace. Web
designers often use tables to correctly place the elements on Web pages. You can create a table at
design time or at run time, depending on your requirement.

102
Standard Controls

Table 3.24 lists Noteworthy Public Properties of the Table class:


Table 3.24: Noteworthy Public Properties of the Table Class
Property Description
BackImageUrl Obtains the URL of the background image that is displayed in a Table control
Caption Obtains the text to render in an HTML caption in a Table control
CaptionAlign Obtains the horizontal or vertical position of an HTML caption element in a
Table control
CellPadding Obtains the amount of space between the content of a cell and the cell’s
border in a Table control
CellSpacing Obtains the amount of space between cells in a Table control
GridLines Obtains the grid line style to display in a Table control
HorizontalAlign Obtains the horizontal alignment of a Table control on a Web page
Rows Obtains the collection of rows in a Table control

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.

The TableRow Class


The TableRow class is used to create the table rows needed in Table objects. The TableRow class exists
within the System.Web.UI.WebControlls namespace. You can use the TableRow class to control the way
in which the content of a table row is displayed. You can manage the cells in a row in code by using the
Cells collection, which is a collection of TableCell objects representing the cells in a row.
Table 3.25 lists noteworthy Public Properties of the TableRow class:
Table 3.25: Noteworthy Public Properties of the TableRow Class
Property Description
Cells Obtains a collection of TableCell objects that represent the cells of a
row in a Table control
HorizontalAlign Obtains the horizontal alignment of the content in a row
TableSection Obtains the location for a TableRow object in a Table control
VerticalAlign Obtains the vertical alignment of the content in a row

The TableCell Class


The TableCell class represents a cell in a Tablle control. You can use the Text property to get or set the
content of the cell. The TableCelll class exists within the System.Web.UI.WebControls namespace. You
can also specify how many rows or columns in the Tablle control are occupied by a single cell, by using
the RowSpaan and ColumnSpa an properties.

103
ASP.NET 4.5 in Simple Steps

Table 3.26 lists noteworthy Public Properties of the TableCell class:


Table 3.26: Noteworthy Public Properties of the TableCell Class
Property Description
AssociatedHeaderCellID Obtains a list of table header cells associated with a TableCell control
ColumnSpan Obtains the number of columns that a cell spans in a Table control
HorizontalAlign Obtains the horizontal alignment of the content in a cell
RowSpan Obtains the number of rows that a cell spans in the Table control
Text Obtains the text content of a cell
VerticalAlign Obtains the vertical alignment of the contents in a cell
Wrap Obtains a value that indicates whether the content of a cell wraps or
not

Let’s now learn to use the Table control in a Web application.

Using the Table Control


You can create a Web application to view the use of Table control.
Let’s perform the following steps to learn the procedure of using the Tablle control:
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 from the left pane of the New Project
dialog box.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Tablecontrol 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 Tablecontrol application is created.
7. Add a Web form to the Tablecontrol application.
8. Drag and drop a Table control (Table1) from the Toolbox to the Web form.
9. Open the Properties window of the Table1 control and set the BorderColor and BorderStyle
properties to Black and Solid, respectively.
Now, set the Rows property by clicking the ellipse button.
The TableRow Collection Editor dialog box appears (Fig.ASP-3.35).
10. Click the Add button four times to add four TableRow objects (Fig.ASP-3.35).
11. Set the Cells property by clicking the ellipse button for each TableRow object, as shown in
Fig.ASP-3.35:

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.

The Panel Control


The Pane el control is one of the most frequently used controls. By default, this control creates a borderless
division on a Web form, which serves as a container for the other controls. The Pane el control exists
within the System.Web.UI.WebControls namespace. These controls are useful when you want to show or
hide a group of controls together or when you want to add controls to a Web page through code.
Table 3.27 lists noteworthy Public Properties of the Panel class:
Table 3.27: Noteworthy Public Properties of the Panel Class
Property Description
n
BackImageUrl Obtains or sets the URL of the background image for a Panel control
DefaultButton Obtains or sets the identifier for the default button that exists in a Panel control
Direction Obtains the direction in which to display controls that include text in a Panel control
GroupingText Obtains or sets the caption for the group of controls that exist in a Panel control
HorizontalAlign Obtains the horizontal alignment of the content within a Panel control
ScrollBars Obtains or sets the display and position of scroll bars in a Panel control
Wrap Obtains a value indicating whether the content wraps within a Panel control

Let’s create a Web application to learn the use of the Pane


el control:

Using the Panel Controls


Let’s now create a Web application to demonstrate the use of the Panel control.
Let’s perform the following steps to learn the procedure of using a Pane
el control:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears.
3. Templates
Select Installed Visual C# Web option from the left pane.
4. Select ASP.NET Empty Web Application option in the middle pane.

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" />
&nbsp;
<asp:RadioButton ID="RadioButton2" runat="server" Text="Green" AutoPostBack="True"
GroupName="Color" />
&nbsp;
<asp:RadioButton ID="RadioButton3" runat="server" Text="Blue" AutoPostBack="True"
GroupName="Color" />&nbsp;
&nbsp;<br />
<br />
<br />
<br />
&nbsp; &nbsp;&nbsp;<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.

The AdRotator Control


ASP.NET supports banner advertisements. These advertisements, which all Internet users are familiar
with, are image files in .gif, .jpeg or other formats that a user clicks to make the browser navigate to the
advertiser’s website. The AdRotato or control is used to display advertisement banners in a Web page. This
control displays a sequence of images that can be predefined or random. The AdRotato or control exists
within the System.Web.UI.WebControls namespace.

109
ASP.NET 4.5 in Simple Steps

Table 3.28 lists noteworthy Public Properties of the AdRotator class:


Table 3.28: Noteworthy Public Properties of the AdRotator Class
Property Description
AdvertisementFile Obtains or sets the path to an Extensible Markup Language XML file that
contains advertisement information to use in an AdRotator control
AlternateTextField Obtains or sets a custom data field to use in place of the AlternateText attribute for
an advertisement
ImageUrlField Obtains or sets a custom data field to use in place of the ImageUrl attribute
for an advertisement
KeywordFilter Obtains or sets a category keyword to filter for specific types of
advertisements in an XML advertisement file
NavigateUrlField Obtains or sets a custom data field to use in place of the NavigateUrl attribute
for an advertisement
Target Obtains or sets the name of a browser window or frame that displays the
content of the Web page linked to the window or frame when the AdRotator
control is clicked

Table 3.29 lists a noteworthy public event of the Adrotator class:


Table 3.29: Noteworthy Public Event of the AdRotator Class
Event Description
AdCreated Occurs once per round trip to the server after the creation of an AdRotator control,
but before a Web page is rendered

Let’s now use the Adrotato


or control in a Web application.

Using the AdRotator Control


You can create an application to use of Adrotator control.
Let’s perform the following steps to learn the procedure of using the AdRotato
or control:
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 from the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Adrotator 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 Adrotator application is created.
7. Add a Web form to the Adrotator application.
8. Drag and drop an AdRotator control (AdRotator1) to the Web form.

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

10. Right–click the name of the Adrotato


or application in the Solution Explore
er window.
A context menu appears.
11. Select AddNeew Ite
em from the context menu.
The Add New Item dialog box appears (Fig.ASP-3.41).
Visual C#
12. Select Installed Data from the left pane of the Add New Item dialog box
(Fig.ASP-3. 41).
13. Select the XML File option from the middle pane (Fig.ASP-3.41).
14. Click the Add button to add an XMLL file in the Adrotator Web application, as shown in
Fig.ASP-3.41:

14

13
12
 Fig.ASP-3.41

The XML file appears with the name XMLFile1.xml.


15. Add the following code snippet in the XMLFile1.xml file:
<Advertisements>
<Ad>
<ImageUrl>~/images/Chrysanthemum.jpg</ImageUrl>
<NavigateUrl>http://www.google.com</NavigateUrl>
<AlternateText>Visit Google.com</AlternateText>
<Impressions>80</Impressions>
<Keyword>search</Keyword> </Ad>

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.

The Calendar Control


The Calenda ar control displays a calendar graphically on which users can select dates. The Calenda ar
control exists within the System.Web.UI.WebControls namespace. You can use the Calenda ar control to
display a single month of a calendar on a Web page. This control allows you to select dates and move
to the next or previous month. By setting the SelectionMode property of this control, you can select a
single day, week, or month.
By default, the Calenda ar control displays the days of the month, the day headings for the days of the
week, a title with the name of the month, and links to navigate to the next or previous month.

113
ASP.NET 4.5 in Simple Steps

Table 3.30 lists Noteworthy Properties of the Calendar class:


Table 3.30: Noteworthy Properties of the Calendar Class
Propertty Descriptio
on
DayHeaderStyle Obtains the style for the days of the week in a Calendar control
DayStyle Obtains the style for the dates in a month in a Calendar control
NextPrevStyle Obtains the style for the navigation elements in a Calendar control
OtherMonthDayStyle Obtains the style for dates not in the displayed month in a Calendar
control
SelectedDayStyle Obtains the style for the selected dates in a Calendar control
SelectorStyle Obtains the style of the selected column for the week and month in a
Calendar control
TitleStyle Obtains the style for the title sections in a Calendar control
TodayDayStyle Obtains the style for the current date in a Calendar control
WeekendDayStyle Obtains the style for weekend dates in a Calendar control

Table 3.31 lists the show/hide properties of the Calendar class:


Table 3.31: Show/Hide Properties of the Calendar Class
Propertie
es Descriptio
on
ShowDayHeader Obtains or sets the days of the week in a Calendar control
ShowGridLines Obtains or sets grid lines (displayed between the days of the month) in a
Calendar control
ShowNextPrevMonth Obtains or sets the navigation controls to the next or previous month in a
Calendar control
ShowTitle Obtains or sets the title of the Calendar control

Table 3.32 lists noteworthy Public Properties of the Calendar class:


Table 3.32: Noteworthy Public Properties of the Calendar Class
Property Descriptio
on
CellPadding Obtains or sets the space used for cell padding in a Calendar control
CellSpacing Obtains or sets the space between cells in a Calendar control
DayHeaderStyle Obtains the style for the day of the week in a Calendar control
DayNameFormat Obtains or sets the format for the name of the day of the week in a
Calendar control

114
Standard Controls

Table 3.32: Noteworthy Public Properties of the Calendar Class


Property Descriptio
on
DayStyle Obtains the style for the days in a Calendar control
FirstDayOfWeek Obtains or sets the day of the week displayed in the first column in a
Calendar control
NextMonthText Obtains or sets the text labeling of the next month’s navigation controls in
a Calendar control
NextPrevFormat Obtains or sets the format of the navigation controls of both the next and
previous months in a Calendar control
NextPrevStyle Obtains or sets the style for the next and previous months in a Calendar
control
OtherMonthDayStyle Obtains or sets the style for the days not in the displayed month in a
Calendar control
PrevMonthText Obtains or sets the text for the navigation controls of the previous month in
a Calendar control
SelectedDate Obtains or sets the selected date in a Calendar control
SelectedDates Obtains or sets a collection of System.DateTime objects for the selected
dates in a Calendar control
SelectedDayStyle Obtains the style for the selected dates in a Calendar control
SelectionMode Obtains or sets the date selection mode, determining if you can select a
day, a week, or a month, in a Calendar control
SelectMonthText Obtains or sets the text for an element of the selected month in a Calendar
control
SelectorStyle Obtains the style of the selected column for the week and month in a
Calendar control
SelectWeekText Obtains or sets the text for the selected week in a Calendar control
ShowDayHeader Obtains or checks if the day of the week header is shown in a Calendar
control
ShowGridLines Obtains or checks if grid lines should appear between the days in a
Calendar control
ShowNextPrevMonth Obtains or checks if a Calendar control can display next and previous
month navigation controls
ShowTitle Obtains or checks if the title should be displayed in a Calendar control
TitleFormat Obtains or sets the format for the title section in a Calendar control
TitleStyle Obtains or sets the style of the title in a Calendar control
TodayDayStyle Obtains or sets the style for the current date in a Calendar control

115
ASP.NET 4.5 in Simple Steps

Table 3.32: Noteworthy Public Properties of the Calendar Class


Property Descriptio
on
TodaysDate Obtains or sets the current date in a Calendar control
VisibleDate Obtains or sets a date, and ensures that it is visible in a Calendar control
WeekendDayStyle Obtains or sets the style for weekend dates in a Calendar control

Table 3.33 lists noteworthy Public Events of the Calendar class:


Table 3.33: Noteworthy Public Events of the Calendar Class
Even
nt Descriptio
on
DayRender Occurs when each day is displayed in a Calendar control
SelectionChanged Occurs when a user selects a date in a Calendar control
VisibleMonthChanged Occurs when a user moves to a different month from the one currently displayed
in a Calendar control

Let’s now learn to use the Calendar control in a Web application.

Using the Calendar Controls


You can create a Web application to view the use of the Calendar control.
Let’s perform the following steps to learn the procedure of using the Calenda
ar control:
1. Open Visual Studio 201
12.
New
2. Select FILE Project from the menu bar. The New Project dialog box appears.
3. Templates
Select Installed Visual C# Web option from the left pane.
4. Select ASP.NET Empty Web Application in the middle pane.
5. Enter Calendar in the Name text box as the name of the Web application.
6. Enter an appropriate location for the application in the Location combo box.
7. Click the OK button. The Calendar Web application is created.
8. Add a Web form to the Calendar application.
9. Add one TextBox (TextBox1) and two Label controls (Label1 and Label2) to the Web form.
10. Set the property of the Label1
1 control to Calendar example and that of the Label2 to Selected
Date:.
11. Drag and drop a Calendar control (Calendar1) on to the Web form.
12. Open the Properties window of the Calendar1 control and set its Caption property to Calendar
Control.
13. Click the smart tag (>) and select the Auto Format option, as shown in Fig.ASP-3.44:

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

<SelectedDayStyle BackColor="#333399" ForeColor="White" />


<OtherMonthDayStyle ForeColor="#999999" />
<TodayDayStyle BackColor="#CCCCCC" />
<NextPrevStyle Font-Size="8pt" ForeColor="#333333" Font-Bold="True"
VerticalAlign="Bottom" />
<DayHeaderStyle Font-Bold="True" Font-Size="8pt" />
<TitleStyle BackColor="White" Font-Bold="True" Font-Size="12pt" ForeColor="#333399"
BorderColor="Black" BorderWidth="4px" /></asp:Calendar> &nbsp;
<asp:Label ID="Label2" runat="server" Text="Selected Date:"></asp:Label><br />
<asp:TextBox ID="TextBox1" runat="server" Width="316px"></asp:TextBox><br /><br />
</div>
</form>
</body>
</html>
16. Double-click the WebForm m1.aspx form in the Design mode and add the following code snippet in
the Load event of the forrm:
protected void Page_Load(object sender, EventArgs e)
{ Calendar1.SelectedDate = DateTime.Now;
TextBox1.Text = "Today's date and time is : " + Calendar1.SelectedDate;}
17. Press the F5 key to view the output in the browser, as shown in Fig.ASP-3.46:

 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.

The HyperLink Control


The HyperLin nk control is used to create a link to another Web page either within a Web application or
with any other application on the Internet. You can specify the location of the linked page by specifying
its URL on the current page. This control exists within the System.Web.UI.WebControlls namespace.
You can use text as well as an image in the HyperLin nk control. Text is specified by using the Text
property and images are specified by using the ImageUrrl property of the control. When you click a
HyperLin
nk control, the hyperlinked content appears in a new browser window by default.

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

Table 3.35 lists noteworthy properties of the Hyperlink class:


Table 3.35: Noteworthy Properties of the HyperLink Class
Property Description
n
ImageUrl Obtains the path of an image to display for a HyperLink control
NavigateUrl Obtains the URL of the location when a HyperLink control is clicked
Target Obtains the target window in which to display the content of a Web page when a
HyperLink control is clicked
Text Obtains the text caption for a HyperLink control

Let’s now create an Web application to learn the use of the HyperLin
nk control.

Using the HyperLink Controls


You can create a Web application to use of the HyperLink control.
Let’s perform the following steps to learn the procedure of using the HyperLin
nk control:
1. Open Visual Studio 201
12.
New
2. Select FILE Project option 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 template in the middle pane.
5. Enter HyperLink in the Name text box as the name of the application and specify an appropriate
location for the application in the Location combo box.
6. Click the OK button. The HyperLink application is created.
7. Add a Web form to the HyperLink application.
8. Add two Label controls (Label1 and Label2) to the Web form from the Toolbox and set the Text
property of the Label1 control to Hyper Links Example and that of Label2 to URL HyperLink.
9. Drag and drop a HyperLink (HyperLink1) control on to the Web form (Fig.ASP-3.47).
10.. Open the Properties window of the HyperLink1 control and set the NavigateUrl property to
http://www.google.co.in, the Target property to _blank, the Text property to Visit Google.co.in,
and the ToolTip property to Visit Google.co.in, as shown in Fig.ASP-3.47:

119
ASP.NET 4.5 in Simple Steps

10

 Fig.ASP-3.47

The WebForm1 form appears, as shown in Fig.ASP-3.48:

 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

Now, let’s learn about the FileUploa


ad control.

The FileUpload Control


The FileUploa ad control is designed to upload files from the client-side to the server-side. This control
exists within the System.Web.UI.WebControlls namespace.
Table 3.36 lists noteworthy properties of the FileUpload class:
Table 3.36: Noteworthy Properties of the FileUpload Class
Propertyy Description
n
FileBytes Returns an array of bytes of a specified file by using a FileUploa
ad control
FileContent Obtains a Stream object that points to a file to upload by using the F ileUploa
ad control
FileName Obtains the name of a file on a client computer to upload by using the FileUploa
ad
control
HasFile Obtains a value indicating whether or not a FileUploa
ad control contains a file
PostedFile Obtains the underlying HttpPostedFille object for a file uploaded by using the
FileUploa
ad control

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

Using the FileUpload Control


In this section, we create a Web application to learn how to use the FileUploa
ad control.
Perform the following steps to learn the procedure of using the FileUploaad control:
1. Open Visual Studio 201 12.
2. New
Select FILE Project option from the menu bar. The New Project dialog box appears.
3. Templates
Select Installed Visual C# Web option from the left pane.
4. Select ASP.NET Empty Web Application template in the middle pane.
5. Enter Fileupload in the Name text box as the name of the Web application and enter an
appropriate location for the application in the Location combo box.
6. Click the OK button. The Fileupload Web application is created.
7. Add a Web form to the Fileupload application.
8. Add two Labell controls (LLabel1 and Label2) and one Button control (B Button1) to the Web form
from the Toolbox.
9. Open the Properties window and set the Text property of the Label1 control to Please Select a file
to upload and the Text property of the Button1 control to Upload File.
10. Drag and drop a FileUpload control (F FileUpload1) on to the Web form.
The Web form appears, as shown in Fig.ASP-3.50:

 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>&nbsp;<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.

Now, let’s discuss the HiddenFielld control.

123
ASP.NET 4.5 in Simple Steps

The HiddenField Control


The HiddenField control is used to store a value that needs to be preserved when sending requests to
the server and receiving their responses. Generally, this control hides values so that they do not appear
on a Web page. However, you should not keep sensitive data in this control as the data can be easily
viewed by right-clicking the Web page in its HTML code. The HiddenField control exists within the
System.Web.UI.WebControls namespace.
Table 3.37 lists a noteworthy property of the of the HiddenField class:
Table 3.37: Noteworthy Property of the HiddenField Class
Propertty Descriptio
on
Value Obtains the value of a HiddenField control

Now, let’s create a Web application to learn the use of the HiddenField control.

Using the HiddenField Controls


You can create a Web application to learn the use of the HiddenField control.
Let’s perform the following steps to learn the procedure of using the HiddenFielld control:
1. Open Visual Studio 201
12.
New
2. Select FILE Project option 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 template in the middle pane.
5. Enter Hiddenfield in the Name text box as the name of the Web application and specify an
appropriate location for the application in the Location box.
6. Click the OK button. The Hiddenfield application is created.
7. Add a Web form to the Hiddenfield application.
8. Add one Labell control (LLabel1) and one Button control (B
Button1) to the Web form from the
Toolbox.
9. Set the Text property of the Button1 control to Click Here to show Hidden Field Value, in the
Properties window.
10. Drag and drop a HiddenField control (H
HiddenField1) on to the Web form from the Toolbox.
The Web form now appears, as shown in Fig.ASP-3.52:

 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

The Wizard Control


The Wizard control provides a means to navigate a series of steps in the control and its user Interface
(UI) to collect related data across multiple steps. It also allows you to implement linear or non-linear
navigation through the steps, such as skipping unnecessary steps or returning to a previously completed
step to change a value. The appearance of the Wizard control is fully customized by using templates,
skins, and style settings; for example, you can use the Header template, and the
startNavigationTemplate, FinishNavigationTemplate, and StepNavigationTemplate properties to
customize the interface of the Wizard control. The hierarchy of the Wizard control class is as follows:
System.Object
System.Web.UI.control
System.Web.UI.WebControls.WebControl
System.Web.UI.WebControls.CompositeControl
System.Web.UI.WebControls.Wizard

Table 3.38 lists noteworthy properties of the Wizard class:


Table 3.38: Noteworthy Properties of the Wizard Class
Propertty Descriptio
on
ActiveStep Obtains a step in the WizardSteps collection, which is currently displayed to
a user
HeaderText Obtains or sets a text caption displayed for the header area on a Wizard
control
SideBarButtonStyle Obtain a reference to a Style object, which describes the settings for the
buttons of the sidebar in a Wizard control
SideBarTemplate Obtains or sets the template used to display the sidebar area in a Wizard
control
WizardSteps Obtains a collection containing all the WizardSteps objects described for a
Wizard control
StepStyle Obtains a reference to a Style object, which describes the settings for the
WizardStep objects

Table 3.39 lists noteworthy methods of the Wizard class:


Table 3.39: Noteworthy Methods of the Wizard Class
Propertty Descriptio
on
GetHistory Obtains a collection of WizardStepBase objects that have been accessed
GetStepType Obtains the WizardStepType value for the specified WizardStepBase
object
MoveTo Sets the specified WizardSTepBase-derived object as the value for the
Active Step property of the Wizard control

126
Standard Controls

Table 3.40 lists noteworthy events of the Wizard class:


Table 3.40: Noteworthy Events of the Wizard Class
Propertty Descriptio
on
ActiveStepChanged Occurs when a user switches to a new step in a Wizard control
CancelButtonClick Occurs when the Cancel button is clicked in a Wizard control
FinishButtonClick Occurs when the Finish button is clicked in a Wizard control
PreviousButtonClick Occurs when the Previous button is clicked in a Wizard control
SideBar ButtonClick Occurs when a button in the sidebar area is clicked in a Wizard control
NextButtonClick Occurs when the Next button is clicked in a Wizard control

Now, let’s learn to use the Wizard control in a Web application.

Using the Wizard Control


You can create an application in which to use of the Wizard control.
Let’s perform the following steps to learn the procedure of using the Wizard control:
1. Open Visual Studio 201
12.
New
2. Select FILE Project option 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 template in the middle pane.
5. Enter Wizardcontrol in the Name text box for the name of the Web application and enter an
appropriate location for the application in the Location combo box.
6. Click the OK button. The Wizardcontrol application is created.
7. Add a Web form to the Wizardcontrol application.
8. Drag and drop a Wizarrd control from the Toolbox on to the Web form.
The Web form appears, displaying two steps, Step 1 and Step 2 (Fig.ASP-3.54).
9. Click the smart tag (>) of the Wizard control. A list of options appears (Fig.ASP-3.54).
10.. Select the Auto Format option, as shown in Fig.ASP-3.54:

10

 Fig.ASP-3.54

The AutoFormat dialog box appears (Fig.ASP-3.55).

127
ASP.NET 4.5 in Simple Steps

11. Select an option from the Select a schem


me pane. In our case, we select the Classiic scheme
(Fig.ASP-3.55).
2. Click the OK button to save the settings, as shown in Fig.ASP-3.55:
12

11

12

 Fig.ASP-3.55

3. Open the Propertie


13 es window of the Wizarrd control and set its Height, Widtth, and HeaderTexxt
properties. In our case, we set the HeaderTexxt property to Wizarrd control, the Heigh
ht property to
204p
px, and the Widtth property to 381p px.
14. Right–click the Wizarrd control. A context menu appears (Fig.ASP-3.56).
15. Select the Add/Remove WizardStep
ps option from the context menu, as shown in Fig.ASP-3.56:

15

 Fig.ASP-3.56

The WizardStep Collection Edito


or dialog box appears (Fig.ASP-3.57).
6. Set the Titlle property for the two members in the Memberrs pane in the Enter Full Nam
16 me
properties pane (Fig.ASP-3.57).

128
Standard Controls

7. Click the OK button to save the settings, as shown in Fig.ASP-3.57:


17

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

20. Double-click the Finish Butto


on of the Enter Address step in the Wizard control in the Design mode
and add the following code snippet in the Click event of the control:
protected void Wizard1_FinishButtonClick1(object sender, WizardNavigationEventArgs e)
{
Response.Write("Wizard is finished");
Wizard1.Visible = false;
}
1. Press the F5 key to view the output(Fig.ASP 3.59).
21
2. Click the Enter Addresss step to move to the next step in the wizard control, as shown in Fig.ASP-3.59.
22

22

 Fig.ASP-3.59

The Enter Addresss step appears (Fig.ASP-3.60).


3. Click the Finissh button of the Wizarrd control to complete the steps, as shown in Fig.ASP-3.60:
23

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

What you will learn in this chapter?


 T he S ite Ma pP a th C ontrol
 T he T re e V ie w C ontrol
 T he Me nu C ontrol

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.

The SiteMapPath Control


The SiteMapPath control is a navigation control that displays the map of the site related to its Web
pages. This map includes the pages of a particular Web site and displays the name of those pages. You
can click that particular page in the SiteMapPath control to navigate to that page. In other words, the
SiteMapPath control displays links for connecting to Uniform Resource Locators (URLs) of other Web
pages. Out of all the Web pages contained in an ASP.NET Web site, you can choose any page to act as
a Home page or start page. This page is also known as root node. A user can access the Home page
and any other page of the Web site with the help of the SiteMapPath control.
h control uses a propertty called SiteMapProvider for accessing data from a database.
The SiteMapPath
The SiteMapProvider provider stores the information related to SiteMapPath control in a data source.
The SiteMapProvider provider internally utilizes the SiteMapProvider abstract class defined under the
System.Web namespace.
The methods defined in this abstract class create a schema containing nodes that represents Web
pages. This schema, which is produced by the SiteMapProvider, is represented as a URL by the
SiteMapPath
h control.
ASP.NET 4.5 in Simple Steps

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

Table 4.2 lists the eventts of the SiteMapPath class:


Table 4.2: Events of the SiteMapPath Class
Events Description
ItemCreated Occurs when a SiteMapNodeItem is created by the SiteMapPath and is
associated with its corresponding SiteMapNode.
ItemDataBound Occurs after a SiteMapNodeItem has been bound to its underlying
SiteMapNode data by the SiteMapPath.

Table 4.3 lists the methods of the SiteMapPath class


Table 4.3: Methods of the SiteMapPath Class
Methods Description
DataBind Binds the data source to the SiteMapPath control and all its child
controls.
ApplyStyleSheetSkin Applies stylesheet to the control

134
Navigation Controls

Let’s create a Web application to learn the usage of the SiteMapPath control.

Creating the SiteMapPath Control


You can create a Web application to know the usage of the control by performing the following steps:
All Programs
1. Open Start Microsoft Visual Studio 2012
 Visual Studio 2012.
New
2. Select FILE Project from the menu bar.
The New Project 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 sitemappath in the Name 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 sitemappath application is created.
8. Open the Solution Explorer window and right-click the application name. In this case, we are
right-clicking the sitemappath application.
New Item option from the context menu.
9. Select the Add
The Add New Item - sitemappath dialog box appears.
10. Select Web Form from the middle pane.
11. Click the Add button.
The WebForm1.aspx form is added to the sitemappath application.
12. Add two more Web forms to the application similarly.
13.. Right-click the sitemappath in the Solution Explorer window. A context menu appears (Fig.ASP-4.1).
New Item option from the context menu, as shown in Fig.ASP-4.1:
14. Select the Add

14

 Fig.ASP-4.1

The Add New Item dialog box appears (Fig.ASP-4.2).


15. Select InstalledVisual C#Web from the left pane and Site Map from the middle pane of the
Add New Item dialog box (Fig.ASP-4.2).
16. Click the Add button, as shown in Fig.ASP-4.2:

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

17. Add the following code snippet in the Web.sitemap file:


<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
<siteMapNode url="WebForm1.aspx" title="Home page" description="">
<siteMapNode url="WebForm2.aspx" title="WebForm 2" description="" />
<siteMapNode url="WebForm3.aspx" title="WebForm 3" description="" />
</siteMapNode>
</siteMap>

18. Add the SiteMapPatth control and two HyperLin


nk controls on the Web Form1 (Fig.ASP-4.4).
19. Open the Propertie
es window and set the Texxt property of HyperLinkk1 and HyperLinkk2 as Visit
form page 2 and Visit form page 3, respectively (Fig.ASP-4.4):
Similarly, set the NavigateUrl property of the HyperLink1 and HyperLink2 control to
WebForm2.aspx and WebForm3.aspx, respectively, as shown in Fig.ASP-4.4:

136
Navigation Controls

 Fig.ASP-4.4

Similarly, drag and drop the SiteMapPatth control on the WebForm2.asp


px and WebForm3.asp
px
forms.
20. Press the F5 key. The SiteMapPatth control is displayed in the browser (Fig.ASP-4.5).
21. Click the Visit form page 2 link (Fig.ASP-4.5).
The WebForm2.asppx page appears on the screen, displaying the SiteMapPath control, as shown
in Fig.ASP-4.5:

 Fig.ASP-4.5

The TreeView Control


The TreeView w control is a navigation control that is used in Web applications to display the location of
different Web pages as a tree structure. This control is used in Web pages to enable the user to view the
structure of the Web application by traversing its nodes. In ASP.NET applications, you can use the
TreeVieew control for representing data accessed from an XML file or a database and arranging it
logically for the user of the Web application. The TreeView class of the .NET Framework defines the
properties of the TreeView w control. This class is defined in the System.Web.UI.WebControls
namespace. The TreeVie ew control has the following four types of nodes:
 Roott: Represents the top-level node in the tree
 Parentt: Represents parent nodes, which have child nodes shown as branches of the parent nodes
 Child
d: Contains its parent nodes
 Leaff: Contains no child nodes
The data displayed on these nodes can be filled by using the DataSource property, which binds the
control with data, of the TreeVie
ew control.
Table 4.4 lists some public properties of the TreeView class:
Table 4.4: Noteworthy Public Properties of the TreeView Class
Property Description
AutoGenerateDataBindings Obtains a value indicating whether or not the TreeView control
automatically generates tree node bindings

137
ASP.NET 4.5 in Simple Steps

Table 4.4: Noteworthy Public Properties of the TreeView Class


Property Description
CheckedNodes Obtains a collection of TreeNode objects that represent the nodes in the
TreeView control displaying a selected check box
CollapseImageToolTip Obtains the ToolTip for the image that is displayed for the collapsible node
indicator
CollapseImageUrl Obtains the URL to a custom image for the collapsible node indicator
DataBindings Obtains a collection of the TreeNodeBinding objects that define the
relationship between a data item and the node that it is binding to

Table 4.5 list some public methods of the TreeView class:


Table 4.5: Noteworthy Public Methods of the TreeView Class
Method Description
CollapseAll Closes every node in the tree
DataBind Binds data from the data source to the control
ExpandAll Opens every node in the tree

Table 4.6 lists some events of the TreeView class:


Table 4.6: Noteworthy Events of the TreeView Class
Event Description
SelectedNodeChanged Invokes when a node is selected in the TreeView control
TreeNodeCheckChanged Invokes when a check box in the TreeView control changes state
between posts to the server
TreeNodeCollapsed Invokes when a node is collapsed in the TreeView control

Let’s create a Web application to learn the usage of the TreeView control.

Creating a TreeView Control


Let’s now perform the following steps to create a TreeVie
ew control:
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 in the left pane of the New Project dialog box.
4.. Select ASP.NET Empty Web Application template in the middle pane of the New Project dialog
box.
5. Enter treeviewcontrol in the Name text box to specify the name of the application. In addition,
enter an appropriate location for the application in the Location combo box.

138
Navigation Controls

6. Click the OK button. The treeviewcontroll application is created.


7. Add a Web form to the treeviewcontroll application.
8. Drag and drop the TreeView w control on Design mode of the WebForm1.aspxx form (Fig.ASP-4.6).
9. Click the smart tag (>
>). A list of options appears (Fig.ASP-4.6).
0. Select the EditNode
10 es option from the list, as shown in Fig.ASP-4.6:

10

 Fig.ASP-4.6

The TreeView Node Edito


or dialog box appears.
1. Click the Add a root nod
11 de button in the TreeView Node Edito
or dialog box.
A new root node appears in the Node
es pane.
2. Click the Texxt property of the root node in the Propertie
12 es window and change it. We have
changed it to Hardwarre in this application, as shown in Fig.ASP-4.7:

11

12

 Fig.ASP-4.7

3. Click the Add a child nod


13 de button in the Node es pane to add the child node in the root node
(Fig.ASP-4.8).
4. Set the Texxt property of the child node in the Propertie
14 es pane. The Texxt property has been
changed as Keyboarrd in this application, as shown in Fig.ASP-4.8:

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

The Web form (W WebForm1.asp px) appears (Fig.ASP-4.10).


16. Click the smart tag (>) option on the TreeVie ew control (Fig.ASP-4.10).
A list of options appears (Fig.ASP-4.10).
17. Select the Autto Formaat option from the list, as shown in Fig.ASP-4.10:

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

The TreeView appears on the Web Form, as shown in Fig.ASP-4.12:

 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

The Menu Control


The Menu u control is a Web server control for representing data items. These data items can be
originated from a database, an XML file, or a sitemap file.

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

Table 4.8 lists the public method of the Menu class:


Table 4.8: Noteworthy Public Method of the Menu Class
Method Description
FindItem Obtains the menu item at the specified value path

Let’s create a Web application to learn the usage of the Menu control.

Creating Static Menu


Let’s perform the following steps to create an application showing a static menu or menu by using the
Menu control:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct from the menu bar. The New Projecct dialog box appears.
TemplatesVisual C#Web option in the left pane.
3. Select Installed

142
Navigation Controls

4. Select ASP.NET Empty Web Applicatio


on template in the middle pane.
5. Enter menucontrool in the Namme text box to specify the name of the application. In addition, enter
an appropriate location for the application in the Locatio
on combo box.
6. Click the OK button. The menucontro
ol application is created.
7. Add a Web Form to the menucontro ol application.
8. Drag and drop the Men nu control from the Toolboox on the Web Form (Fig.ASP-4.14).
9. Click the smart tag (>) option. The Men nu Taskks options appear on the Web Form (Fig.ASP-4.14).
10. Select the Edit Menu Item
ms option, as shown in Fig.ASP-4.14:

10

 Fig.ASP-4.14

The Menu Item Edito


or dialog box appears (Fig.ASP-4.15).
1. Click the Add a root nod
11 de button to add a root node (Fig.ASP-4.15).
2. Set the Texxt property from the Propertie
12 es pane.
3. Click the Add child nod
13 de button to add the child node under the root node (Fig.ASP-4.15).
4. Set the Texxt property of the child node.
14
Similarly, we can add any number of root nodes and child nodes in the Items pane of the Menu Item
Edito
or dialog box. We have added two root nodes and six child nodes in this application. After adding
the nodes, the Item
ms pane of the Menu Item Edito
or dialog box appears (Fig.ASP-4.15).
5. Click the OK button, as shown in Fig.ASP-4.15:
15

14

15

 Fig.ASP-4.15

143
ASP.NET 4.5 in Simple Steps

6. Open the Propertie


16 es window of the Men
nu control and set its Orientatio
on property as Horizonta
al,
as shown in Fig.ASP-4.16:

16

 Fig.ASP-4.16

The Web Forrm appears (Fig.ASP-4.17).


7. Click the smart tag (>) option. The Menu Tasks appears (Fig.ASP-4.17).
17
8. Select the Auto Forma
18 at option from the Menu Taskks, as shown in Fig.ASP-4.17:

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

1. Press the F5 key to view the Menu control (Fig.ASP-4.20).


21
2. Move the mouse on the Hom
22 me node. Its child node appears (Fig.ASP-4.20).
Whenever the mouse moves on any root node, its child node appears on the Web Form, as
shown in Fig.ASP-4.20:

22

 Fig.ASP-4.20

Let’s discuss how to create dynamic menu.

Creating Dynamic Menu


In a dynamic menu, data is provided by the DataSource e controls. To create a functional dynamic menu
on a Web page, you need to bind it with a DataSource e control, which in turn, collects the data from
physical data storage, such as XML files or databases.
Now, let’s create an application displaying dynamic menus using XML file as data source 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 of the New Project dialog
box.
4. Select ASP.NET Empty Web Application template in the middle pane of the New Project dialog
box.
5. Enter Dynamicmenucontrol in the Name text box to specify the name of the application. In
addition, enter an appropriate location for the application in the Location combo box.
6. Click the OK button. The Dynamicmenucontrol application is created.
7. Add a Web Form to the Dynamicmenucontrol application.
8. Drag and drop the Menu control from the Toolbox on the Web Form.

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

The Data Source Configuration Wizard appears (Fig.ASP-4.22).


15.. Select the XML File option from the Where will the application get data from? pane
(Fig.ASP-4.22).
16. Click the OK button, as shown in Fig.ASP-4.22:

146
Navigation Controls

15

16

 Fig.ASP-4.22

The Configure Data Sourcce dialog box appears.


7. Click the Browsse button beside the Data file text box.
17
The Select XML File
e dialog box appears (Fig.ASP-4.23).
8. Select XMLFILE1.xm
18 ml file from the Contents of folde
er pane (Fig.ASP-4.23).
9. Click the OK button, as shown in Fig.ASP-4.23:
19

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

What you will learn in this chapter?


 T he B a s e V a lida tor C la ss
 T he R e quire dF ie ldV a lida tor C ontrol
 T he R a nge V a lida tor C ontrol
 T he R e gula rE xpre ssionV a lida tor C ontrol
 T he C ompa re V a lida tor C ontrol
 T he C ustomV a lida tor C ontrol
 T he V a lida tionS umma ry C ontrol
 T he V a lida tionG roup P rope rty

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.

The BaseValidator Class


The System.Web.UI.WebControls.BaseValidatoor class is the base class for all the validation controls. It
provides the basic implementation needed for all validation controls. The inheritance hierarchy of the
System.Web.UI.WebControls.BaseValidator class is as follows:
System.Object
System.Web.UI.Control
System.Web.UI.WebControls.WebControl
ASP.NET 4.5 in Simple Steps

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

Now, let’s discuss the various validation controls in detail.

The RequiredFieldValidator Control


The RequiredFieldValidator control ensures that the user has entered the required data in the input
control, such as the TextBox control, to which it is bound. For example, if you are entering data to buy a
T-shirt in an input control, then it is necessary to enter the size of the T-shirt that you want to buy. If you
do not enter the size, the validation control displays an error message.
Table 5.3 lists the noteworthy public property of the RequiredFieldValidator class:

150
Validation Controls

Table 5.3: Noteworthy Public Property of the RequiredFieldValidator Class


Property Description

InitialValue Handles the initial value of the associated input control

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

Now, let’s know about the RangeValidato


or control.

The RangeValidator Control


The RangeValidator Control
The RangeValidato or control checks whether or not the value of an input control lies within a specified
range of values. The following are the properties of the RangeValidato
or control:
 ControlToValidate:: Contains the input control to validate
 MinimumValue:: Holds the minimum value of the valid range
 MaximumValue
e: Holds the maximum value of the valid range
If one of these properties is set, then the other properties must also be set; otherwise, it gives error
messages. Do not forget to set the Type property to the data type of the input control to avoid error due
to type of data entered in the control. The different data types that can be used for the input control
values are Strin
ng, Integer, Double, Datte, and Currency.
Table 5.4 lists the noteworthy public properties of the RangeValidator class:
Table 5.4: Noteworthy Public Properties of the RangeValidator Class
Property Description
MaximumValue Obtains or sets the maximum value of the validation range
MinimumValue Obtains or sets the minimum value of the validation range

You can also use it to validate a range of numbers, strings, and dates.

Using the RangeValidator Control


You can create an application to learn the usage of RangeValidato or control. Let’s perform the following
steps to learn the use of the RangeValidato
or 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.
TemplatesVisual C#Web option in the left pane.
3. Select Installed
4. Select the ASP.NET Empty Web Application template in the middle pane.
5. Enter Rangevalidator in the Name text box to specify the name of the application. In addition,
enter an appropriate location for the application in the Location text box.
6. Click the OK button. The Rangevalidator Web application is created.

153
ASP.NET 4.5 in Simple Steps

7. Add a Web form to the Rangevalidato


or Web application.
8. Drag and drop three Labe
el controls, two TextBo
ox controls, and one Butto
on control from the
Toolbo
ox.
9. Open the Properties window and set the Text property of Label1 control as Range Validator
Example, Label 2 as Your Age , Label 3 control as Date of birth (YYYY/MM/DD format), and
Button1 control as Submit.
0. Drag and drop the two RangeValidato
10 or controls (R
RangeValidatorr1 and RangeValidatorr2) from the
Toolboxx on the Web forrm.
11. Open the Propertie es window and bind the ControlToValidatte property of the RangeValidator1 control
to the TextBoxx1 control and set the ErrorMessage
e property as Age shoulld be between 18 to 99.
2. Set the MaximumValu
12 ue property of the RangeValidatorr1 control to 99 and MinimumValu
ue
property to 18.
Similarly, bind the ControlToValidatte property of the RangeValidator2 control to the TextBox2
control and set the ErrorMessaage property as Enter a date between 1900/1/1 to 2012/1//1. Set
the MaximumValu ue property of the RangeValidator2 2 control to 2012/1//1 and MinimumValu ue
property to 1900/1//1.
After setting all the properties and arranging the controls accordingly, the Web form appears, as
shown in Fig.ASP-5.3:

 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>

3. Press the F5 key to execute the Web application (Fig.ASP-5.4).


13
4. Enter the values in the textboxes and click the Submiit button, as shown in Fig.ASP-5.4:
14

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.

The RegularExpressionValidator Control


The RegularExpressionValidator control validates whether or not the value in the input control
(textbox) matches the format specified by regular expressions, such as a US telephone number or the
US date format. The RegularExpressionValidator control exists within the
System.Web.UI.WebControls namespace.
In general, regular expressions consist of text with an embedded code listing that starts with a backslash
(\) as well its code listing. The following is an example of the code listing in a control:
\b[A-Za-z]+\b
The code for a word boundary (where a word ends or starts) is \b. A character class is a set of
characters surrounded by [and], allowing you to specify what characters you want to accept. Therefore,

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.

Using the RegularExpressionValidator Control


You can use the RegularExpressionValidato
or control in a Web application by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewProjectt option from the menu bar. The New Projectt dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane of the New Project dialog
box.
4. Select the ASP.NET Empty Web Application template in the middle pane.
5. Enter Regularexpressionvalidator 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 Regularexpressionvalidator Web application is created.
7. Add a Web form to the Regularexpressionvalidator Web application.
8. Add three Label controls, two TextBox controls, and one Button control from the Toolbox.
9. Open the Properties window and set the Textt property of Label1 control as Using
RegularExpressionValidator control, Label2 control as Enter URL, Label 3 as Enter E-mail
address, and Button control as Submit.
10. Drag and drop two RegularExpressionValidator controls from the Validation tab of the Toolbox to
the Web form.
11. Open the Properties window, and set the ControlToValidate property as TextBox1, ErrorMessage
as Please Enter Valid URL of the RegularExpressionValidator1 control Properties window.

156
Validation Controls

2. Open the Propertie


12 es window and click the ellipsse button beside the ValidationExpressio
on property
of the RegularExpressionValidatorr1 control, as shown in Fig.ASP-5.5:

12

 Fig.ASP-5.5

The Regular Expression Edito


or dialog box appears (Fig.ASP-5.6).
13. Select Internet UR
RL in the Regular Expression Edito
or dialog box from the Standard expression
ns
pane to validate the URL (Fig.ASP-5.6).
14. Click the OK button, as shown in Fig.ASP-5.6:

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- ./?%&amp;=]*)?">
</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

The CompareValidator Control


The CompareValidato or control is used to compare the value entered by a user into one input control
with the value entered into another or with an already existing value. The CompareValidato or control
exists within the System.Web.UI.WebControls namespace.
Table 5.6 lists the noteworthy operator properties of the CompareValidator control:
Table 5.6: Operator Property Types of the CompareValidator Control
Type Description
Equal Specifies whether or not the compared values are equal

NotEqual Checks that controls values are not equal to each other

GreaterThan Checks for a greater than relationship

GreaterThanEqual Checks for a greater than or equal to relationship

LessThan Checks for a less than relationship

LessThanEqual Checks for a less than or equal to relationship

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.

Using the CompareValidator Control


Now, we will explain how this CompareValidator control is used in a Web application. Let’s learn how
to use the CompareValidato
or control by performing the following steps:

159
ASP.NET 4.5 in Simple 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 of the New Project dialog
box.
4. Select the ASP.NET Empty Web Application template in the middle pane.
5. Enter Comparevalidator in the Name text box to specify the name of the application. In addition,
enter an appropriate location for the application in the Location combo box.
6. Click the OK button. The Comparevalidator Web application is created.
7. Add a Web form to the Comparevalidator Web application.
8. Add three Labell controls, two TextBox controls, and one Button control from the Toolbox to the
Web form.
9. Open the Properties window and set the property of the Label1 control as CompareFieldValidator
Example, Label2 control as Father age:, Label3 control as Your age:, and Button1 control as
Submit.
10. Drag and drop one CompareValidator control on the Web form.
11. Open the Properties window and set its ControlToCompare property as TextBox1,
ControlToValidate property as TextBox2, and ErrorMessage property as Your age should be less
than your father’s age.
The Web form now appears, as shown in Fig.ASP-5.9:

 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>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

160
Validation Controls

<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <br />


<asp:Label ID="Label3" runat="server" Text="Your age:"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox> <br /> <br />
<asp:Button ID="Button1" runat="server" Text="Submit" /> <br />
<asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="Your age
should be less than your father’s age" ControlToCompare="TextBox1"
ControlToValidate="TextBox2"></asp:CompareValidator>
</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>

12. Press the F5 key to execute the Web application (Fig.ASP-5.10).


13. Enter the values in the textboxes such that the value entered in the Fathe
er age text box is less than
that entered in the Youur age text box. Click the Submiit button, as shown in Fig.ASP-5.10:

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).

The CustomValidator Control


The CustomValidatorr control checks that the input you have given, such as a prime, even, or odd
number, matches with a given condition or not. It basically validates the input provided by the user
against the user-defined validations. The CustomValidato or control exists within the
System.Web.UI.WebControls namespace.
The CustomValidator controll provides a very powerful way to use the validator controls, where you can
also write your own customization code.

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

Let’s create a Web application to learn the usage of the CustomValidato


or control.

Using the CustomValidator Control


Now, we will explain how this CustomValidator control is used in a Web application. Let’s learn the
procedure of creating the CustomValidator 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 the ASP.NET Empty Web Application template in the middle pane.
5. Enter Customvalidator 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 Customvalidator Web application is created.
7. Add a Web form to the Customvalidator Web application.
8. Add two Label controls, one TextBox control, and one Button control from the Toolbox.
9. Open the Properties window and set the Text property of Label1 Control as Custom Validator
example, Label 2 control as Please enter user name:, and Button1 control as Submit.
10. Drag and drop a CustomValidator control from the Validation tab in the Toolbox on the Web
form.
11. Open the Properties window and set the ControlToValidate property of CustomValidator control
with the TextBox1 control.
12. Set the error message in the ErrorMessage property of the CustomValidator1 control to Invalid
Entry: Correct username is: “ttestuser”.
The ClientValidationFunction property is set in the WebForm1.aspx form by using
VBScript language, as shown in the following code snippet:
<script language="vbscript" type="text/vbscript">
Sub Validate (source, arguments)

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>

14. Press the F5 key to execute the Web application (Fig.ASP-5.12).


15. Enter a value in the TextBoxx1 control (Fig.ASP-5.12)
16. Click the Submiit button, as shown in Fig.ASP-5.12:

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).

The ValidationSummary Control


The ValidationSummarry control collects all the validation control error messages for display at one
place. The ValidationSummarry control exists within the System.Web.UI.WebControls namespace.
The summary can be displayed as a bulleted list, or as a single paragraph based on the DisplayMode
property. You can also specify if the summary should be displayed in the Web page or in a message
box by setting the ShowSummary and ShowMessageBox properties, respectively.
Table 5.10 lists the noteworthy public properties of the ValidationSummary class:
Table 5.10: Noteworthy Public Properties of the ValidationSummary Class
Property Description
DisplayMode Obtains or sets the display mode of the validation summary
EnableClientScript Specifies whether or not the ValidationSummary control updates itself using
the client-side script

164
Validation Controls

Table 5.10: Noteworthy Public Properties of the ValidationSummary Class


Property Description
ForeColor Obtains or sets the foreground color of the control
HeaderText Obtains or sets the header text displayed at the top of the summary
ShowMessageBox Specifies whether or not the validation summary is displayed in a message box
ShowSummary Specifies whether or not the validation summary is displayed inline
ValidationGroup Obtains or sets the group of controls for which the ValidationSummary object
displays validation messages

Let’s create a Web application to learn the usage of the ValidationSummary control.

Using the ValidationSummary Control


Now, we will explain how ValidationSummary control can be used in a Web application. Let’s learn the
procedure of using the ValidationSummarry control in the Web application by performing the following
steps:
1. Open Visual Studio 20112.
2. Select FILENewProjecct option from the menu bar. The New Project dialog box appears.
Templates
3. Select Installed Visual C# Web option in the left pane.
4. Select the ASP.NET Empty Web Application template in the middle pane.
5. Enter Validationsummary 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 Validationsummary Web application is created.
7. Add a Web form to the Validationsummary Web application.
8. Add three Labell controls, two TextBox controls, and one Button control from Toolbox to the Web
form.
9. Open the Properties window and set the Textt property of the Label1 control as
ValidationSummary Example, Label2 as First Name:, Label3 as Last Name:, and Button1 as
Submit.
10. Drag and drop the two RequiredFieldValidator controls on the Web form.
11. Open the Properties window and set the ControlToValidate property of the
RequiredFieldValidator1 control as TextBox1, ErrorMessage as Firstname cannot be empty, and
Display as None.
Similarly, set the ControlToValidate property of the RequiredFieldValidator2 control as TextBox2,
ErrorMessage as Lastname cannot be empty, and Display as None.
12. Drag and drop a ValidationSummary control from the Validation tab on the Web form.
13. Open the Properties window of the ValidationSummary control and set its ShowSummary property as
True. By default, the value of the ShowSummary property of the ValidationSummary control is True.
After adding the controls and setting their properties, the Web form (Webform1.aspx) now
appears, as shown in Fig.ASP-5.13:

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>

4. Press the F5 key to execute the Web application (Fig.ASP-5.14).


14

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).

The ValidationGroup Property


In ASP.NET 4.5, there is one more feature known as ValidationGroup. The ValidationGroup property—
when set—validates only the validation controls within the specified group when the control is post back
to the server. This property is used to assign a validation control to a validation group.
Let’s create a Web application to learn the usage of the ValidationGroup property.

Using the ValidationGroup Property


Now, we will explain how ValidationGroup property is used in a Web application. Let’s learn the
procedure of using the ValidationGroup property by performing the following steps:
1. Open Visual Studio 201
12.
2. Select FILENewProjecct from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane.
4. Select the ASP.NET Empty Web Application template in the middle pane.
5. Enter Validationgroup in the Name e text box to specify the name of the Web application, and
enter an appropriate location for the application in the Location combo box.
6. Click the OK button. The Validationgroup Web application is created.
7. Add a Web form to the Validationgroup Web application.
8. Add five Label controls, two TextBox controls, and two Button controls from the Toolbox.
9. Open the Properties window and set the Text property of the Label1 control as ValidationGroup
property, Label2 as First validation group, Label3 as Name:, Label4 as Second validation group,
Label 5 as Phone:, Button1 as Submit, and Button2 as Submit.
10. Add two RequiredFieldValidator controls from the Validation tab in the Toolbox on the Web form.
11. Open the Properties window and set the ControlToValidate property of the
RequiredFieldValidator1 control as Textbox1, ErrorMessage as Name cannot be empty, and
ValidationGroup as FirstValidationGroup.

167
ASP.NET 4.5 in Simple Steps

Similarlly, set the ControlToValidatte property of the RequiredFieldValidatorr2 control as Textboxx2,


ErrorMessag ge as Phone number cannot be emptty, and ValidationGrou up as
SecondValidationGrou u p.
In this Web application, we have created two validation groups.
12. Set the ValidationGrouup property of Button
n1 as FirstValidationGrou
up and the ValidationGrou
up
property of Button2
2 as SecondValidationGrouup.
The Web form now appears, as shown in Fig.ASP-5.15:

 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/>
&nbsp; <br/>
<asp:Button ID="Button1" runat="server" Text="Submit"
ValidationGroup="FirstValidationGroup" /><br /><br />

168
Validation Controls

<asp:Label ID="Label4" runat="server" Text="Second validation


group"></asp:Label><br/><br/>
<asp:Label ID="Label5" runat="server" Text="Phone:"></asp:Label>
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="TextBox2" ErrorMessage="Phone number cannot be empty."
ValidationGroup="SecondValidationGroup"></asp:RequiredFieldValidator>
<br /> <br /> <br />
<asp:Button ID="Button2" runat="server" Text="Submit"
ValidationGroup="SecondValidationGroup" /><br />
</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>

3. Press the F5 key to execute the Web application (Fig.ASP-5.16).


13
4. Click the Submiit button of the First validation group. An error message appears, as shown in
14
Fig.ASP-5.16:

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

What you will learn in this chapter?


 T he U se r A ccounts
 T he Login C ontrol
 T he LoginN a me C ontrol
 T he LoginS ta tus C ontrol
 T he LoginV ie w C ontrol
 T he P a sswordR e cove ry C ontrol
 T he C ha nge P a ssword C ontrol
 T he C re a te U se rW iz a rd C ontrol

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

The User Accounts


You should first create a user account by using the ASP.NET Web Site Administration Tooll to work with
the Login controls Let’s perform the following steps to create a user account by using the ASP.NET Web
Site Administration Too
ol:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012.
2. Select FILENewProject option from the menu bar. The New Project 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 Creatinguseraccounts in the Name 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 Creatinguseraccounts application is now created.
8. Open the Solution Explorer window and right-click the application name. In our case, we are
right-clicking the Creatinguseraccounts application.
9. Select AddNew Item from the context menu. The Add New Item dialog box appears.
10. Select the Web Form option from the middle pane.
11. Click the Addd button. The WebForm1.aspx form is added to the Creatinguseraccounts
application.
12. Select the ASP.NET Configuration option from the PROJECT menu, as shown in Fig.ASP-6.1:

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

3. Click the Securityy link, as shown in Fig.ASP-6.2:


13

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

The Login Control


The Logiin control is a Web server control that provides a user interface (UI) for authenticating users of a
Web site. This control accepts a user ID and a password, which are used to authenticate the user of the
Web site. Generally, the Logiin control is used in designing the Home pag ge for a Web site. By using the
Logiin control on a Web form of any Web site, you can restrict access to other Web forms of the Web site
for unauthenticated users. It can be done by redirecting only authenticated users to any of those Web
forms of the Web site.
Table 6.1 lists the public properties of the Login class:
Table 6.1: Public Properties of the Login Class
Property Description
CreateUserText Retrieves or specifies the text of a link to a registration page for new users
CreateUserUrl Retrieves or specifies the uniform resource locator (URL) of the new user
registration page
DestinationPageUrl Retrieves or specifies the URL of the page displayed to the user when a login
attempt is successful
FailureAction Retrieves or specifies the action that occurs when a login attempt fails
FailureText Retrieves or specifies the text displayed when a login attempt fails
InstructionText Retrieves or specifies the login instruction text for the user
LoginButtonImageUrl Retrieves or specifies the URL of an image to use for the login button
LoginButtonText Retrieves or specifies the text for the Login control's login button
Password Retrieves the password entered by the user
PasswordLabelText Retrieves or specifies the text of the label for the password textbox
PasswordRecoveryText Retrieves or specifies the text of a link to the password recovery page
PasswordRecoveryUrl Retrieves or specifies the URL of the password recovery page
RememberMeText Retrieves or specifies the text of the label for the Remember Me check box
TitleText Retrieves or specifies the title of the Login control
UserName Retrieves the user name entered by the user
UserNameLabelText Retrieves or specifies the text of the label for the UserName textbox

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

Table 6.2: Noteworthy Public Events of the Login Class


Event Description
LoggingIn Invoked when a user submits login information before authentication takes place
LoginError Invoked when a login error is detected

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

The Propertie es window appears (Fig.ASP-6.7).


0. Click the ellipse button of the DestinationPageUrrl property, as shown in Fig.ASP-6.7:
10

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

The LoginName Control


The LoginNam me control is a Web server control that displays the user ID of the currently logged in user.
The user ID is displayed only for the authenticated users.
Table 6.3 lists the public properties of the LoginName class:
Table 6.3: Public Properties of the LoginName Class
Property Description
AccessKey Allows quick navigation to the Web server control
Attributes Fetches the collection of arbitrary attributes
TemplateSourceDirectory Fetches the virtual directory of the Page or UserControl that
contains the current server control

Table 6.4 lists the public methods of the LoginName class:


Table 6.4: Public Methods of the LoginName Class
Method Description
ApplyStyleSheetSkin Applies the styles defined in the page style sheet
Databind Binds a DataSource to the server control
ResolveUrl Converts a URL relative to the root directory of the Web application
so that it is usable for the client

Table 6.5 lists the public events of the LoginName class:


Table 6.5: Public Events of the LoginName Class
Event Description
Load Invoked when the LoginName control loads into the Page object
PreRender Invoked when the LoginName control is loaded from the memory
Unload Invoked when the LoginName control is unloaded from the memory

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. Click the smart tag (>) of the Login


n1 control, the Login Taskks appears (Fig.ASP-6.13).
13. Select the Administer Websitte option, as shown in Fig.ASP-6.13:

12
13

 Fig.ASP-6.13

The ASP.NET Web Site Administration Too ol home page appears.


4. Select the Securitty option. The Securitty page opens.
14
5. Click the Use the security Setup Wizarrd to configure step-by-step link. The Security Setup Wizarrd
15
windoow opens.
6. Click the Nexxt button to move to the next step, as shown in Fig.ASP-6.14:
16

16

 Fig.ASP-6.14

180
Login Controls

The Select Access Metho od page appears (Fig.ASP-6.15).


17. Select the From the Interne et option (Fig.ASP-6.15).
18. Click the Nexxt button, as shown in Fig.ASP-6.15:

17

18

 Fig.ASP-6.15

The Advanced provider setting


gs page appears.
9. Click the Nextt button. The Define Role
19 es page appears (Fig.ASP-6.16).
0. Select the check box beside the Enable roles for this Web sitte option (Fig.ASP-6.16).
20
1. Click the Nextt button, as shown in Fig.ASP-6.16:
21

20

21

 Fig.ASP-6.16

The Create New rolle page appears.


2. Click the Nexxt button.
22

181
ASP.NET 4.5 in Simple Steps

The Create Use


er page appears (Fig.ASP-6.17).
3. Enter the User Name, Password, Confirm Password, E-mail, Security Questio
23 on, and Security
answerr, as shown in Fig.ASP-6.17.
4. Click the Creatte Use
24 er button, as shown in Fig.ASP-6.17.

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

The Add New Access Rulle page appears (Fig.ASP-6.19).


26
6. Select the All Userrs option in the Rulle applies to section (Fig.ASP-6.19).
27
7. Select the Allo
ow radio button in the Permission ns section (Fig.ASP-6.19).
28
8. Click the Add This Rulle button in the Permission ns section to apply the settings (Fig.ASP-6.19).
29
9. Click the Nexxt button, as shown in Fig.ASP-6.19:

182
Login Controls

27

26
28

29

 Fig.ASP-6.19

The Completing the Security Setup Wizarrd page appears.


0. Click the Finissh button.
30
The Securitty tab appears again.
311. Click the Close (X) butto
on to close the ASP.net Web Site Administration Too
ol window.
Listing 6.2 shows the source code of WebForm1.aspx form after setting the properties of the control:
Listing 6.2
2: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Loginnamecontrol.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>
32. Press the F5 key to execute the application in the browser (Fig.ASP-6.20).
33. Enter the User Nam me and Passworrd that you have created, in the TextBo
ox controls on the Web
form.
34. Click the Log In button, as shown in Fig.ASP-6.20:

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

The LoginStatus Control


The LoginStatuus control is a Web server control that informs user by displaying text, which specify whether or
not the user of the Web site is currently logged on or out. The text displayed on this control changes
according to the login status of the user. The LoginStatus control has the following two views:
 Logged Outt: Displayed when the user is not logged in. In this view, the text Logiin is displayed on
the LoginStatus control.
 Logged In:: Displayed when the user is logged in. In this view, the text Logou
ut is displayed on the
LoginStatus control.
Table 6.6 lists the properties of the LoginStatus class:
Table 6.6: Public Properties of the LoginStatus Class
Property Description
LoginImageUrl Retrieves or sets the URL of the image used for the login link
LoginText Retrieves or sets the text used for the login link
LogoutAction Retrieves or sets a value that determines the action taken when a user logs out of a
Web site with the LoginStatus control
LogoutImageUrl Retrieves or sets the URL of the image used for the logout button
LogoutPageUrl Retrieves or sets the URL of the logout page
LogoutText Retrieves or sets the text used for the logout link

Table 6.7 lists the methods of the LoginStatus class:


Table 6.7: Public Methods of the LoginStatus Class
Method Description
ApplyStyleSkin Applies the visual properties set for the control in the designer
ApplyStyle Copies any nonblank elements of the specified style to the LoginStatus control

Table 6.8 lists the public events of the LoginStatus class:


Table 6.8: Public Events of the LoginStatus Class
Event Description
LoggingOut Invoked after the user has sent a logout request to the server by clicking the logout link

184
Login Controls

Table 6.8: Public Events of the LoginStatus Class


Event Description
LoggedOut Invoked by the LoginStatus class when the user logout process is complete
Load Invoked when the LoginStatus control loads in the Page object

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

The SelectURRL dialog box appears (Fig.ASP-6.25).


5. Select the WebForm1.aspx option from the Contents of folde
15 er pane (Fig.ASP-6.25).
6. Click the OK button, as shown in Fig.ASP-6.25:
16

15

16

 Fig.ASP-6.25

17. Open the WebForm


m1 and add the Login control from the Logiin tab of the Toolbo
ox on the Web
form.
18. Open the Propertiees window of the Logiin control and set the URL as ~/W
WebForm
m2.a
asp
px in the
DestinationPageUrrl property of the Logiin control.
19. Create a user account by using ASP.NET Web Site Administration Tool.
Listing 6.3 shows the source code of WebForm1.aspx form after adding the controls and setting the
properties:
Listing 6.3
3: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Loginstatuscontrol.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.4 shows the source code of WebForm2.aspx after adding the controls and setting the
properties:
Listing 6.4
4: Code of WebForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="Loginstatuscontrol.WebForm2" %>
<!DOCTYPE html >

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

The LoginView Control


The LoginVie
ew control is a Web Server control that is used to display two different views of a Web page
of any Web site on the basis of whether or not the user is currently logged in. The LoginView w control
manages contents for both the views of the Web page with the help of the following templates:
 AnonymousTemplatte: It is displayed when the user is not logged in.
 LoggedInTemplatte: It is displayed when the user is logged in.

187
ASP.NET 4.5 in Simple Steps

Table 6.9 lists the public properties of the LoginView class:


Table 6.9: Public Properties of the LoginView Class
Property Description
AnonymousTemplate Retrieves or sets the template to display to users who are not logged in to the
Web site
Controls Retrieves the ControlCollection object that contains the child controls for the
LoginView control
EnableTheming Retrieves or sets a value indicating whether or not themes are applied to the
LoginView control
LoggedInTemplate Retrieves or sets the template to display to Web site users who are logged in to
the Web site but are not members of one of the role groups specified in the
RoleGroups property
RoleGroups Retrieves a collection of role groups that associate content templates with
particular roles
SkinID Retrieves or sets the skin to apply to the LoginView control

Table 6.10 lists the public methods of the LoginView class:


Table 6.10: Public Methods of the LoginView Class
Method Description
DataBind Binds a data source to the LoginView control and all its child controls. This
method is overridden.
Focus Sets the input focus to a control. This method is overridden.

Table 6.11 lists the public events of the LoginView class:


Table 6.11: Public Events of the LoginView Class
Event Description
ViewChanged Invoked after the view is changed
ViewChanging Invoked before the view is changed

Now, you learn how to use the LoginView


w 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.
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 Loginviewcontrol 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 Loginviewcontrol application is created.
7. Add a Web form to the Loginviewcontrol application.

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

5. Open the WebForm


15 m1 and add the Login control from the Logiin tab of the Toolbo
ox, and set the
DestinationPageUrrl property to ~/W
WebForm2.asp
px of the Login control.
16
6. Create a user account by using the ASP.net Web Site Administration Tooll option.
Listing 6.4 shows the source code of WebForm1.asp
px form after setting the properties of the controls on
WebForm1.aspx form:
Listing 6.4
4: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Loginviewcontrol.WebForm1" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

189
ASP.NET 4.5 in Simple Steps

<asp:Login ID="Login1" runat="server" DestinationPageUrl="~/WebForm2.aspx">


</asp:Login>
</div>
</form>
</body>
</html>
Listing 6.5 shows the source code of the WebForm2.aspx form after setting the properties of controls:
Listing 6.5
5: Code of WebForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="Loginviewcontrol.WebForm2" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:LoginView ID="LoginView1" runat="server">
<LoggedInTemplate>
<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" />
</LoggedInTemplate>
</asp:LoginView></div>
</form>
</body>
</html>
7. Press the F5 key to execute the application (Fig.ASP-6.30).
17
8. Enter the User Nam
18 me and Passworrd that you have created (Fig.ASP-6.30).
9. Select the Remember me next tim
19 me checkbox and click the Log In button, as shown in Fig.ASP-6.30:

19

 Fig.ASP-6.30

The WebForm2.aspx form appears (Fig.ASP-6.31).


200. Click the Logou
ut button (Fig.ASP-6.31).
The WebForm1.aspx form, which is the login form, appears again, as shown in Fig.ASP-6.31:

20

 Fig.ASP-6.31

190
Login Controls

Let’s now learn the usage of the PasswordRecoverry Control.

The PasswordRecovery Control


The PasswordRecoverry control is a Web server control that provides a UI for recovering or resetting a
forgotten password of the login account in a Web site. Passwords recovered by using the
PasswordRecoverry control are sent to the e-mail addresses of the concerned users, specified at the time
of creating the user account. The PasswordRecoverry control has the following three views:
 UserNam me: Asks the user to enter the user name to recover the password
 Questio
on: Asks the user to enter the answer for its security question
 Success: Displays the message to the user that specifies that the retrieved password has been sent
to the user
Table 6.12 lists the public properties of the PasswordRecovery class:
Table 6.12: Public Properties of the PasswordRecovery Class
Property Description
AnswerRequiredErrorMessage Using this property, a custom error message for the
PasswordRecovery control can be specified in case the user leaves
the answer field blank
QuestionFailureText Using this property, a custom message for the PasswordRecovery
control can be specified in case the user provides incorrect answer
SuccessText Using this property, a custom message for the PasswordRecovery
control can be specified in case the task of password recovery is
accomplished successively

Table 6.13 lists the public events of the PasswordRecovery class:


Table 6.13: Public Events of the PasswordRecovery Class
Event Description
AnswerLookupError Invoked when the user’s answer to the question is found to be incorrect
SendingMail Invoked when the server sends an e-mail containing the password after
the user’s answer is found to be correct
VerifyingAnswer Invoked when the user has submitted the answer to the password-recovery
confirmation question

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

9. Select the WebForm1.asp


px form and add a Login control on it.
0. Create a user account by using ASP.NET Web Site Administration Too
10 ol as done earlier.
1. Drag and drop a HyperLin
11 nk control on the Design view of the WebForm1 from the Toolbox, and
set its Texxt property to Forgot Passwordd? and NavigateUrrl property to ~/W
WebForm2.asp
px.
The WebForm1.aspx Web form now appears, as shown in Fig.ASP-6.33:

 Fig.ASP-6.33

12. Open the Internet Information Services (IIS) Manage


er (Fig.ASP-6.34).
13. Double-click the SMTP E-maill option from the ASP.NET section, as shown in Fig.ASP-6.34:

13

 Fig.ASP-6.34

The SMTP E-maiil page appears (Fig.ASP-6.35).


4. Select the Store e-mail in pickup directorry option and browse for a pickup directory where your
14
password details will be sent (Fig.ASP-6.35).

192
Login Controls

5. Click the Browsse button, as shown in Fig.ASP-6.35:


15

15

 Fig.ASP-6.35

The Browse For Folde


er dialog box appears (Fig.ASP-6.36).
6. Select the application nam
16 me, that is, Passwordrecoveryy control (Fig.ASP-6.36).
17. Click the OK button, as shown in Fig.ASP-6.36:

16

17

 Fig.ASP-6.36

18. Click the smart tag of the Logiin control.


The Login Taskks option appears.
19. Select the Administer Web sitte from the Login Taskks.
The ASP.net Web Site Administration Too ol home page appears (Fig.ASP-6.37).
20. Select the Application Ta
ab, as shown in Fig.ASP-6.37:
21. Select the Configure SMTP e-mail setting
gs option from the SMTP Setting
gs pane, as shown in
Fig.ASP-6.37:

193
ASP.NET 4.5 in Simple Steps

21

 Fig.ASP-6.37

The Configure SMTP Setting gs page appears in the Applicatio


on tab (Fig.ASP-6.38).
2. Enter the Server Name as smtpout.secureserver.net (Fig.ASP-6.38).
22
3. Enter the Server Portt as 25 (Fig.ASP-6.38).
23
4. Enter your e-mail ID in the Fro
24 om text box (Fig.ASP-6.38).
5. Select the Basiic option (Fig.ASP-6.38).
25
6. Enter your e-mail ID in the Sender’s user name
26 e textbox (Fig.ASP-6.38).
7. Enter the Sender’s Password
27 d as your password (Fig.ASP-6.38).
8. Click the Savve button, as shown in Fig.ASP-6.38:
28

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

The ASP.net Web Site Administration Too


ol window appears again.
0. Click the Close(X
30 X) button.
Listing 6.6 shows the source code of the WebForm1.aspx form after setting the properties of the control:
Listing 6.6
6: Code of WebForm1.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
Inherits="Passwordrecoverycontrol.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>
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/WebForm2.aspx">Forgot
password?</asp:HyperLink></div>
</form>
</body>
</html>
Listing 6.7 shows the source code of the WebForm2.aspx form after setting the properties of controls::
Listing 6.7
7: Code of WebForm2.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs"
Inherits="Passwordrecoverycontrol.WebForm2" %>
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server"><title></title></head>
<body>
<form id="form1" runat="server">
<div>
<asp:PasswordRecovery ID="PasswordRecovery1" runat="server">
</asp:PasswordRecovery>
</div></form>
</body></html>
1. Select the WebForm1.aspx form in the Passwordrecoverycontro
31 ol application (Fig.ASP-6.40).
2. Press the F5 key to execute the application in the browser (Fig.ASP-6.40).
32

195
ASP.NET 4.5 in Simple Steps

3. Click the Forgot Passworrd? Link, as shown in Fig.ASP-6.40:


33

33

 Fig.ASP-6.40

4. Enter the user name in the User Nam


34 me text box (Fig.ASP-6.41).
5. Click the Submiit button, as shown in Fig.ASP-6.41:
35

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

The ChangePassword Control


There may be situations when you want to change your existing password: for example, if your
password is not a strong password. In such situations, you can change the existing password by using
the ChangePassworrd control. The ChangePassworrd control prompts a user to enter the old and new
passwords. The new password needs to be specified twice in the control. If the user enters the old
password incorrectly, then the new password does not take effect. However, if the user correctly enters

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

Table 6.14: Public Properties of the ChangePassword Class


Property Description
Continue button is configured by the ContinueButtonType property to
be an image button
ContinueButtonText Retrieves or sets the text that is displayed on the Continue button on the
Success view of the ChangePassword control
ContinueDestinationPageUrl Retrieves or sets the URL of the Web page that the user will see after
clicking the Continue button on the Success view
CreateUserIconUrl Retrieves or sets the URL of an image to display next to the link of the
Web page that contains a CreateUserWizard control for the Web site
CreateUserText Retrieves or sets the text of the link to the Web page that contains a
CreateUserWizard control for the Web site
CreateUserUrl Retrieves or sets the URL of the Web page that contains a
CreateUserWizard control for the Web site
CurrentPassword Retrieves the current password for the user
DisplayUserName Retrieves or sets a value indicating whether the ChangePassword
control should display the UserName control and label

Table 6.15 lists the public events of the ChangePassword class:


Table 6.15: Public Events of the ChangePassword Class
Event Description
CancelButtonClick Occurs when the user clicks the Cancel button to cancel the changing
of a password
ChangedPassword Occurs when the password is changed for a user account
ChangingPassword Occurs before the password for a user account is changed by the
membership provider
ContinueButtonClick Occurs when the user clicks the Continue button
SendingMail Occurs before the user is sent an e-mail confirmation that the
password has been changed

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

The CreateUserWizard Control


The CreateUserWizard control creates a new user in the aspnetdb database present in the ASP.NET.
You can add users either through the ASP.NET Web Site Administration Tool or through the
CreateUserWizard control. You can customize the CreateUserWizard control by using templates
and other style properties.
If you need to collect some additional information about the user, you can do so by adding additional steps
in the wizard. The following are some of the important components of the CreateUserWizard control:
 CreateUserWizardSte ep: Contains the UI and logic to create a user account.
 CompleteWizardSte ep: Displays the information whenever a user account is created successfully.
 Collection of WizardStep ps: Displays one by one step for creating the new user. Though there can
be multiple steps, only one step is displayed at a given time.
 Navigation button ns: Allow users to go to the next or previous steps in the CreateUserWizard
control.
 SideBaar: Used for listing all WizardSteps and hence enables users to randomly access any of the
WizardSteps.
 Heade er: Provides the user the information regarding each step. This component is present at the
top of the wizard.
Table 6.16 lists public properties of the CreateUserWizard class:
Table 6.16: Public Properties of the CreateUserWizard Class
Property Description
Answer Retrieves or sets the user’s answer to the password recovery
confirmation question
AnswerLabelText Retrieves or sets the text of the label that identifies the password
confirmation answer textbox
AnswerRequiredErrorMessage Retrieves or sets the error message shown when the user does not enter
an answer to the password confirmation question
CompleteStep Retrieves a reference to the final user account creation step
CompleteSuccessText Retrieves or sets the text displayed when a Web site user account is
created successfully
ConfirmPassword Retrieves the second password entered by the user
ConfirmPasswordCompareError Retrieves or sets the error message shown when the user enters two
Message different passwords in the Password and Confirm Password textboxes
ConfirmPasswordLabelText Retrieves or sets text of the label for the second password textbox
ConfirmPasswordRequired Retrieves or sets the error message displayed when the user leaves the
Error Message confirm password textbox empty
ContinueButtonImageUrl Retrieves or sets the URL of an image used for the Continue button on
the final user account creation step
ContinueButtonText Retrieves or sets the text caption displayed on the Continue button

201
ASP.NET 4.5 in Simple Steps

Table 6.16: Public Properties of the CreateUserWizard Class


Property Description
ContinueDestinationPageUrl Retrieves or sets the URL of the Web page the user sees after clicking the
Continue button on the success page
DisableCreatedUser Retrieves or sets a value indicating whether the new user should be
allowed to log on to the Web site
DuplicateEmailErrorMessage Retrieves or sets the error message displayed when the user enters an e-
mail address already in use in the membership provider
DuplicateUserNameError Retrieves or sets the error message displayed when the user enters a
Message user name already in use in the membership provider
Email Retrieves or sets the e-mail address entered by the user
EmailLabelText Retrieves or sets the text of the label for the e-mail textbox
EmailRegularExpression Retrieves or sets a regular expression used to validate the provided e-
mail address
EmailRegularExpressionError Retrieves or sets the error message displayed when the entered e-mail
Message address does not pass the site’s criteria for e-mail addresses
EmailRequiredErrorMessage Retrieves or sets the error message shown to the user when an e-mail
address is not entered in the e-mail textbox
InvalidAnswerErrorMessage Retrieves or sets the message displayed when the password retrieval
answer is not valid
InvalidEmailErrorMessage Retrieves or sets the message displayed when the entered e-mail address
is not valid
InvalidPasswordErrorMessage Retrieves or sets the message displayed when the password entered is
not valid
InvalidQuestionErrorMessage Retrieves or sets the message displayed when the password retrieval
question entered is not valid

Table 6.17 lists the public events of the CreateUserWizard class:


Table 6.17: Public Events of the CreateUserWizard Class
Event Description
ContinueButtonClick Occurs when the user clicks the Continue button in the final user
account creation step
CreatedUser Occurs after the membership provider has created the new Web site
user account
CreateUserError Occurs when the membership provider cannot create the specified user
account
CreatingUser Occurs before the membership provider is called to create the new Web
site user account

202
Login Controls

Table 6.17: Public Events of the CreateUserWizard Class


Event Description
SendingMail Occurs before the user is sent an e-mail confirmation that an account
has been created
SendMailError Occurs when there is an SMTP error sending e-mail to the new user

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

What you will learn in this chapter?


 O ve rvie w of W e bP a rts C ontrols
 C re a ting a S imple W e bP a rts P a ge

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.

Overview of the WebParts Controls


The WebPartts controls comprise many controls, each performing a particular function. Various
WebPartts controls are available in ASP.NET 4.5.
Table 7.1 lists the functions of the WebParts controls:
Table 7.1: List of the WebParts Controls
Controls Description
WebPartManager Manages all the WebParts controls of a Web page. It has no user interface (UI),
and it is invisible at runtime.
ProxyWebPartManager Allows developers to specify static connections in a content page when the
WebPartManager control has been specified in the master page.
ASP.NET 4.5 in Simple Steps

Table 7.1: List of the WebParts Controls


Controls Description
WebPartZone Describes a region for the WebParts controls that can be relocated, maximized,
or minimized according to the requirements specified by the end-user. A page
can contain one or more WebPartZone controls.
CatalogZone Creates a catalog of the WebParts controls.
ImportCatalogPart Imports the description file for a WebParts control (or any other ASP.NET server
control that is used as a WebParts control), so that the control can be added to a
Web page with pre assigned settings to a specified zone.
DeclarativeCatalogPart Allows end-users to modify the functionality of a Web page.
PageCatalogPart Restores the deleted WebParts controls on a Web page. It is the only means of
restoring the deleted WebParts controls.
EditorZone Edits the appearance, format, and structure of the WebParts controls on Web
pages. It is the primary control used for editing.
LayoutEditorPart Allows you to change the layout-oriented properties (such as state and title) for the
linked WebParts controls. This control is visible when a WebParts page is in edit mode.
AppearanceEditorPart Allows you to edit or change the characteristics of the WebParts controls
displayed on a Web page.
PropertyGridEditorPart Allows the end-users to edit the custom properties of a WebParts control.
BehaviorEditorPart Enables end-users to modify the behavior properties of the WebParts controls.
ConnectionsZone Allows the WebParts controls to connect dynamically (at runtime) to each other.

Now, let’s discuss some of the most important and commonly used WebParts controls in detail.

The WebPartManager Control


The WebPartManage er control is a control that manages all other WebParts controls on the Web page.
The WebPartManage er control resides within the System.Web.UI.WebControls.WebParts
namespace. If you create a Web page by using WebParts controls, then you need to ensure that the
Web page contains a WebPartManage er control before placing any other WebParts control on the Web
page.
The WebPartManage
er control performs the following tasks to control the functionality of the Web page:
 Tracks the controls that provide WebParts features to the Web page, including the WebPartZon
ne
control and the ConnectionsZone e control.
 Provides methods to insert and remove different types of WebParts controls on a Web page.
 Establishes, monitors, and manages connections among different types of controls.
 Enables you to drag controls to different locations on a Web page to customize its appearance.
 Provides various views that you can use to change and personalize the properties and behavior
of the controls.

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

Table 7.3: Public Methods of the WebPartManager Class


Methods Description
WebPartZoneBase zone to another zone or to a new location within the
same zone
Table 7.4 lists the noteworthy public events of the WebPartManager class:
Table 7.4: Public Events of the WebPartManager Class
Event Description
DisplayModeChanged Occurs when the current display mode of a Web page is changed.
DisplayModeChanging Occurs after a user clicks a verb on a Web page that begins the process of
changing the display mode.
SelectedWebPartChanged Occurs when the currently selected Web control changes.
SelectedWebPartChanging Occurs during the process of changing the current selection to other
WebParts or server control.
WebPartAdded Occurs when a dynamic WebParts or server control is added to a
WebPartZoneBase zone. This event indicates that the control has been
added successfully.
WebPartAdding Occurs when a dynamic WebParts or other server control is added to a
WebPartZoneBase zone.
WebPartClosed Occurs when a WebParts control is removed from a Web page.
WebPartClosing Occurs during the process of deleting a WebParts control from a Web page.
WebPartDeleted Occurs after a WebParts or other server control has been deleted from a
WebPartZoneBase zone.
WebPartDeleting Occurs while permanently deleting an instance of a dynamic WebPart from
a WebPartZoneBase zone.
WebPartMoved Occurs when the location of a WebParts or server control on a Web page is
changed.
WebPartMoving Occurs when a WebParts or server control contained in the WebPartZoneBase
zone is moved in its own zone or another zone in a Web page.
WebPartsConnected Occurs after a connection between the WebParts controls has been
established.
WebPartsConnecting Occurs during the process of establishing a connection between the
WebParts controls placed in a WebPartZoneBase zone.
WebPartsDisconnected Occurs during the termination of the connection between two WebParts or
server controls.
WebPartsDisconnecting Occurs during the process of terminating the connection between previously
connected WebParts or server controls.

208
WebParts Controls

Fig.ASP-7.1 shows the WebPartManage


er control in the Design view:

 Fig.ASP-7.1

The CatalogZone Control


The CatalogZon
ne control is a control that provides a catalog on the Web page from where an end-user
makes a choice. It makes Web Sites more personalized so that the end-users are able to manage the
WebPartss controls in a more structured manner. The CatalogZon ne control resides within
theSystem.Web.UI.WebControls. WebParts namespace.
Table 7.5 lists the noteworthy public property of the CatalogZone class:
Table 7.5: Public Property of the CatalogZone Class
Property Description
SelectedCatalogPartID Retrieves or initializes a string to identify the currently selected
CatalogPart control in a zone
SelectedPartLinkStyle Retrieves an object that contains style attributes for the currently selected
CatalogPart control in a zone
SelectTargetZoneText Retrieves or sets the text next to a server control in the catalog UI. This
allows a user to select the zone for adding selected controls
ShowCatalogIcons Retrieves or sets a value to indicate whether server controls in a
CatalogZone control display their associated icons or not
EmptyZoneText Shows the text when the zone is empty
InstructionText Shows the instruction text in the zone

Table 7.6 lists the noteworthy events of the CatalogZone class:


Table 7.6: Public Events of the CatalogZone Class
Event Description
DataBinding Invokes when the server control binds to a data source
Disposed Invokes when the control has been disposed

Table 7.7 lists the noteworthy methods of the CatalogZone class:


Table 7.7: Public Methods of the CatalogZone Class
Method Description
CatalogPartChrome Creates the CatalogpartChrome object used to render the UI elements
of CatalogPart controls in a zone

209
ASP.NET 4.5 in Simple Steps

Table 7.7: Public Methods of the CatalogZone Class


Method Description
CatalogParts Create instances of all CatalogPart controls declares in a CatalogZone
control

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

The EditorZone Control


After designing a Web page, you may sometimes feel the need to modify its appearance, such as its color or
style. For this purpose, you can use the EditorZone e control, which is one of the primary controls used for
editing. The EditorZon ne control resides within the System.Web.UI.WebControls.WebParts
namespace. It is used for editing the appearance, format, and structure of the WebParts pages. You can also
use an EditorZon ne control to change the behavior and content of the WebPartts controls. The EditorZon ne
control contains various EditorParrt controls, such as AppearanceEditorParrt and BehaviorEditorPart controlls,
which are used to customize the WebPartts pages.
Table 7.8 lists the public properties of the EditorZone class:
Table7.8: Public Properties of the EditorZone Class
Property Description
Instruction Text Shows the instructional text in the zone
EmptyZoneText Retrieves or sets the message text, which appears when a zone is empty
and has no controls
ErrorText Retrieves or sets the text that displays an error message in the editing UI
HeaderText Sets the text for the header area of a zone

Table 7.9 lists the public events of the EditorZone class:


Table 7.9: Public Events of the EditorZone Class
Event Description
DataBinding Invokes when the control’s data binding expressions are to be evaluated
Disposed Invokes when the control has been disposed

Fig.ASP-7.3 shows the EditorZone control in the Design view:

 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.

The LayoutEditorPart Control


The LayoutEditorPart control is a control that allows you to edit the properties of a WebParts control,
which, in turn, affects the layout of the Web Part. The LayoutEditorPart control is visible only when

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

The AppearanceEditorPart Control


The AppearanceEditorPart control is a control that edits or changes the characteristics of the WebParts
displayed on a Web page. This control allows the end users to edit the properties, which in turn, affects
the appearance of the linked WebParts controls on a Web page. The AppearanceEditorPart
control is to be added to an EditorZone zone, and is displayed only when a WebParts control is selected
for editing. Some of the options displayed on the AppearanceEditorPart control are as follows:
 Titlle: Enables you to retrieve or specify a string value, which appears as a title of a control
 Heigh ht: Enables you to retrieve or specify the height of a control
 Widtth: Enables you to retrieve or specify the width of a control
 Chrome typ pe: Enables you to select the type of title border option by using the DropDownList
control
 Directio on: Enables you to select the direction of content flow on a WebParts page by using the
DropDownList control
 Hidde en: Enables you to hide or unhide a control by using the CheckBox control
The AppearanceEditorPart control that is added inside the EditorZone control in the Designer
window is shown in Fig.ASP-7.5:

212
WebParts Controls

 Fig.ASP-7.5

The PropertyGridEditorPart Control


The PropertyGridEditorPart control is a control providing a UI that allows users to edit the custom
properties of a WebParts control on a Web page. This control needs to be added to an EditorZone
control on a Web page. The PropertyGridEditorPart control is visible only when the Web page is
in the edit mode or if the user selects a WebParts control for editing.
The PropertyGridEditorZone control is added inside the EditorZone control, as shown in Fig.ASP-7.6:

 Fig.ASP-7.6

The BehaviorEditorPart Control


The BehaviorEditorPart control is a control that enables users to modify the properties of a WebParts
control that affect the behavior of the control. The BehaviorEditorPart control remains hidden, but
is visible when a WebParts page is in the edit mode. As with other EditorPart controls, the
BehaviorEditorPart control is also contained in an EditorZone control.
The BehaviorEditorPart control provides several options used for editing the behavior of any Web
Part control. The options provided by the BehaviorEditorPart control are as follows:
 Descriptioon: Enables you to retrieve or specify the functionality of a WebParts control in brief
 Title Lin
nk: Enables you to retrieve or specify the link of a WebParts control for providing details
about the control

213
ASP.NET 4.5 in Simple Steps

 Title Icon Image Lin


nk: Enables you to retrieve or specify an image, which appears in the title bar
of a WebParts control
 Catalog Icon Image Lin nk: Enables you to retrieve or specify an image, which appears in a
catalog of a WebParts control
 Help Lin
nk: Enables you to retrieve or specify the link of the Help file of a WebParts control
 Help Mod de: Enables you to retrieve or specify the mode of UI to display the Help file of a
WebParts control
 Import Error Messagge: Enables you to retrieve or specify the error message, which appears when
you face an error while importing a WebParts control from a Web site
 Export Mod
de: Enables you to export the properties of a WebParts control to the Web site
 Authorization Filte
er: Enables you to retrieve or specify a string value to determine whether a Web
Part control is authorized to be added to a Web page
 Allow Closse: Enables you to retrieve or specify a value, which allows you to close a WebParts
control on a Web page
 Allow Connecct: Enables you to retrieve or specify a value to enable connection with other controls
 Allow Ediit: Enables you to retrieve or specify a value, which allows you to modify a WebParts
control on a Web page
 Allow Hid
de: Enables you to retrieve or specify a value, which allows you to hide a Web Parts
control
 Allow Minimizze: Enables you to retrieve or specify a value, which allows you to minimize a
WebParts control
 Allow Zone Chang ge: Enables you to retrieve or specify a value indicating whether a WebParts
control can be moved from one zone to another
The BehaviorEditorPart control is added inside the EditorZone control, as shown in Fig.ASP-7.7:

 Fig.ASP-7.7

214
WebParts Controls

The WebPartZone Control


The WebPartZonne control is a control that is used to describe a region on a WebParts page for placing
the WebParts or other controls, such as Labe el, Textboxx, and Image controls.. Once placed, the controls
can be relocated, maximized, or minimized according to the requirements of the end-user. The
WebPartZonee control resides within the System.Web.UI.WebControls.WebParts namespace.
Table 7.10 lists the public properties of the WebPartZon
ne class:
Table 7.10: Public Properties of the WebPartZone Class
Properties Description
LayoutOrientation Determines whether or not the controls in a WebPartZone control are
aligned vertically or horizontally.
RestoreWebPart Restores a selected minimized WebParts control to the normal state.
AllowLayoutChange Determines whether or not the layout of a WebParts control can be
modified. This property also allows you to specify a layout for the
WebParts control.
EditVerb Obtains a reference to the WebPartVerb class object to change a
WebParts control into the WebPartsZone control.
ExportVerb Obtains a reference to the WebPartVerb class object to export an XML
definition for a WebParts control.

Table 7.11 lists the public methods of the WebPartZon


ne class:
Table 7.11: Public Methods of the WebPartZone Class
Methods Description
CatalogPartChrome Creates the CatalogpartChrome object used to render the UI elements
of Catalogpart controls in a zone
RestoreWebPart Restores a selected minimized WebParts control to the normal state

Table 7.12 lists the public events of the WebPartZon


ne class:
Table 7.12: Public Events of the WebPartZone Class
Events Description
CreateVerbs Initiates when the verbs are created for a zone derived from the
WebPartZone base class

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

The ConnectionsZone Control


The ConnectionsZon ne control is a control that allows you to connect the WebPartts controls dynamically to
each other. The ConnectionsZone e control resides within the System.Web.UI.WebControls.WebParts
namespace. The ConnectionsZone e control provides with a user interface for making connections with the
WebPartts controls that are enabled for such type of dynamic connection.
Table 7.13 lists the public properties of the ConnectionsZon ne class:
Table 7.13: Public Properties of the ConnectionsZone Class
Properties Description
ConfigureConnectionTitle Gets or sets the title text of a connection UI created by a
ConnectionsZone control.
ConfigureVerb Gets a reference to a WebPartVerb object. You can use this
reference to open the configuration view in a connection UI.
ConnectToConsumerText Gets or sets the hyperlink text that the user can click to select
a consumer control for a connection.
ConnectToConsumerTitle Gets or sets the title text of a section in a connection UI where
users select the consumer control to connect with other
WebParts.
ConnectVerb Gets a reference to a WebPartsVerb object to allow two
WebParts controls to connect with others WebParts.
GetText Gets or sets the text present before the name of consumer in
the connection UI. This consumer retrieves the data from the
provider.
CancelVerb Retrieves a reference to a WebPartsVerb object that enables
the user to cancel the process of establishing the connection.
CloseVerb Retrieves a reference to a WebPartsVerb object that enables
the user to close the connection UI.
DisconnectVerb Gets a reference to a WebPartsVerb object that enables the
user to disconnect two connected WebPart controls.
ProvidersInstructionText Gets or sets the instruction text contained in the providers
section of a connection UI, when a connection already exists.
SendText Gets or sets the text present before the name of the provider
in the connection UI. This provider sends data to the
consumer.
Providers title Gets or sets the title text contained in the providers section of
a connection UI when a connection already exists,
SendToText Gets or sets the text present in the connection UI before the
name of the consumer to which a provider will send data,

216
WebParts Controls

Table 7.14 lists the public events of the ConnectionsZon


ne class:
Table 7.14: Public Events of the ConnectionsZone Class
Events Description
DataBinding Invokes when the control’s data binding expressions are to be
evaluated
Disposed Invokes when the control has been disposed

Table 7.15 lists the public methods of the ConnectionsZon


ne class:
Table 7.15: Public Methods of the ConnectionsZone Class
Methods Description
ApplyStyle Applies the specified style to the style elements of a WebParts control
RenderBeginTag Provides the beginning tag for a Panel control to add a panel on
which server controls can be added
RenderEndTag Provides the ending tag for a Panel control indicating the end of the
panel

Fig.ASP-7.9 shows the ConnectionsZone


e control in the Design view:

 Fig.ASP-7.9

The PageCatalogPart Control


The PageCatalogPartt control is used with the CatalogZone e control to allow users to restore previously
deleted WebPartts controls of a Web page. This is the only way to restore the deleted WebPartts control
on a Web form. The PageCatalogPart control resides within the System.Web.UI.WebControls.WebPartts
namespace. The PageCatalogParrt control adds a list of check boxes to the CatalogZon ne control
corresponding to each deleted WebPartts control. To restore these controls on the Web page, the users
simply need to select the required check box and a WebPart zone, where the WebParts control is to be
added, and click the Add button.

217
ASP.NET 4.5 in Simple Steps

Table 7.16 lists the properties of the PageCatalogPart class:


Table 7.16: Public Properties of the PageCatalogPart Class
Property Description
Backcolor Specifies or determines the background color of a WebParts control
ChromeType Determines or specifies the border of a WebParts control
ChromeState Determines whether a WebParts control is in minimized or normal state
ClientIDMode Indicates how the ClientID should be generated for the control
HasAttributes Determines whether a WebParts control has attributes set or not

Table 7.17 lists the events of the PageCatalogPart class:


Table 7.17: Public Events of the PageCatalogPart Class
Events Description
DataBinding Invokes when the control’s data binding expressions are to be
evaluated
Disposed Invokes when the control has been disposed
Focus Sets the focus on the control

Table 7.18 lists the methods of the PageCatalogPart class:


Table 7.18: Public Methods of the PageCatalogPart Class
Methods Description
ApplyStyle Applies the specified style to the style elements of a WebParts control
GetAvailableWebpartsDescripti Provides details of a WebPart control that are included in the catalog
ons displayed on a Web Page
RenderBeginTag Provides the beginning tag for a Panel control to add a panel on which
server controls can be added
RenderEndTag Provides the ending tag for a Panel control indicating the end of the
panel
GetWebPart Provides a reference to a WebParts control based on the description
passed to the GetWebPart method
MergeStyle Adds the style elements passed as parameter to a WebParts control

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

Creating a Simple WebParts Page


To understand the concept of personalizing the WebPartts controls on a Web form. Let’s create a Web
application by performing the following steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012.
2. Select FILENewProject option from the menu bar.
The New Project dialog box appears.
Templates
3. Select Installed Visual C#Web option in the left pane of the New Project dialog
box.
4.. Select the ASP.NET Empty Web Application templates in the middle pane of the New Project
dialog box.
5. Enter Webpartscontrol in the Name 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 Webpartscontrol application is created.
8. Open the Solution Explorer window and right-click the application name. In our case, we are
right-clicking the Webpartscontrol application.
9. Select AddNew Item from the context menu.
The Add New Item – Webpartscontrol dialog box appears.
10. Select the Web Form option from the middle pane.
11. Click the Add button. The WebForm1.aspx form is added to the Webpartscontrol application.
12. Drag and drop the WebPartManager control from the Toolbox on the Web Form.
13. Drag and drop two LinkButton controls from the Standard tab of the Toolbox on the Web Form.
14. Open the Properties window and set the Text property of LinkButton1 control as Catalog and
LinkButton2 control as Edit (Fig.ASP-7.11).
15. Drag and drop two WebpartZone controls on the Web Form (Fig.ASP-7.11).
16. Add a Calendar control in the WebpartZone1 control and a LinkButton control in the
WebpartZone2 control (Fig.ASP-7.11).
17. Add the CatalogZone control to the Web Form, and then, add the PageCatalogPart control in the
CatalogZone control (Fig.ASP-7.11).
18. Add the EditorZone control to the Web Form, and then, add the LayoutEditorPart and
AppearanceEditorPart controls in the EditorZone control, as shown in Fig.ASP-7.11:

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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<br />
<asp:LinkButton ID="LinkButton1" runat="server">Catalog</asp:LinkButton>
&nbsp;&nbsp;&nbsp;&nbsp;
<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

<asp:PageCatalogPart ID="PageCatalogPart1" runat="server" /> </ZoneTemplate>


</asp:CatalogZone>
<asp:EditorZone ID="EditorZone1" runat="server"><ZoneTemplate>
<asp:AppearanceEditorPart ID="AppearanceEditorPart1" runat="server" />
<asp:LayoutEditorPart ID="LayoutEditorPart1" runat="server" /> </ZoneTemplate>
</asp:EditorZone>
</div>
</form>
</body>
</html>
9. Double-click the WebForm
19 m1 control in the Desig
gn mode and add the namespace, that is, using
System.Web.UI.WebControls.WebParts, in the WebForm1.aspx.ccs form.
0. Double-click the Catalog Lin
20 nk button in the Desig
gn mode and add the following code snippet in
the Click event:
protected void LinkButton1_Click(object sender, EventArgs e)
{
WebPartManager1.DisplayMode = WebPartManager.CatalogDisplayMode;
}
1. Double-click the Edit Link button in the Design mode and add the following code snippet:
21
protected void LinkButton2_Click(object sender, EventArgs e)
{
WebPartManager1.DisplayMode = WebPartManager.EditDisplayMode;
}
2. Press the F5 key to execute the application (Fig.ASP-7.12).
22
3. Click the Ediit link on the Web page, as shown in Fig.ASP-7.12:
23

23

 Fig.ASP-7.12

4. Drag the LinkButto


24 on control from the WebPartZone e2 control toward the WebPartZone
e1 control
and drop in the WebPartZonne control (Fig.ASP-7.13).
The WebPartZone e2 control becomes empty and displays the Add a Web Part to this zone by
dropping it here messag
ge, as shown in Fig.ASP-7.13:

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

7. Click the Catalo


27 og link (Fig.ASP-7.15).

27

 Fig.ASP-7.15

The Catalog zone appears, as shown in Fig.ASP-7.16:


28. Select the Untitle
ed checkbox in the Page Catalo
og pane (Fig.ASP-7.16).
29. Select the WebPartZone e2 control from the Add to drop-down list (Fig.ASP-7.16).
30. Click the Add button, as shown in Fig.ASP-7.16:

28

30
29

 Fig.ASP-7.16

223
ASP.NET 4.5 in Simple Steps

The WebPartZone2 control displays the LinkButton n control (Fig.ASP-7.17).


1. Click the Closse link to close the Catalog zon
31 ne, as shown in Fig.ASP-7.17:

31

 Fig.ASP-7.17

The Web form now appears (Fig.ASP-7.18).


2. Click the Ediit link, as shown in Fig.ASP-7.18:
32

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

The Editor Zon


ne appears on the screen (Fig.ASP-7.20).
35. Enter The Calendar controll in Titlle textbox in the Appearance
e pane (Fig.ASP-7.20).
36. Click the OK button to set title on the Calenda
ar control, as shown in Fig.ASP-7.20:

35

36

 Fig.ASP-7.20

225
ASP.NET 4.5 in Simple Steps

The title appears in the WebPartZone1 control, as shown in Fig.ASP-7.21:

 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

What you will learn in this chapter?


 C onne cte d D a ta A cce ss
 A D O .N E T
 T he S Q LD a ta S ource C ontrol
 T he O bje ctD a ta S ource C ontrol
 T he X mlD a ta S ource C ontrol
 T he LinqD a ta S ourc e C ontrol
 T he A cce ssD a ta S ource C ontrol
 Introduction to D a ta -B ound C ontrols

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

Connected Data Access


This model is the only way to access the data from the database earlier in the Web applications. In this
model, you have to manage the open connection with database. This model requires continuous open
connection with the database to fetch the data. The various database operations such as select, delete,
update, and insert can be performed on the database only when there is an open connection with the
database. After performing the operations on the database, the users have to close the connection
explicitly. The various objects of this model are SQLConnection, OleDbconnection, SQLDataReader,
and OledbDataReader.
However, in a Web application that hosts multiple Web users simultaneously, maintaining a continuous
link to a database quickly consumes all the system resources. A large number of open connections also
reduce the efficiency and decrease the system performance. An application that maintains connections
very efficiently with 10 clients becomes significantly slow when it has to support 20 clients, and finally
becomes unusable (redundant) with 80 clients. ADO.NET addresses this issue with its unique
disconnected data access model.

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.

Disconnected Data Architecture


In most cases, accessing data from a database requires connection with the database. Working with
databases through .NET applications requires a constant connection with the database servers.
Accessing a Web application by multiple users at the same time increases load on the Web server.
Using connected data architecture in applications affects the performance of applications.
The .NET development environment reads the database objects, such as tables, views, relations, and
data types, into the ASP.NET application’s memory. The .NET application processes data in a detached
(disconnected) mode with the databases. The live connection is established only when the user
transaction has to finally write the modified data or new data to a database.
The .NET Framework creates a data layer known as ADO.NET data layer, which contains all the
physical data storage services.
Various operations that are performed on the databases by the services offered by this layer are as follows:

228
Database Controls

 Connecting to a database or an Extensible Markup Language (XML) file.


 Querying the database by using SQL for filling the filtered data in the virtual memory of the Web
application; for example, selecting salaries of all the employees whose age is greater than 50
years. This involves the use of Data Manipulation Language, which uses the Select query.
 Making changes in the database table(s) as a result of processing the retrieved data in the code;
for example, calculating annual salary, increasing salary by some percent, and modifying the
salary.
 Inserting new data and performing delete operations; for example, adding records for new
employees and deleting the records for retired employees.
The tasks involved in the second and third points are accomplished by ASP.NET applications in three
steps: reading the data from the database, modifying the data, and storing the modified data in the
database. Although the application processes the data or provides the output for viewing the data by the
users, there is no active connection with the database.
However, when the user wants to finally submit the data to a database or to make permanent changes
in a database, a live connection is established until the changes are committed to the database.

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.

The SQLDataSource Control


The SqlDataSource control is used to establish a connection with a database,, such as SQL server.
This data source control loads the provider for SQL server. The wizard launched by this control helps the
users to do the following:
 Creating provider-specific connection (SQL Connection) to the SQL server
 Building SQL query or use stored procedures
 Fetching the data from the SQL server database
In earlier versions of ASP.NET, this task was done through code, wherein all the values were passed to
provider-specific class constructors.
Table 8.1 lists some noteworthy public properties of the SqlDataSource class:

Table 8.1: Noteworthy Public Properties of the SqlDataSource Class


Propertie
es Description
n
ConnectionString Obtains or specifies the connection string parameters into the Connection class
constructor. This string contains the database name, server name, initial catalog,
user ID, and password.
SelectCommand Obtains or specifies the query string for retrieving the records from the SQL
database.
InsertCommand Obtains or specifies the string containing the Insert SQL query for inserting the data
into an SQL server database.

Table 8.2 lists some noteworthy public methods of the SqlDataSource class:

230
Database Controls

Table 8.2: Noteworthy Public Methods of the SQLDataSource Class


Method
ds Description
n
Databind Binds an SQL data source to the SQL server data source control
Select Retrieves the records or data from an SQL server database
Insert Inserts the records or data into an SQL server database

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

The Configure Data Sourcce dialog box appears (Fig.ASP-8.2).


4. Click the New Connectio
14 on button in the dialog box, as shown in Fig.ASP-8.2:

14

 Fig.ASP-8.2

The Add Connectio on dialog box appears.


5. Select the server name from the Server name drop-down list.
15
6. Select the Use Windows Authentication radio button from the Log on to the server group.
16
7. Select the Northwin
17 nd database option from the Select or enter database nam
me drop-down list in
the Connect to a databasse group.
8. Click the Tesst Connection button.
18
The Microsoft Visual Studiio message box appears (Fig.ASP-8.3).
19. Click the OK button to continue, as shown in Fig.ASP-8.3:

19

 Fig.ASP-8.3

0. Click the OK button in the Add Connectio


20 on dialog box, as shown in Fig.ASP-8.4:

232
Database Controls

20

 Fig.ASP-8.4

The Choose Your Data Connectio


on page of the Choose Data Sourcce dialog box appears
(Fig.ASP-8.5
5).
1. Click the Nexxt button, as shown in Fig.ASP-8.5
21 5:

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. Click the Finissh button, as shown in Fig.ASP-8.8:

27

 Fig.ASP-8.8

28. Click the smart tag of the GridView


w control (Fig.ASP-8.9):
The GridView Taskks appears (Fig.ASP-8.9).
29. Select the SQLDataSource e1 option from the Choose Data Sourcce drop-down list in the GridView
Taskks, as shown in Fig.ASP-8.9:

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>

0. Press the F5 key to execute the Web site (Fig.ASP-8.10):


30

 Fig.ASP-8.10

The ObjectDataSource Control


The ObjectDataSourcce control is used to configure an Object Data provider layer to retrieve data from
business objects. Business objects are logical independent components, such as classes, modules, Web
components, and .NET components, which process the data and return the customized or encapsulated
data objects. For example, a class to select color can have functions to check the user ID and return
colors according to the user’s preferences stored in an XML file or a database. The ObjectDataSourcce
control resides within the System.Web.UI.WebControls namespace.
Table 8.3 lists some noteworthy public properties of the ObjectDataSource class:

236
Database Controls

Table 8.3: Noteworthy Public Properties of the ObjectDataSource Class


Propertie
es Description
n
EnableCaching Enables the caching of ObjectDataSource control in the application
InsertParameters Obtains the collection of parameters that will be used by the InsertMethod property
SelectParameters Obtains the collection of parameters that will be used by the SelectMethod property

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

9. Right-click the Web site name in the Solution Explore


er window (Fig.ASP-8.12).
0. Select the Add Add ASP.NET Folde
10 er option from the context menu (Fig.ASP-8.12).
1. Select the App_Cod
11 de option, as shown in Fig.ASP-8.12:

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. Select the BUILDBuild Web Site optio


on from the menu bar, as shown in Fig.ASP-8.14:

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

The Choose a Business Objecct page of the Configure Data Source


e dialog box appears
(Fig.ASP-8.16).
9. Select business object as Classs1 from the Choose your businesss objects drop-down list and click
19
the Nexxt button, as shown in Fig.ASP-8.16:

19

 Fig.ASP.8.16

The Define Data Method


ds page appears (Fig.ASP-8.17).

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

2. Click the smart tag of the GridVie


22 ew control and select the data source as ObjectDataSource
e1
from the Choose Data Sourcce drop-down list, as shown in Fig.ASP-8.18:

 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

The XmlDataSource Control


The XmlDataSourcce control is a control used to configure XML files as data sources. XML files are
structured documents in which the XML schemas define the data layout and structure of the document.
To perform its tasks, this control utilizes the functions contained in the classes belonging to the
System.Data.Xml and System.Data.XmlSchema namespaces.
The XmlDataSourcce control provides a wizard to configure XML files into your application. The wizard
provides the option to specify the XML data a file as the data source for the XmlDataSourcce control. A user
of this control can optionally specify additional files that are used to modify the XML files before they are
used by the XmlDataSourcce control.
Table 8.5 lists some noteworthy properties of the XmlDataSource class:
Table 8.5: Noteworthy Properties of the XmlDataSource Class
Propertty Description
n
Data Obtains or specifies the block of XML data
TransformFile Specifies the style sheet (XSLT) transformation for the referenced XML file
XPath Defines the XPath expression for the XML file

Table 8.6 lists some noteworthy methods of the XmlDataSource class:


Table.-8.6: Noteworthy Methods of the XmlDataSource Class
Method
ds Description
n
DataBind Binds a DataSource to the XmlDataSource control
GetXmlDocument Retrieves the specified XML document to be loaded as data source
ToString Returns a string representation of an object

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

12. Add the following code snippet in the XmlFile.xml file:


<Student>
<student Name="John" RollNo="A001" Standard="X"/>
<student Name="David" RollNo="A002" Standard="XI"/>
<student Name="Lisa" RollNo="A003" Standard="XII"/>
</Student>

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

The Configure Data Sourcce dialog box opens.


14. Click the Browsse button.
The Select XML Filee dialog box appears.
15. Select the XmlFile.xml file from the Contents of folder pane.
16.. Click the OK button.
The Data file text box now contains the name of the Xml file in the Configure Data Sourcce dialog box.
17. Click the OK button in the Configure Data Source dialog box.
ew control, and select the data source
18.. Open the Web Form and click the smart tag of the GridVie
as XmlDataSource
e1 from the Choose Data Sourcce drop-down list, as shown in Fig.ASP-8.22:

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

8. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.23:


18

 Fig.ASP-8.23

Now, let’s discuss the LinqDataSourcce control in the next section.

The LinqDataSource Control


The LinqDataSource control is a data source control that allows a Web server control to access data
located in relational databases or in the memory data collection, such as an array and context objects.
This control enables Web developers to use language-integrated query (LLIN NQ), which simplifies the
interaction between object-oriented programming and relational data by applying the principles of
object-oriented programming to relational data. This control also provides the capability to connect to
data from either a database or an in-memory collection, such as an array. This control enables a user
to handle operations, such as insert and delete, without using SQL commands.
Table 8.7 lists the noteworthy properties of the LinqDataSource class:
Table 8.7: Noteworthy Properties of the LinqDataSource Class
Propertty Description
n
Select Obtains or sets the properties and calculated values that are included
in the retrieved data
SelectParameters Obtains the collection of parameters that are used during a data-
retrieval operation
StoreOriginalValuesInViewState Specifies whether or not the data from the data source should be
stored in view state to make sure that the data has not been changed
by another process before it has been updated or deleted
TableName Obtains or sets the name of the property or field in the data context
object that represents a data collection
UpdateParameters Obtains the collection of parameters that are used during an update
operation
Where Obtains or sets a value that specifies what conditions must be true for a
record to be included in the retrieved data
WhereParameters Obtains the collection of parameters that is used to create the Where
clause

Table 8.8 lists the noteworthy methods of the LinqDataSource class:

244
Database Controls

Table 8.8: Noteworthy Methods of the LinqDataSource Class


Method
ds Description
n
Delete Deletes data from the database
Insert Inserts data in the database
Update Updates data in the database

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

The Add Connection dialog box appears.


12. Add the Northwind database from the Add Connection dialog box, similar to how you have done
in the Sqldatasourcecontrol application.
The deboleena-pc.Northwind.dbo database appears in the Server Explorer window, as shown in
Fig.ASP-8.25:

245
ASP.NET 4.5 in Simple Steps

 Fig.ASP-8.25

13. Open the Solution Explore


er window and right-click the name of the application.
14. Select the AddAdd New Ite
em option from the context menu. The Add New Ite
em dialog box
appears.
Visual C# from the left pane and LINQ to SQL Classes from the middle pane of
15. Select Installed
the Add New Item dialog box (Fig.ASP-8.26).
16. Click the Add button, as shown in Fig.ASP-8.26:

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

18. Open the Server Exploreer window (Fig.ASP-8.28).


19. Drag and drop the Productts table from the Server Explore
er window on the design surface of the
DataClasses.dbm
ml file, as shown in Fig.ASP-8.28:

 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

The Configure Data Sourcce dialog box appears (Fig.ASP-8.30).


21. Select check box beside the Show onlly DataContexxt objectts option (Fig.ASP-8.30).

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

Now, let’s discuss the AccessDataSource


e control in the next section.

The AccessDataSource Control


The AccessDataSource control is a data source control that allows a Web server control to access a
Microsoft (MS) Access database. This control does not support connection strings, but the DataFile
property of this control allows you to specify the Access file (.mdb file) that you want to use to
access the data. When you add an AccessDataSource control to your ASP.NET page, the following
line of code appears in the HTML page:
<asp:AccessDataSource ID="AccessDataSource1" runat="server">
</asp:AccessDataSource>
The AccessDataSource control does not allow you to provide username and password to access the
data. If you need to use a password-protected database, then select the SqlDataSource control to
access the database.
Table 8.9 lists the noteworthy properties of the AccessDataSource class:
Table 8.9: Noteworthy Properties of the AccessDataSource Class
Propertty Descriptio
on
ConnectionString Obtains the connection string that is used to connect to the Microsoft Access
database
DataFile Obtains or specifies the location of the Microsoft Access .mdb file
ProviderName Obtains the name of the .NET data provider that the AccessDataSource
control uses to connect to a Microsoft Access database

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

It opens the Configure Data Sourcce dialog box (Fig.ASP-8.35).


4. Click the Browsse button, as shown in Fig.ASP-8.35:
14
5. Select the sttudent.accd
15 db file and click the OK button.
You can see the selected MS Access file in the Configure Data Sourcce wizard (Fig.ASP-8.35).
6. Click the Nexxt button, as shown in Fig.ASP-8.35:
16

251
ASP.NET 4.5 in Simple Steps

16

 Fig.ASP-8.35

7. Select the ID, StudName, Rollno


17 o, and Classs options in the Column
ns pane and click the Nexxt
button, as shown in Fig.ASP-8.36:

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

0. Click the smart tag of the GridVie


20 ew control and select the data source as AccessDataSource
e1
from the drop-down list beside the Choose Data Source optioon, as shown in Fig.ASP-8.38:

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

ReadOnly="True" SortExpression="ID" />


<asp:BoundField DataField="Studname" HeaderText="Studname"
SortExpression="Studname" />
<asp:BoundField DataField="Rollno" HeaderText="Rollno"
SortExpression="Rollno" />
<asp:BoundField DataField="Class" HeaderText="Class"
SortExpression="Class" />
</Columns>
</asp:GridView>
</div> <asp:AccessDataSource ID="AccessDataSource1" runat="server"

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

Introduction to Data-Bound Controls


Data-bound controls are controls that are used to bind with the data-source controls to display and modify
data in Web applications easily. Data-bound controls also enable you to customize the layout of the control
by using various templates provided in the control. Some Web server controls, such as the GridView,
FormView, DetailsView, TreeView, Repeater, and DataList controls, support complex data binding. Binding to
these data-bound controls is similar to complex binding, because a control displays multiple fields at once,
such as GridView, to display an entire table. Now, let‘s discuss some of the data-bound controls in detail.

The DataList Control


The DataListt control displays the data from a data source in the form of a list. This control supports
various templates to display grouped-up data in various layouts. These templates display the data with
visual clarity and ease of distinction.
The DataSourcce control is used to feed data to a DataLisst control. Therefore, to use a DataLisst control to
display data, you need to include a Datta Sourcce control in the Web form. The DataLisst control resides
within the System.Web.UI.WebControls namespace.
Table 8.10 lists noteworthy public properties of the DataList class:
Table 8.10: Noteworthy Public Properties of the DataList Class
Propertty Descriptio
on
AlternatingItemStyle Obtains or sets the style properties for alternating items in the DataList
control
AlternatingItemTemplate Obtains or sets the template for alternating items in the DataList control

254
Database Controls

Table 8.10: Noteworthy Public Properties of the DataList Class


Propertty Descriptio
on
EditItemIndex Obtains or sets the index number of the selected item in the DataList control to
edit
EditItemStyle Obtains or sets the style properties for the item selected for editing in the
DataList control
EditItemTemplate Obtains or sets the template for the item selected for editing in the DataList
control
FooterStyle Obtains the style properties for the footer section of the DataList control
FooterTemplate Obtains or sets the template for the footer section of the DataList control
Items Obtains a collection of the DataListItem objects representing the individual
items within the control
ItemStyle Obtains the style properties for the items in the DataList control
ItemTemplate Obtains or sets the template for the items in the DataList control
RepeatColumns Obtains or sets the number of columns to display in the DataList control
RepeatDirection Specifies whether the DataList control displays vertically or horizontally
RepeatLayout Specifies whether the control is displayed in a table or flow layout
SelectedIndex Obtains or sets the index of the selected item in the DataList control
SelectedItem Obtains the selected item in the DataList control
SelectedItemStyle Obtains the style properties for the selected item in the DataList control
SelectedItemTemplate Obtains or sets the template for the selected item in the DataList control
SelectedValue Obtains or sets the value of the key field for the selected data list item
SeparatorStyle Obtains or sets the style properties of the separator between each item in
the DataList control

Table 8.11 lists the public events of the DataList class:


Table 8.11: Noteworthy Public Events of the DataList Class
Even
nt Descriptio
on
CancelCommand Invokes when the Cancel button is clicked for an item in the DataList control
DeleteCommand Invokes when the Delete button is clicked for an item in the DataList control
EditCommand Invokes when the Edit button is clicked for an item in the DataList control
ItemCommand Invokes when any button is clicked in the DataList control
ItemCreated Invokes on the server when an item in the DataList control is created

255
ASP.NET 4.5 in Simple Steps

Table 8.11: Noteworthy Public Events of the DataList Class


Even
nt Descriptio
on
ItemDataBound Invokes when an item is data bound to the DataList control
UpdateCommand Invokes when the Update button is clicked for an item in the DataList control

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

The Auto Format dialog box opens (Fig.ASP-8.42).


12. Select the Colorful scheme from the Select a scheme pane (Fig.ASP-8.42).
13. Click the OK button, as shown in Fig.ASP-8.42:

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

<br /><br /> </ItemTemplate>


<SelectedItemStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" />
</asp:DataList></div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</form></body></html>
3. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.43:
13

 Fig.ASP-8.43

Let’s learn about the FormVie


ew control in the next section.

The FormView Control


The FormVie ew control displays only a single record in a table at a time retrieved from a data source.
Templates are used to display and edit the bound values in a FormVie ew control. When multiple records
are retrieved from the data source, paging is used to view all the records. The FormVie ew control
supports basic functions, such as editing, inserting, and deleting data records. The FormVieew control
resides within theSystem.Web.UI.WebControls namespace.
Table 8.12 lists some noteworthy public properties of the FormView class:
Table 8.12: Noteworthy Public Properties of the FormView Class
Propertty Description
DataKey Retrieves the DataKey object on which the control performs page-wise grouping
AllowPaging Accepts a Boolean value to enable or disable paging
BackColor Sets the background color for display

Table 8.13 lists some noteworthy public methods of the FormVie


ew class:

258
Database Controls

Table 8.13: Noteworthy Public Methods of the FormView Class


Metho
od Descriptio
on
RenderControl Renders the output of the Server control
ToString Provides a string representation of an current object into the FormView control
The FormView control is useful in situations where you need to display only one record at a time.
Let’s create an application to learn how to work with the FormVieew control by performing the following
steps:
1. Open Visual Studio 201
12.
2. Select FILENewWeb Sitte 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
Formviewcontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create Formviewcontrol Web site.
7. Add a Web Form to the Formviewcontrol Web site.
8. Drag and drop a FormView control and a SqlDataSource control from the Data tab of the
Toolbox on the Web Form, as shown in Fig.ASP-8.44:
9. Configure the SqlDataSource control to a Northwind database, similar to how you have done
earlier.
10. Click the smart tag of the FormView control and select the data source as SqlDataSource1 from
the Choose Data Source drop-down list in the FormView Tasks, as shown in Fig.ASP-8.44.
11. Open the Auto Format dialog box of the FormView control using smart tag.
12. Select the Brown Sugar scheme from the Select a scheme pane of the Auto Format dialog box
and click the OK button.
13. Click the smart tag and select the Enable Paging check box in the FormView Tasks of the
FormView control, as shown in Fig.ASP-8.44:

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" />
&nbsp;<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" />
&nbsp;<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

<asp:Label ID="ProductNameLabel" runat="server" Text='<%# Bind("ProductName") %>' />


<br /> UnitPrice:
<asp:Label ID="UnitPriceLabel" runat="server" Text='<%# Bind("UnitPrice") %>' />
<br /> UnitsInStock:
<asp:Label ID="UnitsInStockLabel" runat="server" Text='<%# Bind("UnitsInStock") %>' />
<br /> UnitsOnOrder:
<asp:Label ID="UnitsOnOrderLabel" runat="server" Text='<%# Bind("UnitsOnOrder") %>' />
<br /> </ItemTemplate>
<PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" />
<RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" />
</asp:FormView> </div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of products]">
</asp:SqlDataSource> </form></body></html>
3. Press the F5 key to execute the Web site. The output is shown in Fig.ASP-8.45.
13
You can notice that paging is enabled on the Web page. If you want to see the any record, just click the
numbers, as shown in Fig.ASP-8.45:

 Fig.ASP-8.45

Now, let’s know about the DetailsVie


ew control next.

The DetailsView Control


The DetailsView control is a data-bound control that is used to display a single record from the
associated data source in a table format, where each row of the table represents a field of the record.
This control uses the DataSourceID property to support two-way binding; consequently, it also
supports insert, update, and delete operations.
The DetailsView control exists within the System.Web.UI.WebControls namespace.
Table 8.14 lists the noteworthy properties of the DetailsView class:
Table 8.14: Noteworthy Properties of the DetailsView Class
Propertty Descriptio
on
AllowPaging Obtains or specifies a value indicating whether the paging feature is
AlternatingRowStyle Obtains or specifies a reference to the TableItemStyle object that allows you to
set the appearance of the alternating data rows in a DetailsView control.

261
ASP.NET 4.5 in Simple Steps

Table 8.14: Noteworthy Properties of the DetailsView Class


Propertty Descriptio
on
AlternatingRowStyle Obtains or specifies a reference to the TableItemStyle object that allows you to
set the appearance of the alternating data rows in a DetailsView control.
AutoGenerateInsertButton Obtains or specifies a value indicating whether the built-in controls to insert a
new record are displayed in a DetailsView control.
AutoGenerateRows Obtains or specifies a value indicating whether the row fields for each field in the
data source are automatically generated and displayed in a DetailsView control.
BackImageUrl Obtains or specifies the Uniform Resource Locator (URL) to an image to
display in the background of a DetailsView control.
BottomPagerRow Obtains a DetailsViewRow object that represents the bottom pager row in a
DetailsView control.
Caption Obtains or specifies the text to render in a Hypertext Markup Language
(HTML) caption element in a DetailsView control. This property is provided to
make the control more accessible to users of assistive technology devices.
CaptionAlign Obtains or specifies the horizontal or vertical position of the HTML caption
element in a DetailsView control. This property is provided to make the
control more accessible to users of assistive technology devices.
DataItem Obtains the data item bound to the DetailsView control.
DataItemCount Obtains the number of items in the underlying data source.
DataItemIndex Obtains the index of the item displayed in a DetailsView control from the
underlying data source.
DataKey Obtains a DataKey object that represents the primary key of the displayed
record.
DataKeyNames Obtains or sets an array that contains the names of the key fields for the data
source.
DefaultMode Obtains or sets the default data-entry mode of the DetailsView control.
EditRowStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the data rows when a DetailsView control is in edit mode.
EmptyDataRowStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the empty data row displayed when the data source bound to
a DetailsView control does not contain any records.
EmptyDataTemplate Obtains or sets the user-defined content for the empty data row rendered when a
DetailsView control is bound to a data source that does not contain any records.
EmptyDataText Obtains or sets the text to display in the empty data row rendered when a
DetailsView control is bound to a data source that does not contain any
records.

262
Database Controls

Table 8.14: Noteworthy Properties of the DetailsView Class


Propertty Descriptio
on
EnablePagingCallbacks Specifies whether or not client-side callback functions are used for paging
operations in the DetailsView control.
FieldHeaderStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the header column in a DetailsView control.
Fields Obtains a collection of the DataControlField objects that represent the
explicitly declared row fields in a DetailsView control.
FooterRow Obtains a DetailsViewRow object that represents the footer row in a
DetailsView control.
FooterStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the footer row in a DetailsView control.
FooterTemplate Obtains or sets the user-defined content for the footer row in a DetailsView
control.
FooterText Obtains or sets the text to display in the footer row of a DetailsView control.
GridLines Obtains or sets the gridline style for a DetailsView control.
HeaderRow Obtains a DetailsViewRow object that represents the header row in a
DetailsView control.
HeaderStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the header row in a DetailsView control.
HeaderTemplate Obtains or sets the user-defined content for the header row in a DetailsView
control.
HeaderText Obtains or sets the text to display in the header row of a DetailsView control.
HorizontalAlign Obtains or sets the horizontal alignment of a DetailsView control on the page.
InsertRowStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the data rows in a DetailsView control when the DetailsView
control is in insert mode.
PageCount Obtains the number of the records in the data source.
PageIndex Obtains or sets the index of the displayed record.
PagerSettings Obtains a reference to the PagerSettings object that allows you to set the
properties of the pager buttons in a DetailsView control.
PagerStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the pager row in a DetailsView control.
PagerTemplate Obtains or sets the custom content for the pager row in a DetailsView control.
Rows Obtains a collection of DetailsViewRow objects that represent the data rows in
a DetailsView control.

263
ASP.NET 4.5 in Simple Steps

Table 8.14: Noteworthy Properties of the DetailsView Class


Propertty Descriptio
on
RowStyle Obtains a reference to the TableItemStyle object that allows you to set the
appearance of the data rows in a DetailsView control.
SelectedValue Obtains the data key value of the current record in a DetailsView control.

Table 8.15 lists the noteworthy methods of the DetailsView class:


Table 8.15: Noteworthy Methods of the DetailsView Class
Metho
od Descriptio
on
ChangeMode Uses to switch the DetailsView control to the specified mode
DataBind Uses to bind data from the data source to the control
DeleteItem Uses to delete the current record from the data source
InsertItem Uses to inserts the current record in the data source
IsBindableType Specifies whether or not the specified data type can be bound to a field in the
DetailsView control
UpdateItem Updates the current record in the data source

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

0. Click the smart tag of the DetailsVie


10 ew control and select the data source as SqlDataSourcee1 from
the drop-down list beside the Choose Data a Source option in the DetailsView Taskks, as shown in
Fig.ASP-8.47:

10

 Fig.ASP-8.47

1. Click the Auto Forma


11 at option in the DetailsView Taskks of the DetailsVie
ew control. It opens the
Auto Forma at dialog box.
2. Select the Slatte scheme from the Select a schem
12 me pane and click the OK button.
3. Select the Enable Pagin
13 ng check box in the DetailsView Taskks smart tag of the DetailsView
w control.
Listing 8.8 shows the source code of the Default.aspx Web form after adding the controls and setting their
properties:
Listing 8.8
8: Code of the Default.aspx Web form of the Detailsviewcontrol 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:DetailsView ID="DetailsView1" runat="server" AllowPaging="True"
AutoGenerateRows="False" BackColor="White" BorderColor="#E7E7FF"
BorderStyle="None" BorderWidth="1px" CellPadding="3"
DataKeyNames="ProductID"
DataSourceID="SqlDataSource1" GridLines="Horizontal" Height="50px"
Width="125px">
<AlternatingRowStyle BackColor="#F7F7F7" />
<EditRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="#F7F7F7" />
<Fields>
<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"
SortExpression="UnitPrice" />
<asp:BoundField DataField="UnitsInStock" HeaderText="UnitsInStock"
SortExpression="UnitsInStock" />
<asp:BoundField DataField="UnitsOnOrder" HeaderText="UnitsOnOrder"
SortExpression="UnitsOnOrder" /> </Fields>
<FooterStyle BackColor="#B5C7DE" ForeColor="#4A3C8C" />
<HeaderStyle BackColor="#4A3C8C" Font-Bold="True" ForeColor="#F7F7F7" />
<PagerStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" HorizontalAlign="Right" />
<RowStyle BackColor="#E7E7FF" ForeColor="#4A3C8C" />
</asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice],
[UnitsInStock], [UnitsOnOrder] FROM [Alphabetical list of products]">
</asp:SqlDataSource> </div> </form></body></html>

265
ASP.NET 4.5 in Simple Steps

4. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.48:


14

 Fig.ASP-8.48

Now, let’s know about the ListVie


ew and DataPage
er controls.

The ListView and DataPager Controls


The ListView control is a data-bound control used to display data from the associated data source. It
enables a developer to display data in any format by using templates and styles. It also provides the
developer with the capability to control the rendered HTML output, and provides support for adding new
row and sorting.
Table 8.16 lists some noteworthy properties of the ListView class:
Table 8.16 : Noteworthy Properties of the ListView Class
Propertyy Description
n
EditItem Obtains the item that is in edit mode in a ListView control.
EditItemTemplate Obtains or sets the custom content for the item in edit mode.
EmptyDataTemplate Obtains or sets the user-defined content for the empty template that is rendered when
a ListView control is bound to a data source that does not contain any records.
EmptyItemTemplate Obtains or sets the user-defined content for the empty item that is rendered in a
ListView control when there are no more data items to display in the last row of the
current data page.
Font Sets the font of the text in the ListView control.
ForeColor Sets the foreground color of the ListView control.
GroupItemCount Obtains or sets the number of items to display per group in a ListView control.
GroupPlaceholderID Obtains or sets the ID for the group placeholder in a ListView control.
GroupSeparatorTem Obtains or sets the user-defined content for the separator between groups in a
plate ListView control.
GroupTemplate Obtains or sets the user-defined content for the group container in a ListView
control.
ItemTemplate Obtains or sets the custom content for the data item in a ListView control.
LayoutTemplate Obtains or sets the custom content for the root container in a ListView control.
SelectedDataKey Obtains the data-key value for the selected item in a ListView control.

266
Database Controls

Table 8.16 : Noteworthy Properties of the ListView Class


Propertyy Description
n
SortDirection Obtains the sort direction of the field or fields that are being sorted.
SortExpression Obtains the sort expression that is associated with the field or fields that are being
sorted.

Table 8.17 lists some noteworthy methods of the ListView class:


Table 8.17: Noteworthy Methods of the ListView Class
Method
ds Description
n
DeleteItem Allows you to delete the record at the specified index from the data source
ExtractItemValues Obtains the values of each field that is declared in the specified item, and stores
them in the specified IOrderedDictionary object
InsertNewItem Allows you to insert the current record in the data source
Sort Allows you to perform sorting on the ListView control, depending on the specified
sort expression and direction
UpdateItem Allows you to update the record at the specified index in the data source

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

Table 8.19 : Noteworthy Methods of the DataPager Class


Method
ds Description
n
RenderBeginTag Allows you to render the HTML opening tag of the DataPager control to the
specified writer
SetPageProperties Specifies the page-related properties in the DataPager control

Let’s create a Web application to learn how to use the ListVie


ew and DataPagerr controls to display a set
of records by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewWeb Sitte 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
Listviewanddatapagercontrol in the text box to specify the location and name of the Web site.
6. Click the OK button to create Listviewanddatapagercontrol Web site.
7. Drag and drop the SQLDataSource, ListView and DataPager control from the Data tab of the
Toolbox on the Web form (Fig.ASP-8.49).
Now, configure the SqlDataSource1 control to the Northwind database as you have done earlier.
8. Click the smart tag of the ListView control and select the data source as SqlDataSource1 option
from the Choose Data Source drop-down list in the ListView Tasks.
9. Click the Configure ListView option in the ListView Tasks of the ListView control, as shown in
Fig.ASP-8.49:

 Fig.ASP-8.49

The Configure ListView dialog box opens (Fig.ASP-8.50).


10. Select the Bulleted List scheme from the Select a Layout pane, and select Blues style from the
Select a style pane in the Configure ListView dialog box and click the OK button, as shown in
Fig.ASP-8.50:

268
Database Controls

10

 Fig.ASP-8.50

1. Click the smart tag of the DataPage


11 er control (Fig.ASP-8.51).
2. Select the Numeriic Page
12 er option from the drop-down list in the DataPage
er Tasks of the
DataPage er control, as shown in Fig.ASP-8.51:

12

 Fig.ASP-8.51

3. Open the Propertie


13 es window of the DataPage
er control and select the property PageControlIID to
ListView
w1, as shown in Fig.ASP-8.52:

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

<asp:SqlDataSource ID="SqlDataSource1" runat="server"


ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</form></body></html>
4. Press the F5 key to execute the Web site (Fig.ASP-8.53).
14
You can use paging of the Datapageer control to view the records of the ListVie
ew, as shown in Fig.ASP-8.53:

 Fig.ASP-8.53

The Repeater Control


The Repeater control is a data-bound control that is used to display repeated list of items from the
associated data source. The Repeater control does not provide support to inbuilt layout or styles.
Therefore, while working with the Repeater control, you have to explicitly declare all layouts,
formatting, and style. In other words, the Repeater control does not support built-in selection or
editing features. The Repeater control exists within the System.Web.UI.WebControls
namespace.
Table 8.20 lists some noteworthy properties of the Repeater class:
Table 8.20: Noteworthy Properties of the Repeater Class
Propertty Descriptio
on
AlternatingItemTemplate Obtains or sets the object implementing the System.Web.UI.ITemplate
interface that defines how alternating items in the control are displayed
Controls Obtains a System.Web.UI.ControlCollection class that contains the child
controls of the Repeater control
DataMember Obtains or sets the specific table in the DataSource to bind to the Repeater
control
DataSource Obtains or sets the data source that provides data for populating the list
DataSourceID Obtains or sets the ID property of the data source control that the Repeater
control should use to retrieve its data source

272
Database Controls

Table 8.20: Noteworthy Properties of the Repeater Class


Propertty Descriptio
on
EnableTheming Obtains or sets a value indicating whether the themes are applied to this
control
FooterTemplate Obtains or sets the System.Web.UI.ITemplate interface that defines how the
footer section of the Repeater control will be displayed

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

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


<div>
<table>
<asp:Repeater ID="Repeater1" runat="server" DataSourceID="SqlDataSource1">
<HeaderTemplate>
<tr style="background-color: Gray">
<th>AuthorId</th>
<th>LastName</th>
<th>FirstName</th>
<th>Phone</th>
<th>City</th>
</tr></HeaderTemplate><ItemTemplate>
<tr>
<td><%#DataBinder.Eval(Container, "DataItem.ProductID")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.ProductName")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.UnitPrice")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.UnitsInStock")%></td>
<td><%#DataBinder.Eval(Container, "DataItem.UnitsOnOrder")%></td>
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr>
<td style="background-color: Gray"><%#DataBinder.Eval(Container, "DataItem.ProductID")%>
</td> <td style="background-color: Gray">
<%#DataBinder.Eval(Container, "DataItem.ProductName")%></td>
<td style="background-color: Gray">
<%#DataBinder.Eval(Container, "DataItem.UnitPrice")%></td>
<td style="background-color: Gray">
<%#DataBinder.Eval(Container, "DataItem.UnitsInStock")%></td>
<td style="background-color: Gray">
<%#DataBinder.Eval(Container, "DataItem.UnitsOnOrder")%></td>
</tr> </AlternatingItemTemplate>
</asp:Repeater>
</table>
</div>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of products]">
</asp:SqlDataSource>
</form>
</body>
</html>
The Web Form now appears, as shown in Fig.ASP-8.55:

 Fig.ASP-8.55

3. Press the F5 key to execute the Web site, as shown in Fig.ASP-8.56:


13

274
Database Controls

 Fig.ASP-8.56

The Chart Control


ASP.NET 4.5 now includes a new control, that is, Chart control, in the Data tab. It contains various types
of chart such as point, column, bar, area, doughnut, range, and other types. The chart control is
capable of managing excessive data by using scale breaks, and also can be used in a three-
dimensional (3D) mode. It can be used like any other control present in the Data tab. This control
basically provides the efficient way to present data analysis on the Web Form. When you include the
Chart on the Web form, it adds the following code in the source view:
<asp:Chart ID="Chart1" runat="server">
<Series>
<asp:Series Name="Series1"></asp:Series>
</Series>
<ChartAreas><asp:ChartArea Name="ChartArea1"></asp:ChartArea>
</ChartAreas>
</asp:Chart>
Table 8.21 lists some noteworthy properties of the Chart class:
Table 8.21: Noteworthy Properties of the Chart Class
Propertty Descriptio
on
AlternateText Displays the alternate text when the chart mage is not shown
BackImage Gets or sets the background image path
BackImageAlignment Gets or sets the alignment of the background image
ClientIDMode Generates ClientID for the control
Compression Stores the compression value
DataSourceID Stores the ID of the data source that should be used with the control
ViewStateContent Saves the chart content
ViewStateMode Determines whether the viewstate is enabled for the chart control or not
Visible Decides whether the control should be visible or not

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

<body><form id="form1" runat="server"><div> <br />


<asp:Label ID="Label2" runat="server" Text="UNITS IN STOCK"
style="margin-left: 30px; text-align: center; z-index: 1; left: -45px; top:
136px; position: absolute; height: 18px; width: 221px;"></asp:Label>
<asp:Chart ID="Chart1" runat="server" DataSourceID="SqlDataSource1"
style="margin-left: 70px; z-index: 1; left: 145px; top: 22px; position:
relative; width: 314px; height: 294px;"><series><asp:Series Name="Series1"
XValueMember="UnitsOnOrder" YValueMembers="UnitsInStock"> </asp:Series>
</series>
<chartareas> <asp:ChartArea Name="ChartArea1"> </asp:ChartArea>
</chartareas> </asp:Chart>
</div><p> <asp:Label ID="Label1" runat="server" Text="UNITS ON ORDER"
style="width: 199px; z-index: 1; left: 323px; top: 368px; position:
absolute"></asp:Label> </p> <p>&nbsp;</p> <p>&nbsp;</p>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:northwndConnectionString %>"
SelectCommand="SELECT [ProductID], [ProductName], [UnitPrice], [UnitsInStock],
[UnitsOnOrder] FROM [Alphabetical list of products]"></asp:SqlDataSource>
</form></body></html>
13. Press the F5 key to execute the Web site. You can view the chart based on Columns UNITS ON
ORDER and UNITS IN STOCK as shown in Fig.ASP-8.59:

 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

What you will learn in this chapter?


 D e scribing Ma ste r P a ge s
 E xploring T he me s
 D e scribing C a sca ding S tyle S he e t

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.

Describing Master Pages


A master page defines the overall layout of a Web application and all the other Web pages of the Web
application are derived from the master page. It contains controls, banners, navigation menus, and other
elements that you want to include in all the pages of your Web application. This makes your Web application
more maintainable and also avoids duplication of code. The Web pages that inherit the properties defined in
master pages are called content pages. The content pages display their own properties as well as the
properties inherited from the master pages.
ASP.NET 4.5 in Simple Steps

The following are the key functions of a master page:


 Defining common properties of a website, such as banners, navigation menus, and other
elements that can be accessed by the content pages
 Allowing single or multiple content pages to access it
 Displaying the content of each content page in its content placeholder
A master page is actually a template that is referred by all the content pages for using its content in the
Web application. It has the .master extension while a content page has the .aspx extension.
To create a master page for a Web application, identify the controls that you want to display on all the
pages, add these controls to the master page, and then create the ContentPlaceHolder placeholder to
store the content of the Web pages. The content stored in ContentPlaceHolders can be replaced by
any content in an associated content page. When you run the Web application, the layout of the master
page and the content of ContentPlaceHolders are merged to display the resultant Web page.
Master pages are created in Visual Web Developer Express Edition, or Microsoft Visual Studio 2012.
There are two types of master pages, simple master page and nested master page. In this section, you
learn about:
 Creating a simple master page
 Creating nested master page
 Creating a Web form using a master page
Let’s discuss these in detail.

Creating Simple Master Pages


A simple master page simplifies your website design by allowing you to create content pages. It is a
page that is combined with the content page to display the appearance and functionality of the
combined Web page. The concept of simple master and content pages can be better visualized with the
help of following diagram as shown in Fig.ASP-9.1:

 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

The Default.aspx Web form appears in the Solution Explorer window.


10. Open the Desiggn view of the Default.asp
px Web form (Fig.ASP-9.5).
11. Click the smart tag of ContentPlaceHolderr1 (Fig.ASP-9.5).
12. Select the Default to Master’s Conten
nt option from the Content Taskks menu, as shown in
Fig.ASP-9.5:

12

 Fig.ASP-9.5

The Confirrm message box appears (Fig.ASP-9.6).


3. Select the Don’t ask me this agaiin check box and click the Yess button, as shown in Fig.ASP-9.6:
13

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.

Creating Nested Master Pages


The concept of nested master pages is very much similar to that of simple master pages; the only difference is
that nested master pages are used in websites that have several hierarchical levels. Fig.ASP-9.8 shows that an
application can have a number of master pages depending on the level of hierarchy that it incorporates:

 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

5. Add a master page named MasterPage.maste er in the Solution Explore


er window.
6. Add the following code snippet in MasterPage.master:
<div><h1>ASP.NET 4.5 IN SIMPLE STEPS </h1></div>
<div> <h2>Parent Master!</h2><br /><hr style="color: black" /> </div>

Do not add the preceding code snippet in the ContentPlaceHolder tag of MasterPage.master.

7.. Right-click the Nestedmasterpag ge Web application in the Solution Explore


er window and select
Add New Ite em from the context menu. The Add New Item
m dialog box appears.
8. Select Visual C# Master Page option.
9. Select the Select master page check box.
10. Click the Add button. The Select a Master Page dialog box appears.
11. Select the MasterPage.master option from the Contents of folder pane.
12. Click the OK button to add the nested master page in the Web application. The MasterPage2.master
master page is displayed in the Solution Explorer window (Fig.ASP-9.9).
13. Add the following code snippet in ContentPlaceHolder of MasterPage2.master:
<asp:Label ID="Label1" runat="server" BackColor="Aqua" BorderColor="Black"
BorderWidth="2px" BorderStyle="Solid" Font-Size="Large" Text="Child Master">
</asp:Label>
14. Right-click the MasterPage2.master option from the Solution Explorer window (Fig.ASP-9.9).
15. Select the Add Content Page option from the context menu, as shown in Fig.ASP-9.9:

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

Let’s learn to create a Web form by using a master page.

284
Master Pages and Themes

Creating a Web Form Using a Master Page


In ASP.NET 4.5, you can add a Web form which is already built from a master page in your Web
application. The advantage of using these Web forms is that they already inherit the properties of the
master page. The Web forms added without using a master page do not contain its properties.
Therefore, if you want a Web form to contain properties of the master page, you need to create the Web
form by using the master page.
Let’s perform the following steps to add a Web form which already contains properties of a master page
in a Web application.
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.
4. Enter Webformusingmaster as the name of the ASP.NET Empty Web Site in the Web location field
and click the OK button.
5. Add a master page named MasterPage.master.
6 Add the following code snippet in the master page:
<div><asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder> <h1>Web Form Using Master Page</h1></div>
7. Right-click the Webformusingmaster Web application and select the Add New Item option
from the context menu. The Add New Item dialog box appears.
8. Select VisualC#Web Form from the middle pane.
9. Select the Select master page check box.
10. Click the Add
d button. The Select a Master Page dialog box appears.
11. Select the MasterPage.master option from the Contents of folder pane.
12. Click the OK button.
13. Press the F5 key to execute the Web application, as shown Fig.ASP-9.11:

 Fig.ASP-9.11

After learning about master pages, let’s learn about themes.

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

The Add New Iteem dialog box appears (Fig.ASP-9.14).


8. Select Visual C#
# in the left pane and Skin Fille in the middle pane of the Add New Ite
em dialog
box (Fig.ASP-9.14).
9. Click the Add button, as shown in Fig.ASP-9.14:

 Fig.ASP-9.14

0. Add the following code snippet in the skin file:


10
<asp:label runat="server" width="350px" height="50px" font-bold="True" font-size="Large"
forecolor="yellow" backcolor="Blue" Text="Theme Label"/>
<asp:button runat="server" forecolor="Blue" backcolor="Silver" Text="Themebutton"/>
<asp:textbox runat="server" font-bold="True" font-size="Medium" forecolor="Blue"
backcolor="Silver" font-italic="True" Text="Theme textbox"/>
1. Add Labe
11 el, Butto
on, and Textboxx controls in your Default.asp
px page to test the skin file.
2. Add the Them
12 me name in the Page
e directive, as shown in Fig.ASP-9.15:

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.

Using Multiple Themes


In the previous section, we have created a single theme and applied it to the entire Web page. You can
also create multiple themes and give a choice to the user to apply any one of them at runtime.
Let’s perform the following steps to learn how to create and use multiple themes:
1. Open Visual Studio 201 12.
New
2. Select FILE Web Site option.
Templates
3. Select the Installed VisualC# 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 Multiplethemewebsite as the name of the ASP.NET Empty Web Site in the Web location field
and click the OK button.
5. Add two theme folders named Themecontrol1 and Themecontrol2 in the App_Themes folder.
6. Add a skin file to each of the two theme folders and name them as SimpleSkinFile.skin and
InverseSkinFile.skin, as shown in Fig.ASP-9.17:

 Fig.ASP-9.17

288
Master Pages and Themes

7. Add the following code snippet in the SimpleSkinFile.skin file:


<asp:label runat="server" width="350px" height="50px" font-bold="True" font-
size="Large" forecolor="Red" backcolor="Blue"/>
<asp:button runat="server" forecolor="Blue" backcolor="Silver"/>
<asp:textbox runat="server" font-bold="True" font-size="Medium"
forecolor="Blue" backcolor="Silver" font-italic="True"/>
8. Add the following code snippet in the InverseSkinFile.skin file:
<asp:label runat="server" width="350px" height="50px" font-bold="True" font-
size="Large" forecolor="Blue" backcolor="Red"/>
<asp:button runat="server" forecolor="Silver" backcolor="Blue"/>
<asp:textbox runat="server" font-bold="True" font-size="Medium"
forecolor="Silver" backcolor="Blue" font-italic="True"/>
9. Add a Web Form, Default.asp px, in the Solution Explorerr window and then add the following code
snippet to the source file of the Default.aspxx Web form to give the choice of selecting a theme at
runtime:
Listing 10.3
3: Showing the Code of Default.aspx
<%@ 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>
<br />
<strong><em>Applying Themes at Runtime<br />
</em></strong>
<br /> <br /> <br />
<asp:Label ID="Label1" runat="server" Text="Enter your name in
the text box"></asp:Label><br /> &nbsp; <br />
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <br />
<asp:Button ID="Button3" runat="server" Text="Simple Button"/> <br /> <br />
Select Theme<br />
<a href="Default.aspx?Theme=Themecontrol1">Simple</a>
<a href="Default.aspx?Theme=Themecontrol2">Inverse</a>
<br />
</div>
</form>
</body>
</html>
0. Add the following code snippet in the code-behind file, Default.aspx.ccs:
10
protected void Page_PreInit(object sender, EventArgs e)
{
Page.Theme =Request.QueryString["Theme"] ;
}
1. Press the F5 key to execute the Multiplethemewebsite
11 e Web application.
12. Click the Simplle lin
nk in the Web page to apply the theme, as shown in Fig.ASP-9.18:

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

Let’s now learn about CSS.

Describing Cascading Style Sheet


Similar to themes, CSS is also used to give consistent look to Web pages in a Web application. CSS is
used to design a Web page in an efficient manner. It also saves time when there is change in the design
of the Web page. You can change the design of a Web application rapidly using CSS. For example,
suppose there are five text boxes on a Web page in the yellow background color. Now, if you need to
change the color to green then without CSS you have to change the color of each text box explicitly.
However, with CSS you just need to change the color at one place in the style defined for the text box in
CSS. You have to create a CSS file to define styles for the different controls. After creating the CSS file,
you need to include it in a Web page to define styles. CSS is very popular because it is understood by all
the latest browsers. Therefore, it is the language for presentation of Web pages among developers.
Let’s now learn how to use CSS in a Web application.

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> &nbsp;
<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> &nbsp;
<asp:TextBox ID="TextBox2" runat="server" CssClass="txt" Width="196px"
Height="25px"></asp:TextBox>

291
ASP.NET 4.5 in Simple Steps

<br /> <br /> <br /><asp:Button ID="Button1" runat="server" Text="Submit"


CssClass="btn" Width="123px" />
</div>
</form>
</body>
</html>
1. Press the F5 key to view the effect of the style sheet on the Web Form, as shown in Fig.ASP-9.20:
11

11

 Fig.ASP-9.20

Let’s discuss about the improvements in CSS.

Exploring Improvements in CSS


ASP.NET 4.5 includes significant enhancements in CSS according to the latest Hypertext Markup
Language (HTML) standards. The changes in CSS include its usage with Web server controls, such as
label and textbox. CSS now includes set of tools to create, apply, and manage styles as well as CSS.
Some of these tools are as follows:
 Apply Styless: Enables you to create, modify, and apply styles. External CSS can also be used in a
Web application using this tool. It helps you to identify the style types and apply styles to a whole
Web page or the selected portions of the Web page.
 Manage Styless: Enables you to change styles from an internal style sheet to an external style sheet
or vice versa. It also enables you to move styles within a style sheet.
 CSS Propertiess: Displays the styles that are currently applied to a Web page. It also shows you
the priority order for the styles. It also displays the list of all CSS properties in a style sheet. It
helps you to add properties other than present in an existing style, modify properties of already
set styles, and create new inline styles.
 Direct Style Application
n: Helps you to remove or apply styles which are based on class-ID. It also
helps you to create or apply new styles on the controls. It controls styles that are generated by
ASP.NET application.
With this, we come to the end of the chapter. Let’s now summarize the main points of the chapter.
SUMMARY
In this chapter, you have learned about:
 Master pages
 Concept and types of themes
 CSS and improvements in CSS

292
CHAPTER 10
Introducing ASP.NET AJAX

What you will learn in this chapter?


 ASP.NET AJAX
 Traditional and ASP.NET AJAX Web Applications
 Exploring Some Important Features of AJAX
 AJAX Server Controls
 Creating an ASP.NET AJAX Application
 Creating jQuery Web Application

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.

Traditional and ASP.NET AJAX Web Applications


Traditional Web applications are based on the request-response or postback model. For each client
interaction for requesting information with traditional Web application, an HTTP request is sent to the
server, which processes the request and sends the results back to the application. After the request has
been sent to the server, the user has to wait until the server responses. On the other hand, using AJAX
controls, you can develop a Web application that send HTTP request to the server asynchronously. This
helps the users to continue their interaction with the Web site without waiting for the response. As soon
as the server responses, the information or data appears on the Web site.

Exploring Some Important Features of AJAX


Nowadays, Web applications are primarily developed by using the AJAX framework, as the AJAX-
supporting websites are more responsive and consume less time for Web server processing than the
traditional Web applications. Microsoft keeps enhancing the features of AJAX with every release of
ASP.NET to provide more functionality to build rich Internet applications. The following are some
important features in ASP.NET 4.5 related to the AJAX technology are as follows:
 Live data binding
 Declarative instantiation of client components
 The observer pattern on JavaScript objects and arrays
 ADO.NET data services and data contexts
Let’s discuss each of these features in detail.

Live Data Binding


Live data binding ensures that the data is bound with the server controls at runtime. ASP.NET AJAX
provides the support for live data binding with the help of observer pattern, which is supported by the
Sys.Observer class. The observer pattern feature helps you to observe the changes made in a JavaScript
object. You can use the live data binding technique in two ways: one-way and two-way. In the one-way
data binding, data is not updated automatically. On the other hand, in the two-way data binding, data
is updated automatically if the data source changes.

Declarative Instantiation of Client Components


ASP.NET AJAX supports declarative instantiation of client components, such as controls and behaviors
attached to them. The declarative instantiation of controls works only when the declarative markup is
present within an element that has been configured for this purpose only. The declarative markup
includes additional namespace attributes, which are XHTML compliant. To declaratively instantiate
controls outside a template, you need to first configure a page to ensure that the sys:attach markup is
present within an activated element. The following code snippet shows how to activate controls:
<body xmlns:sys="javascript:Sys" sys:activate="Button1,Button2">

294
Introducing ASP.NET AJAX

In the preceding code snippet, you can observe that two Button controls are activated.

The Observer Pattern on JavaScript Objects and Arrays


The observer pattern provides a functionality to observe the changes made in JavaScript objects. If there
is any change in an object, a notification is raised and an event handler is used to handle the changes
in the object. You can set the observers on an object by using the observer design pattern. ASP.NET
AJAX uses the Sys.Observer class to support the observer design pattern. You can use the observer
pattern to establish live bindings between User Interface (UI) elements and objects or arrays that might
be provided by the JSON Web service. The observer pattern is also used to define a one-to-many
dependency among the objects. Therefore, when one object changes its state, all the others are notified
accordingly and updated automatically.

ADO.NET Data Services and Data Contexts


The data context object enables you to bind the JavaScript array or object to a template. It can interact
with JSON-based Web services. The data context recognizes all the changes that have been made in the
data automatically by using the Sys.Observer class. There are two types of data context objects that are
provided by ASP.NET AJAX: Sys.Data.DataContext and Sys.Data.AdoNetDataContext. The
Sys.Data.DataContext class enables you to read and write data while using the data provider, such as
ADO.NET data service. If you are using an ADO.NET data service, you should use the
AdoNetDataContext class. The AdoNetDataContext class supports the enhanced features of ADO.NET
data services, such as identity management, links, and association between entity sets.

AJAX Server Controls


Microsoft has introduced AJAX-specific controls in Visual Studio 2012 to implement AJAX easily in a
Web site. You can find these controls under the tab named AJAX Extensions in the Toolbox. When you
add any of these controls to the Web form, the reference of the corresponding script library is added
automatically to the Web page. The following is a list of AJAX server controls:
 The ScriptManager control
 The UpdatePanel control
 The UpdateProgress control
 The Timer control
 The ScriptManagerProxy control
Now, let’s discuss each of these controls in detail.

The ScriptManager Control


The ScriptManager control is the first AJAX server control in the Toolbox that helps in implementing
the AJAX functionality in the ASP.NET Web site. You need to add this control on the Web page
whenever the AJAX functionality is required. In the absence of this control, no other AJAX server
controls, such as Timer, UpdatePanel, and UpdateProgress, will work on the Web page. To add
the ScriptManager control in the Web page, just drag and drop it from the Toolbox in the Design
view of the Web page.
Table 11.1 lists some noteworthy properties of the ScriptManager class:

295
ASP.NET 4.5 in Simple Steps

Table 11.1: Noteworthy Properties of the ScriptManager Class


Property Description
AsyncPostBackErrorMessage Specifies an error message that is returned to the client due to
occurrence of an unhandled server exception during an asynchronous
postback
AsyncPostBackSourceElementID Specifies the identity document (ID) of the control that triggers the
asynchronous postback
AsyncPostBackTimeout Specifies a time value in seconds to timeout the asynchronous postback
if the response is not received
EnablePartialRendering Specifies a value to indicate whether or not to enable partial-page
rendering
IsInAsyncPostBack Specifies whether or not the ScriptManager control executes the current
postback in a partial-rendering mode
LoadScriptsBeforeUI Specifies a value to indicate whether scripts are loaded before or after
the page markup
Services Retrieves a ServiceReferenceCollection object that contains a
ServiceReference object for each Web service that ASP.NET discloses on
the client for AJAX functionality
SupportsPartialRendering Specifies a value to indicate whether or not the client supports partial-
page rendering

Table 11.2 lists some noteworthy events of the ScriptManager class:


Table 11.2: Noteworthy Events of the ScriptManager Class
Event Description
AsyncPostBackError Fires due to occurrence of page error during an asynchronous
postback
ResolveScriptReference Fires when a member of the Scripts collection is registered with the
ScriptManager control

Partial-page rendering is a feature of AJAX-enabled Web sites. It enables you to update a


specific part instead of the entire Web page.

The UpdatePanel Control


The UpdatePanel control helps you to divide a Web page into any number of parts, where each part
can be updated independently from each other. A single Web page can contain multiple UpdatePanel
controls, where each control creates a separate part of your Web page. To add the UpdatePanel
control in the Web page, drag and drop it from the Toolbox in the Design view of the Web page. The
UpdatePanel control uses the UpdatePanel class to support partial-page rendering.

296
Introducing ASP.NET AJAX

Table 11.3 lists some properties of the UpdatePanel class:


Table 11.3: Noteworthy Properties of the UpdatePanel Class
Property Description
ContentTemplate Retrieves or sets a template to define the content of the UpdatePanel control
ContentTemplateContainer Retrieves the UpdatePanel control object to programmatically add child
controls
Controls Retrieves the ControlCollection object having the child controls for the
UpdatePanel control
IsInPartialRendering Retrieves a value to indicate whether or not to update the UpdatePanel
control when a client triggers the asynchronous postback
RenderMode Retrieves or sets a value to indicate whether or not the content of the
UpdatePanel control is placed within the HTML <div> or <span> tags
UpdateMode Retrieves or sets a value to indicate when the content of the UpdatePanel
control is updated

The UpdateProgress Control


While working with the UpdatePanel control, you sometimes need to show the status of the
information requested by the user. In other words, you need to make your viewers aware of the progress
status of the requested data while refreshing the content of the UpdatePanel control. This task is
accomplished with the help of the UpdateProgress control. As per your requirement, you can use
image, text, or a progress bar to show the status. The UpdateProgress control is visible when the
task of updating content is in progress, and disappears as soon as the content is updated. To add the
UpdateProgress control to the Web page, just drag and drop it from the Toolbox in the Design view
of the Web page.
The UpdateProgress control uses the UpdateProgress class to support the properties involved in
displaying the update progress.
Table 11.4 lists some noteworthy properties of the UpdateProgress class:
Table 11.4: Noteworthy Properties of the UpdateProgress Class
Property Description
AssociatedUpdatePanelID Retrieves or sets the ID of the UpdatePanel control for which the status has
been displayed
DisplayAfter Retrieves or sets time in milliseconds before which the UpdateProgress
control is showed
DynamicLayout Retrieves or sets a value to indicate whether or not to render the progress
template dynamically
ProgressTemplate Retrieves or sets a template that describes the content of the UpdateProgress
control

297
ASP.NET 4.5 in Simple Steps

The Timer Control


Generally, the contents of the UpdatePanel control are updated when an event is triggered by the
user. Sometimes, this leads to a problem as you are required to update the contents of the page after a
specific interval. In other words, instead of triggering the updates by the users, the content should be
updated automatically on the Web page. This is done with the help of the Timer control that contains
a property named Interval and an event named Tick. The Interval property of the Timer
control is used to specify the desired time limit in seconds. When this time limit is over, it raises the
Tick event. This Tick event is handled to update the content of the Web page. To add the Timer
control to the Web page, just drag and drop it from the Toolbox in the Design view of the Web page.
The Timer control uses the Timer class to support the properties and events required to work with the
Timer control.
Table 11.5 lists some noteworthy properties of the Timer class:
Table 11.5: Noteworthy Properties of the Timer Class
Property Description
Enabled Retrieves or sets a value to indicate whether or not the Timer control starts a
postback when the interval time has passed
Interval Retrieves or sets time in milliseconds to wait before the Timer control initiates a postback
ViewStateMode Retrieves or sets the control’s viewstate mode

Table 11.6 lists some noteworthy event of the Timer class:


Table 11.6: Noteworthy Event of the Timer Class
Events Description
Tick Occurs whenever the specified interval time elapses in the Interval property

In this chapter, the ScriptManagerProxy control is not discussed, as it requires some advance
programming techniques.

Creating an ASP.NET AJAX Application


After discussing the various AJAX server controls, let’s now learn to use these controls in the Web
application. In the following Web application, when the user clicks the button control on a Web page,
the system’s current date and time are displayed. Moreover, when the process is in progress, the
UpdateProgress control is displayed. To do so, you are required to follow these steps:
1. Open Visual Studio 2012.
2. Select FILENewWeb Site option.
The New Web Site dialog box appears.
3. Select the Installed TemplatesVisual C# option from the left pane and the ASP.NET Empty
Web Site template from the middle pane of the New Web Site dialog box.

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

<%@ 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:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate><strong>Updation is in progress
</strong>
</ProgressTemplate>
</asp:UpdateProgress>
<h2>
<asp:Label ID="LabelHadding" runat="server" Text="Application Using
UpdateProgress Control">
</asp:Label>
</h2>
<asp:Label ID="Label1" runat="server" Text="UpdateProgress Demo">
</asp:Label>&nbsp;
<asp:Button ID="Button1" runat="server" Text="Get Time" />
</ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
</html>

The Web form now appears in the Design view (Fig.ASP-11.1).


11. Double-click the Get Time button, as shown in Fig.ASP-11.1:

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.

Creating jQuery Web Application


Let’s create a Web application to learn the usage of jQuery with Web server controls by performing the
following steps:
1. Open Visual Studio 2012.

300
Introducing ASP.NET AJAX

2. Select FILENewWeb Site option.


The New Web Site dialog box appears.
3. Select the Installed TemplatesVisual C# option from the left pane and the ASP.NET Empty
Web Site template from the middle pane of the New Web Site dialog box.
4. Specify the location and name of the application in the Web location combo box. In our case, we
have provided the name as JQuerywebapplication.
5. Click the OK button to save the settings.
6. Add a Web form by right-clicking the application name, similar to how you have done earlier.

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

<%@ 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>
<h2>This is JQuery World</h2>
<asp:TextBox ID="txtFirstName" runat="server" />
<asp:Label ID="Label1" runat="server"></asp:Label>
<br />
<asp:TextBox ID="txtLastName" runat="server" />
<br />
<input id="Button1" type="button" value="button" />
<script src="Scripts/jquery-1.3.2.js" type="text/javascript">
</script>

<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

The text ultimately disappears (Fig.ASP-11.6).


10. Click the text boxes one by one, their color will change at runtime (Fig.ASP-11.6).
11. Click the button control on the Web page, its size and color changes, as shown in Fig.ASP-11.6:

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

What you will learn in this chapter?


 N e e d for U sing S ilve rlight
 N e w F e a ture s of S ilve rlight 5.0
 S ilve rlight A rchite cture
 D e ve loping a S ilve rlight A pplica tion

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.

Need for Using Silverlight


You know that Silverlight is designed for developing rich and interactive Web-based content. In this
section, you will come to know the different scenarios or situations where Silverlight can be used. The
following are some of the Web applications where Silverlight can be used:
ASP.NET 4.5 in Simple Steps

 Playing dynamic video and audio playback files.


 Mini applications, such as casual games and gadgets.
 Customizing navigation properties, data visualization, and displaying animated advertisements.
Silverlight offers a variety of innovative features that facilitate Web developers and designers to build
appealing Web sites. Silverlight has an improved programming model, comprehensive UI framework,
and support for Deep Zoom technology, two-dimensional (2D) graphics, animations, multimedia, and
networking. Silverlight leverages many functionalities and features of the .NET framework, such as type-
safety and exception handling. It also includes many classes from the base class library and offers you
the scope of working with Input/Output (IO) operations, collections and generics, and threading. You
can use any of the .NET languages, such as Visual Basic (VB) and C#, to develop Silverlight
applications. You can combine ASP.NET AJAX and Silverlight to get the best of both the technologies.
Silverlight also supports Language Integrated Query (LINQ) to Objects, which facilitates you to work with
various types of data in the Web applications. Moreover, Silverlight seamlessly integrates with the HTML,
JavaScript, Document Object Model (DOM) as well as with an Extensible Application Markup Language
(XAMLL) parser, thereby providing you the scope to work with HTML, JavaScript, and XAML
simultaneously. In this way, Silverlight extends a cohesive platform for developing interactive and
superior-quality Web applications.
Silverlight has a comprehensive UI framework, which allows you to design the UI of Web sites by using
the predefined controls, styles, themes, and templates. Silverlight offers a wide range of controls and
layout features to build exceptionally attractive Web applications. You can also use styles and control
templates in the Silverlight applications. You can also use the data-binding and data-manipulation
controls, such as DataGrid. Predefined Silverlight controls and layout features help you to quickly and
easily develop some high-end Web applications. You can set the properties of these controls to get the
desired effect. Note that these properties can also be set by using XAML, which separates the design and
the code of Web applications. Silverlight has built-in support for 2D vector graphics and animations.
You can create 2D shapes, such as rectangles and ellipses, geometries, and brushes, in the Silverlight
application. You can also transform and animate the shapes and geometries. In addition, you can make
your Web applications attractive by including the .jpeg or .png images in the Web applications to make
the UI more attractive. Silverlight also supports various multimedia formats, such as .wma, .wmv, and
.mp3, to play multimedia content.

New Features of Silverlight 5.0


The Silverlight 5.0 in ASP.NET 4.5 includes the following new features that help in building rich-
animated Web-based applications.

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

Developing a Silverlight Application


Let’s create an application in Silverlight to learn its usage by performing the following steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
Visual Studio 2012. The Start Page
appears.
2. Select FILENewProject from the menu bar.
The New Project dialog box appears (Fig.ASP-11.2).
3. Select InstalledTemplatesVisual C#Silverlight option in the left pane (Fig.ASP-11..2).
4. Select the Silverlight Application in the middle Templates pane (Fig.ASP-11..2).
5. Enter Silverlightvideoapplication in the Name text box to specify the name of the application
(Fig.ASP-11..2).
6. Enter an appropriate location for the application in the Location combo box (Fig.ASP-11.2).
7. Click the OK button, as shown in Fig.ASP-11.2:

5
6

 Fig.ASP-11.2

The New Silverlight Application dialog box appears (Fig.ASP-11.3).


8. Select the Host the Silverlight application in a new Web site check box (Fig.ASP-11.3).
9. Click the OK button, as shown in Fig.ASP-11.3:

309
ASP.NET 4.5 in Simple Steps

 Fig.ASP-11.3

0. Right-click the application name in the Solutio


10 on Exploreer window to open the context menu
(Fig.ASP-11.4).
1. Select AddExisting Ite
11 em option from the context menu, as shown in Fig.ASP-11.4:

11

 Fig.ASP-11.4

The Add Existing Ite


em dialog box appears.
2. Navigate to the location and select the video, which you want to display on the Web page. In our
12
case, we are selecting the Wildlife video in the Samplle Video
os folder (Fig.ASP-11.5).
3. Click the Add button, as shown in Fig.ASP-11.5:
13

310
Working with Silverlight Applications

12

13

 Fig.ASP-11.5

The video file appears in the Solutio


on Explore
er window (Fig.ASP-11.6).
4. Right-click the Wildlife.wm
14 mv file (Fig.ASP-11.6).
5. Select the Propertie
15 es option from the context menu, as shown in Fig.ASP-11.6:

15

 Fig.ASP-11.6

311
ASP.NET 4.5 in Simple Steps

The Propertiees window appears (Fig.ASP-11.7).


6. Set the Build Actio
16 on property to Resourcce, as shown in Fig.ASP-11.7:

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">

<Grid x:Name="LayoutRoot" Background="White">


<MediaElement x:Name="MediaPlayer" Source="Wildlife.wmv" AutoPlay="False"
Margin="28,28,26,34" HorizontalAlignment="Center"></MediaElement>

<Button Content="Play" Height="23" HorizontalAlignment="Center"


Margin="53,276,33,0" Name="button1" VerticalAlignment="Bottom" Width="75"
Click="button1_Click" />

<Button Content="Pause" Height="23" HorizontalAlignment="Center"


Margin="155,276,0,0" Name="button2" VerticalAlignment="Bottom" Width="75"
Click="button2_Click" />

<Button Content="Stop" Height="23" HorizontalAlignment="Center"


Margin="313,0,12,0" Name="button3" VerticalAlignment="Bottom" Width="75"
Click="button3_Click" />
</Grid>

</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

What you will learn in this chapter?


 N e w F e a ture s in W P F 4.5
 E xploring X A ML B rowse r A pplica tions
 Imple me nting T ypogra phy in W P F
 E xploring S ome C ontrols in W P F

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

New Features in WPF 4.5


WPF 4.5 is a User Interface (UI) framework that helps you in creating interactive client applications. It
supports various application development features, such as controls, graphics, layout, and data binding.
WPF 4.5 uses XAML language for application programming. You can use WPF 4.5 for creating both
standalone and browser-hosted applications.
WPF 4.5 has several improvements and enhancements over its previous version, WPF 4.0. Some new
features of WPF 4.5 include:
 The Ribbon control
 Support for validating data synchronously and asynchronously
 Support for binding to types that implement ICustomTypeProvider
 Support for fetching binding information
 Data binding to static properties
 Support for access to collections on a non-UI thread
 Support for automatically updating a source of a data binding
 New VirtualizingPanel features
 Support for implementing a Weak reference to an Event
 New methods defined in the Dispatcher class
 Support for use of Markup extensions for events
 Support for rearrangement of data on modification (Live shaping)
 Improved performance when displaying large sets of grouped data
 Support for validation of DataContext object
Let’s explore these features of WPF 4.5 in detail.

The Ribbon Control


The Ribbon control enables you to place some controls on a horizontal bar called ribbon, which is
present at the top edge of an application window. Using the Ribbon control, you can create tabs that
contain related controls. Depending upon the functionality of each control in a tab, you can further
divide the controls into groups. For example, in Microsoft Word, the main tabs on a ribbon are Home,
Insert, Page Layout, References, Mailings, Review, and View. These tabs are further categorized into
groups of commands, for instance, the Home tab is categorized into the Clipboard, Font, Paragraph,
Styles, and Editing groups. The Ribbon control makes it easy for a user to find and run certain
commands that are executed frequently while using an application. The user can simply click and select
a control to execute the command associated with it and does not need to search for the command in
menus and toolbars.

Support for Validating Data Synchronously and Asynchronously


WPF 4.5 provides support for validating data both synchronously and asynchronously by implementing
the INotifyDataErrorInfo interface. By using this interface, you can specify user-defined validation rules
for data entity classes. This interface also allows you to implement user-defined or custom error objects.

316
Windows Presentation Foundation

Moreover, it provides support for validating cross-property errors, entity-level errors, and multiple errors
for a single property.

Support for Binding to Types that implement ICustomTypeProvider


WPF 4.5 provides support for custom types by implementing the ICustomTypeProvider interface. This
interface is used to bind an object or custom type with properties at run time, thereby avoiding name
resolution errors at run time. The custom types can be used as PropertyPath during data binding, value
of the DataType property, and type that finds the automatically generated columns of the DataGrid
control.

Support for Fetching Binding Information


In WPF 4.5, some new Application Programming Interfaces (APIs) have been added to help you in
fetching data-binding information. If the BindingExpression class is known, then you can easily fetch the
source and target object information by using these APIs. You can also fetch information related to the
properties that are associated with the source or target object involved in the binding. Table 12.1 lists
the new APIs added in WPF:
Table 12.1: New APIs in WPF
API Description
BindingExpressionBase.Target Retrieves the target object involved in binding
BindingExpressionBase.BindingGroup Retrieves the binding group of the binding expression
BindingExpressionBase.TargetProperty Retrieves the property of binding target object
Owner Retrieves the object with which a binding group is
associated
BindingExpression.ResolvedSource Retrieves the source object involved in binding
BindingExpression.ResolvedSourcePrpperty Name Retrieves the property of binding source object

Data Binding to Static Properties


WPF 4.5 enables you to establish data binding using static properties of a class. A static property is
shared by each instance of a class and can be used as the source of data binding. An event can then be
defined as one which can be raised whenever the value of the static property changes. For example,
consider a class, ExampleClass, which consists of a static property, ExampleProperty. In this case, a
static event can be defined as one which can be raised whenever ExampleProperty changes its value.
You can declare a static event by using any one of the following two syntaxes:
 public static event EventHandler ExamplePropertyChanged;
 public static event EventHandler<PropertyChangedEventsArgs> StaticPropertyChanged;

Support for Access to Collections on a Non-UI Thread


In the previous versions of WPF, a data collection cannot be accessed from a non-UI thread, as it might
raise a run-time exception. However, in WPF 4.5, you can use a non-UI thread to access and modify a
data collection. This enables you to display a data collection modified by a non-UI thread on a UI

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.

Support for Automatically Updating a Source of a Data Binding


In WPF 4.5, you can prevent a data source in a data binding from frequently updating its content using
the Delay property. By using the Delay property, the process of updating the source of data binding is
postponed for a specified amount of time (in milliseconds). This is done to prevent the source from
updating the property values until the target finishes modifying the values. Therefore, only final property
value is updated in the source, preventing the source from making unnecessary updates. For example,
while resizing an image in an image editing application, you need to save only the final size of the
image. In this case, the Delay property can be used to prevent the source from unnecessarily saving
intermediate size values.

New VirtualizingPanel Features


In WPF 4.5, some new properties, such as ScrollUnit, CacheLength, and CacheLengthUnit, have been
added in the VirtualizingPanel class. This makes the performance of VirtualizingPanel even better than
the one in the previous versions of WPF 4.5. You can set the ScrollUnit property to the Item or Pixel
value. When its value is set to Item, it displays an element only when the element can be displayed
completely. This implies that it does not display those elements that can be displayed partially on a UI.
However, when the value of ScrollUnit property is set to Pixel, even those elements are displayed that are
partially visible on the UI. The CacheLength and CacheLengthUnit properties improve the performance
of VirtualizingPanel by allowing you to set both the size of the cache using the CacheLength property
and the unit in which the cache size is specified using the CacheLengthUnit property. Moreover, apart
from specifying values, you can retrieve the cache size and its unit using these properties.

Support for Implementing Weak Reference to an Event


The garbage collector does not free the memory allocated to an event handler even when its job is over
or it is not required anymore. As a result, the memory remains allocated to an event handler
unnecessarily. This inefficient management and wastage of memory is called memory leaks. WPF
provides weak event patterns that are used to prevent such memory leaks.
Weak event pattern was first introduced in WPF 3.0; however, WPF 4.5 has simplified its
implementation. In WPF 4.5, you do not need to implement the IWeakEventListner interface for
implementing a weak event pattern. Moreover, you can subscribe to an event using a generic weak
event pattern. You can also create your own custom weak event pattern when you cannot find a weak
event manager available for an event in WPF.

New Methods Defined in the Dispatcher Class


In WPF 4.5, the Invoke and InvokeAsync methods have been added in the Dispatcher class. Invoke is a
synchronous method that accepts an Action or Func<TResults> as its parameters and executes a
delegate on the thread that is linked with the Dispatcher class. The InvokeAsync method also performs
the same operation of executing a delegate by accepting an Action or Func<TResult> as its parameter.
However, InvokeAsync is not a synchronous method. This implies that it executes the delegate
asynchronously.

318
Windows Presentation Foundation

Support for the Use of Markup Extensions for Events


A markup extension assigns a value specified within curly braces to an attribute. In WPF 4.5, events can
also have markup extensions. However, you can only use third-party markup extensions with events.
This is because WPF 4.5 only provides the support for using markup extensions with events, but does not
allow you to define your own customized markup extension for an event.

Support for Rearrangement of Data on Modification (Live Shaping)


WPF 4.5 supports the concept of live shaping of data. Live shaping of data means rearranging, filtering,
sorting, or grouping of data when it is modified. In other words, live shaping is a real-time
rearrangement of data, which is performed when the data is modified. For example, consider a
DataGrid control that displays a list of products, which is sorted in the ascending order, according to the
price of each product. When the price of any product is changed, its position in the data grid must also
change. In such cases, live shaping can be implemented to enable the repositioning of the product in
real time as soon as its price is changed.

Improved Performance when Displaying Large Sets of Grouped Data


When a large number of UI elements are displayed at the same time, performance is affected to a great
extent. This is because it requires huge memory as well as rendering requirements, thereby making your
application slow and unresponsive. UI virtualization supported by WPF 4.5 enables you to display only
those visual elements that are required at any point of time; other elements of the UI are processed only
when the requirement arises. This minimizes the number of UI elements that are displayed at a time,
thereby improving the overall performance of your application. The VirtualizingPanel class provides the
IsVirtualizingWhenGrouping attached property that allows UI Virtualization for grouped data.

Support for Validation of DataContext Object


WPF 4.5 provides the support for validating the connection of a DataContext object with the item container
with which it is associated. A data item is displayed by an item container which is an element of ItemsControl
bounded to a collection. Sometimes, the DataContext object of an item container gets disconnected from it.
This usually happens when the UI is virtualized or when the item container is removed from the collection
which is bound to ItemControl. Therefore, you need to validate the DataContext object associated with the
item container by comparing it with the DisconnectedSource object.
Let’s explore the XAML browser applications.

Exploring XAML Browser Applications


XAML files are files that are created using the Extensible Markup Language (XML), which is the subset of
XAML. These files have .xaml extension and allow you to perform various tasks, such as creating UI
elements in the XAML markup, separating the UI from the application logic, and joining markup
through partial classes. XAML browser applications (XBAP, pronounced as x-bap) are WPF applications
that run in a Web browser. Visual Studio 2012 provides a project template for creating XBAPs that can
run easily on the Web environment.
Let’s perform the following steps to create a XAML browser application:
1. Click StartAll Programs Microsoft Visual Studio 2012 Visual Studio 2012. The Start Page
appears.

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

Implementing Typography in WPF


WPF supports a rich text format. In other words, the text in a WPF application can be presented in
different format and styles. The presentation of text in WPF is termed as Typography, which is the art of
presenting the content in various styles, such as alignment of text, font style, and placement of graphics.
Now, let’s perform the following steps to learn how to implement typography in a Web site:
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#
Windows option in the left pane of the New Project
dialog box.
4. Select WPF Browser Application template in the middle pane.
5. Enter WPFtypography 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.
7. Replace the code of Page1.xaml file with the code given in Listing 12.2 to add the required
controls and set their properties:
Listing 12.2: Code of the Page1.xaml File in the WPFtypography Application
<Page x:Class="WPFtypography.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>

322
Windows Presentation Foundation

<Rectangle Canvas.Left="-526.614" Canvas.Top="-159.984" Height="92.5"


VerticalAlignment="Top">
<Rectangle.Fill>
<LinearGradientBrush EndPoint='0,1'>
<LinearGradientBrush.GradientStops>
<GradientStop Offset='0' Color='#FFFF0000' />
<GradientStop Offset='.39' Color='#9900FF00' />
<GradientStop Offset='.16' Color='#FF0000FF' />
<GradientStop Offset='.45' Color='#00FFFFFF' />
</LinearGradientBrush.GradientStops>
</LinearGradientBrush>
</Rectangle.Fill>
</Rectangle>
<Button Margin="97.5,143.75,57.5,88.75" Name="button1" Click="button1_Click">
<Button.LayoutTransform>
<ScaleTransform ScaleX="5" ScaleY="5" />
</Button.LayoutTransform>
<StackPanel Orientation="Horizontal">
<Canvas Width="20" Height="18" VerticalAlignment="Center">
<Ellipse Canvas.Left="1" Canvas.Top="1" Width="18" Height="18"
Fill="CadetBlue" Stroke="Black" />
<Ellipse Canvas.Left="5.5" Canvas.Top="5" Width="2.5" Height="3"
Fill="Black" />
<Ellipse Canvas.Left="11" Canvas.Top="5" Width="2.5" Height="3"
Fill="Black" />
<Path Data="M 5,10 A 3,3 0 0 0 13,10" Stroke="Black" />
</Canvas>
<TextBlock VerticalAlignment="Center">Click Me!</TextBlock>
</StackPanel>
</Button>
</Grid>
</Page>

Add namespace System.Threading in the Page1.xaml.cs file to use Thread class.

8. Double-click the button


n1 control on the design surface and add the following code snippet in its
Click event:
private void button1_Click(object sender, RoutedEventArgs e)
{
FormattedText text=new FormattedText("KOGENT
SOLUTIONS!",Thread.CurrentThread.CurrentUICulture, FlowDirection.LeftToRight, new
Typeface("Arial Black"), 10, Brushes.Black);
Geometry textGeometry = text.BuildGeometry(new Point(0, 0));
button1.Clip = textGeometry;
}
9. Press the F5 key to execute the application, as shown in Fig.ASP-12.4:

323
ASP.NET 4.5 in Simple Steps

 Fig.ASP-12.4

0. Click the Click Me


10 e! button. The text on the button changes, as shown in Fig.ASP-12.5:

 Fig.ASP-12.5

Exploring Some Controls in WPF


To further enhance interactivity and user-friendliness with WPF applications, let’s learn about some
controls in WPF:
 The DataGrid control
 The DatePicker control
 The Calendar control
 The Ribbon control
Let’s now learn the usage of each of these controls.

324
Windows Presentation Foundation

Using DataGrid Control


The DataGrid control allows you to display data in the form of rows and columns. It has built-in column
types and a template column for hosting the specific set of data requested by the user.
Let’s create an application to learn the usage of the DataGrid 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#
Windows option in the left pane of the New Project
dialog box.
4. Select WPF Browser Application in the Templates pane.
5. Enter Datagridbrowserapplication 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.
7. Add a DataGrid control on the page (name it as Northwindgrid) and set the AutoGenerateColumns
property to true.
8. Add a Button control on the design surface and set the content property of the Button control to
Submit.
9. Open the Page1.xaml.cs file and add the following code shown in Listing 12.3:
Listing 12.3: Code of the Page1.xaml.cs File
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

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

public string BName { get; set; }


public DateTime DOP { get; set; }
public string BookTitle { get; set; }
}
private List<Books> LoadBooksData()
{
List<Books> authors = new List<Books>();
authors.Add(new Books()
{
ID = 1001,
BName = "Database",
BookTitle = "SQLSERVER 2008",
DOP = new DateTime(2009, 12, 12),

});
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

<DataGrid x:Name="Northwindgrid" AutoGenerateColumns="True" Height="200"


Margin="20,27,0,0" VerticalAlignment="Top" HorizontalAlignment="Left"
Width="353" />
<Button Content="Submit" Height="23" HorizontalAlignment="Left"
Margin="160,268,0,0" Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
</Grid>
</Page>
11. Press the F5 key to execute the application (Fig.ASP-12.6).
12. Click the Submiit button on the Web Form, as shown in Fig.ASP-12.6:

12

 Fig.ASP-12.6

Using DatePicker Control


The DatePicker control allows you to select date from the drop-down calendar. Let’s create an
application to learn the usage of the DatePicker 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.
Templates
3. Select Installed Visual C# Windows option in the left pane of the New Project
dialog box.
4. Select WPF Browser Application template in the middle pane.
5. Enter Datepickerbrowserapplication 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.
7. Add five Label controls, three DatePicker controls, and one Button control on the design surface
on the Page1.xaml page.
8. Set the Content property of the label1 control as TIME SCHEDULE, Label2 as English, Label3 as
Hindi, Label4 as Maths, and button1 as Submit.
The Page1.xaml page appears, as shown in Fig.ASP-12.7:

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

<DatePicker Height="25" HorizontalAlignment="Left" Margin="135,124,0,0"


Name="datePicker2" VerticalAlignment="Top" Width="115" />
<DatePicker Height="25" HorizontalAlignment="Left" Margin="135,48,0,0"
Name="datePicker3" VerticalAlignment="Top" Width="115" />
</Grid>
</Page>
10. Press the F5 key to execute the application (Fig.ASP-12.8).
11. Select the values from each of the three DatePicker controls on the Web Form, as shown in
Fig.ASP-12.8:

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

Using Calendar Control


The Calendar control is used with the DatePicker control to select date. Let’s create an application to
learn the usage of the Calendar control by performing the following steps:
1. Open Visual Studio 201 12.
2. Select FILENewProjectt option from the menu bar. The New Projecct dialog box appears.
Templates
3. Select Installed Visual C# Windows option in the left pane of the New Project
dialog box.
4. Select WPF Browser Application template in the middle pane.
5 Enter Calendarbrowserapplication 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.
7. Add three label controls, a calendar control, and a button control.
8. Set the content property of the label1 control as Calendar Control, label2 control as Select Your
Birth date, and button1 control as Submit.
The Page1.xaml page now appears, as shown in Fig.ASP-12.10:

 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

The Ribbon Control


The Ribbon control enables you to place some controls on a horizontal bar called Ribbon which is
present at the top of a WPF application window. This control makes it easier for a user to access and run
certain commands that are executed frequently while using an application. Let’s create an application to
learn the usage of the Ribbon control by performing the following steps:

331
ASP.NET 4.5 in Simple 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# Windows option in the left pane of the New Project
dialog box.
4. Select WPF Application template in the middle pane.
5. Enter Ribboncontrol 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.
7. Right-click the References node in the Solution Explorer window and select the Add Reference
option in the context menu, as shown in Fig.ASP-1312:

 Fig.ASP- 14.12

The Reference Manager dialog box appears (Fig.ASP-1313).


8. Select the System.Windows.Controls.Ribbon check box to add its reference (Fig.ASP-12.13).
9. Click the OK button, as shown in Fig.ASP-12.13:

 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>

<Ribbon HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top"


Width="489">
<RibbonTab Header="Home" HorizontalAlignment="Left" Height="88" VerticalAlignment="Top"
Width="476">
<RibbonGroup Header="Font" Height="88" Margin="0" VerticalAlignment="Top" Width="123">
<ComboBox HorizontalAlignment="Left" Height="22" VerticalAlignment="Top" Width="103"
Margin="0,0,-78,0">
<ComboBoxItem Content="Times New Roman"/>
<ComboBoxItem Content="Arial"/>
<ComboBoxItem Content="Lucida Console"/>
<ComboBoxItem Content="Book Antiqua"/>
</ComboBox>
</RibbonGroup>
<RibbonGroup Header="show" Height="88" Margin="0" VerticalAlignment="Top" Width="123">
<CheckBox Content="Ruler" HorizontalAlignment="Left" Height="16" VerticalAlignment="Top"
Width="68"/>
<CheckBox Content="Gridline" Height="16" VerticalAlignment="Top" Margin="0,9,0,-9"/>
<CheckBox Content="Navigation Pane" HorizontalAlignment="Left" Height="16"
VerticalAlignment="Top" Width="68" Margin="0,17,0,-17"/>
</RibbonGroup>
</RibbonTab>
<RibbonTab Header="" HorizontalAlignment="Left" Height="88" VerticalAlignment="Top"
Width="476">
<RibbonGroup Header="" Height="88" Margin="0" VerticalAlignment="Top" Width="123"/>
<DocumentViewer Height="100" Width="100"/>
</RibbonTab>
</Ribbon>

</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

Now, let’s summarize the topics discussed in this chapter.


SUMMARY
In this chapter, you have learned about:
 XAML browser applications.
 Typography in WPF.
 Some WPF controls and their applications.

334
CHAPTER 13
Web, WCF, and Cloud Service

What you will learn in this chapter?


 U sing a W e b S e rvice
 U sing a W C F S e rvic e
 U sing a W C F S e rvic e
 C loud S e rvice

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.

Using a Web Service


Let’s learn the usage of Web service by creating a Web service project by performing the following
steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
Visual Studio 2012. The Start Page
appears.
2. Select FILENewWeb Site option from the menu bar.
The New Web Site dialog box appears.
Templates
3. Select the Installed Visual C#
 ASP.NET Empty Web Site option in the left pane.
4. Set the location and enter the name as Webserviceapplication in the Web location combo box to
specify the name and location for the Web application.
5. Click the OK button.
6. Right-click the application name in the Solution Explorer window and select the AddAdd New
Item option from the context menu.
The Add New Item dialog box appears.
7. Select the InstalledVisual C#Web Form option from the dialog box.
8. Click the Add button to add the Web Form in the application.
9. Right-click the application name in the Solution Explorer window and select the AddAdd New
Item option from the context menu, similar to how you have done earlier.
The Add New Item dialog box appears (Fig.ASP-13.1).
10. Select the InstalledVisual C#Web Service option from the Add New Item dialog box
(Fig.ASP-13.1).
11. Click the Add button, as shown in Fig.ASP-13.1:

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

The Add Service Referencce dialog box appears (Fig.ASP-13.3).


5. Click the Advance
15 ed button in the dialog box, as shown in Fig.ASP-13.3:

337
ASP.NET 4.5 in Simple Steps

15

 Fig. ASP-15.3

The Service Reference Setting


gs dialog box appears (Fig.ASP-13.4).
6. Click the Add Web Referencce button in the Service Reference Setting
16 gs dialog box, as shown in
Fig.ASP-13.4:

16

 Fig.ASP-13.4

The Add Web Referencce dialog box appears (Fig.ASP-13.5).


7. Click the Web services in this solutio
17 on link in the Start Browsing for Web Services page of the
dialog box, as shown in Fig.ASP-13.5:

338
Web, WCF, and Cloud Service

17

 Fig.ASP-13.5

The Web Services in this Solution page appears (Fig.ASP-13.6).


8. Click the WebService
18 e link in the Web Services in this Solution page of the dialog box, as shown in
Fig.ASP-13.6:

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

The Web page that displays the answer appears (Fig.ASP-13.9).

 Fig.ASP-13.9

21. Click the Close button[X] to close the Web page.


22. Click the Add Referencce button in the Add Web Referencce dialog box, as shown in (Fig.ASP-13.10).

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>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <asp:TextBox
ID="TextBox1" runat="server"></asp:TextBox> <br /> <br />
<asp:Label ID="Label2" runat="server" Text="Enter Second Number"></asp:Label>&nbsp;
<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.

Using a WCF Service


Creating a WCF service is easy in Visual Studio 201 12 due to its in-built support for WCF. Now, let’s perform
the following steps to create the WCF service using the template provided in Visual Studio 201
12:
1. Open Visual Studio 201
12.
2. Select FILENewWeb Sitte option from the menu bar. The New Web Sitte dialog box appears.

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

The WCFapplication is created.


6. Add the following code snippet in the Service class of the Servicce.ccs file:
public int Add(int a, int b)
{
return (a + b);
}
7. Open the Solutio
on Exploreer window and double-click the IServicce.ccs file present in the App_C
Cod
de
folder, as shown in Fig.ASP-13.13:

 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

1. Right-click the name of the application in the Solution Explore


11 er window (Fig.ASP-13.15).
2. Select the Add Service Referencce option from the context menu, as shown in Fig.ASP-13.15:
12

12

 Fig.ASP-13.15

The Add Service Referencce dialog box appears (Fig.ASP-13.16).


3. Click the Discove
13 er button to find the Service.svc WCF service (Fig.ASP-13.16).

344
Web, WCF, and Cloud Service

14. Click the Go button (Fig.ASP-13.16).


The WCF Service appears in the Services pane, as shown in Fig.ASP-13.16:

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

<%@ 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>
<center>
<asp:Label ID="Label1" runat="server" Text="Enter First number"></asp:Label>
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<br /> <br /><asp:Label ID="Label2" runat="server" Text="Enter Second Number">

</asp:Label>&nbsp;<asp:TextBox ID="TextBox2" runat="server"> </asp:TextBox> <br /><br />

<asp:Button ID="Button1" runat="server" Text="ADD" Width="99px" onclick="Button1_Click"


style="margin-top: 0px" /><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>

1. Press the F5 key to execute the application (Fig.ASP-13.18).


21
2. Enter the values in both the text boxes and click the ADD button (Fig.ASP-13.18).
22

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

Let’s discuss about the Cloud service in the following section.

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.

Let’s now learn how to create an application in the cloud environment:


1. Open Visual Studio 201
12.
2. Select FILENewProjecct option from the menu bar. The New Projecct dialog box appears
(Fig.ASP-13.19).
Templates
3. Select Installed Cloud in the New Project dialog box in the left pane (Fig.ASP-13.19).
4. Select the Windows Azure Cloud Service template in the templates pane (Fig.ASP-13.19).
5. Enter a name for the application, which in this case is MyFirstCloudApplication and specify a
location to save the application (Fig.ASP-13.19).
6. Click the OK button in the dialog box, as shown in Fig.ASP-13.19:

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

The cloud application opens.


10. Open the Default.asp
px page in the Source view and add the following code:
<asp:Content runat="server" ID="BodyContent" ContentPlaceHolderID="MainContent">
<h3>We suggest the following:</h3>
<h2><asp:Label ID="lblmsg" runat="server" Text="Label"></asp:Label></h2>
<p>&nbsp;</p>
<asp:Button ID="Button1" runat="server" Text="Click Here" OnClick="Button1_Click" />
</asp:Content>
11. Double-click the Button1 control in the Design view and add the following code in its Click event:
protected void Button1_Click(object sender, EventArgs e)
{
lblmsg.Text = "This is my First Cloud Application";
}
12. Press the F5 key to execute the application. The output of the application appears (Fig.ASP-13.21).
13. Click the Click Herre button, as shown in Fig.ASP-13.21:

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

What you will learn in this chapter?


 A S P .N E T MV C A rchite cture
 A S P .N E T MV C F ra me work
 N e w F e a ture s of A S P .N E T MV C 4
 C re a ting a n MV C A pplica tion

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.

ASP.NET MVC Architecture


Nowadays, a Web application requires interaction with different types of users with different types of
Web interfaces to fulfil the need of users. A Web application may be required to present an HTML View
to a Web user, a WML View to a wireless user, and a Form View to an administrator, as shown in
Fig.ASP-14.1:
ASP.NET 4.5 in Simple Steps

 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.

ASP.NET MVC Framework


ASP.NET MVC Framework is not a substitute for the ASP.NET Web Forms pattern. It just provides an
alternative choice to the developer while designing and developing a Web application. ASP.NET MVC
Framework enables you to achieve and maintain a clear separation of presentation layer (UI), logic,
and data access. It also facilitates a test-driven development (TDD) environment where you implement
automated unit tests which define and verify the requirements of new code before you actually write the
code itself.

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.

New Features of ASP.NET MVC 4


ASP.NET MVC 4 is the latest version of MVC and is included in ASP.NET 4.5 Framework. The new
features included in ASP.NET MVC 4 are as follows:
 Improvements in Web API:: Includes new features, such as modern HTTP programming model,
full support for routing, content negotiation, model binding and validation, filters, query
composition, improved testability, code-based configuration, improved support for IoC
containers, Self-host, creation of custom help and test pages, monitoring and diagnostics, link
generation, new Web API project template, and Scaffolding of Web API controller on the basis of
Entity Framework and model type.
 Enhancements in Default Project templates:: Specifies the enhancement of previous project
templates to modern-looking templates.
 Adaptive rendering
g: Specifies the technique due to which a template appears good in both
desktop browsers and mobile browsers without requiring any customization.
 Mobile Application project template:: Specifies the inclusion of Mobile Application project
template that is used for creating applications for mobile devices and tablet browsers.
 Display Modes feature:: Allows an application to select views depending upon the browser that is
sending the request.
 jQuerry Mobile librarry: Allows you to develop applications that can run on mobile devices and
tablet browsers.
 Task support for asynchronous controllers: Allows you to create asynchronous action methods as
single methods that return an object of type Task.
 Support for Azure Software Development Kit (SDK): Specifies that ASP.NET MVC 4 supports 1.6
and latest version of Windows Azure SDK.
 Support database migrationss: Specifies that ASP.NET MVC 4 includes Entity Framework 5 for
supporting database migrations. This feature allows you to easily develop a database schema
using a code-focused migration without modifying data in the database.
 Empty project templatte: Specifies that ASP.NET MVC 4 includes Empty project template so that
you can develop your application from scratch.

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.

Creating an MVC Application


You can create a Web application to learn the usage of MVC by performing the following steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012.
2. Select FILENewProject option from the menu bar.
The New Project dialog box appears (Fig.ASP-14.3).
TemplatesVisual C#Web option in the left pane (Fig.ASP-14.3).
3. Select the Installed
4. Select the ASP.NET MVC 4 Web Application template in the middle pane (Fig.ASP-14.3).
5. Enter FirstMvcApplication in the Name text box to specify the name of the application (Fig.ASP-14.3).
6 Enter an appropriate location for the application in the Location combo box (Fig.ASP-14.3).
7. Click the OK button, as shown in Fig.ASP-14.3:

5
6

 Fig.ASP-14.3

The New ASP.NET MVC 4 Project dialog box appears (Fig.ASP-14.4).


8. Select the InternetApplication template (Fig.ASP-14.4).

The Razor option must be selected in the View engine drop-down list.

356
Introduction to MVC

9. Click the OK button, as shown in Fig.ASP-14.4:

 Fig.ASP-14.4

10. Open the Solution Explore


er window and right-click the Modells folder (Fig.ASP-14.5).
11. Select the AddClasss option from the context menu, as shown in Fig.ASP-14.5:

11

10

 Fig.ASP-14.5

The Add New Ite


em dialog box appears.
Visual C# in the left pane and
12. Select the Installed the Class option and name it as
ClassBooks.cs in the Name text box in the dialog box.
13. Click the Add button.
14. Replace the class ClassBooks with the following code snippet in the ClassBooks.cs file to create a
class:
public class ClassBooks
{
#region properties
public string BName { get; set; }
public string BPrice { get; set; }
public string BEdition { get; set; }
public string BISBN { get; set; }
public string publisher { get; set; }
#endregion
}
15. Open the Solution Explorer window and right-click the Controllers folder (Fig.ASP-14.6).
16. Select the AddController option from the context menu, as shown in Fig.ASP-14.6:

357
ASP.NET 4.5 in Simple Steps

15

16

 Fig.ASP-14.6

The Add Controlle


er dialog box appears (Fig.ASP-14.7).
17. Enter the name of the Controlle er in the Controller Nam
me text box as BooksControlle
er
(Fig.ASP-14.7).
18. Click the Add button, as shown in Fig.ASP-14.7:

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

25. Open the Solution Explore


er window and right-click the Bookks folder.
26. Select the AddVie
ew option from the contexxt menu.
The Add Vie
ew dialog box appears (Fig.ASP-14.9).
27. Enter Inde
ex in the Vie
ew nam
me text box (Fig.ASP-14.9).
28. Select the Create a strongly-typed vie
ew check box (Fig.ASP-14.9).
29. Select class name in the Modaal class drop-down list (Fig.ASP-14.9).
30. Click the Add button in the Add Vie
ew dialog box, as shown in Fig.ASP-14.9:

27

28
29

30

 Fig.ASP-14.9

31.. Replace the code in the Index.cshtm


ml page with the following code:
@model FirstMvcApplication.Models.ClassBook
@{
ViewBag.Title = "Index";
}
<h2>Asp.Net 4.5</h2>
<fieldset>
<legend>ClassBook</legend>
<div class="display-data">
<table border="1" style=" background-color:#0094ff">
<tr>
<td> Book Name </td>
<td> @Html.DisplayFor(model => model.BName)</td>
</tr>
<tr>
<td>Book Price</td>

359
ASP.NET 4.5 in Simple Steps

<td> @Html.DisplayFor(model => model.BPrice)</td>


</tr>
<tr>
<td>Book Edition</td>
<td> @Html.DisplayFor(model => model.BEdition)</td>
</tr>
<tr>
<td>ISBN Number</td>
<td> @Html.DisplayFor(model => model.BISBN)</td>
</tr>
<tr>
<td>Publisher Name</td>
<td> @Html.DisplayFor(model => model.publisher)</td>
</tr>
</table>
</div>
</fieldset>
<p>
@Html.ActionLink("Edit", "Edit", new { /* id=Model.PrimaryKey */ }) |
@Html.ActionLink("Back to List", "Index")
</p>
32. Press the F5 key to execute the application to view the output (shown in Fig.ASP-14.10).
33. Replace the URL as http://localhost:19322/Bookks, as shown in Fig.ASP-14.10:

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

What you will learn in this chapter?


 D e ploying A S P .N E T W e bsite by U sing the C opy W e b S ite U tility
 P ublishing a W e bsite
 U sing X C O P Y D e ploy me nt
 D e ploying by U sing O ne -C lick P ublish
 Insta llS hie ld Limite d E dition for V isua l S tudio 2012

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.

Deploying ASP.NET Website by Using the Copy Web Site Utility


Copy Web Site is a utility in ASP.NET used to deploy the Web application by copying its content files to
the destination. This option of deployment consists of the following main entities:
ASP.NET 4.5 in Simple Steps

 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

The Connections page appears (Fig.ASP-15.2).

362
Web Application Deployment

7. Click the Connecct button, as shown in Fig.ASP-15.2:

 Fig.ASP-15.2

The Open Web Site dialog box appears (Fig.ASP-15.3).


This dialog box has the following tabs:
 File System
m: Used for copying the Web site files and contents to any local drives.
 Local Internet Information Services (IIS)): Used to select the Local IIS directory to publish the
Web site locally.
 FTP Sitee: Used to connect to a different computer connected on the local network on which
file transfer tasks are accomplished with the FTP standard.
 Remote Sitte: Used to connect to any remote HTTP or FTP server.
8. Click the FTP Site e tab on the left pane (Fig.ASP-15.3).
9. Enter the Internet Protocol (IPP) address of the remote server in the Server text box (Fig.ASP-15.3).
10. Enter the port number in the Porrt text box (Fig.ASP-15.3).
11. Enter the directory name in the Directorry text box (Fig.ASP-15.3).
12. Select the Passivve mode check box (Fig.ASP-15.3).
13. Select the Anonymou us Login check box (Fig.ASP-15.3).
14. Click the Ope
en button, as shown in Fig.ASP-15.3:

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

The Publish Web Sitte dialog box appears (Fig.ASP-15.6):


7.. Set the path in the Target location text box using the […] ellipse button (Fig.ASP-15.6).
8. Click the OK button, as shown in Fig.ASP-15.6:

 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

Let’s now discuss about XCOPY deployment.

Using XCOPY Deployment


XCOPY is used to deploy an application by copying a set of files to a folder on the target computer and
then executing the application on the client. Regardless of the number of assemblies, if the files are
copied to the same folder, the application is executed without editing the configuration settings and
registry values. In other words, the XCOPY deployment technique deploys a fully functional application
by simply copying the assemblies to the target computer.

366
Web Application Deployment

Table 15.1 lists some noteworthy options of the XCOPY command:


Table 15.1: Noteworthy Options of the XCOPY Command
Optio
on Descriptio
on
/E Copies directories, subdirectories, and files including empty ones from directories to another
directory
/S Copies directories, subdirectories, and files excluding empty ones
/K Copies attributes and the normal XCOPY will reset read-only attributes
/R Overwrites read-only files
/O Copies security-related information such as file ownership and Access Control List (ACL)
information
/H Copies directories and subdirectories including hidden and system files
/I Assumes the destination as a directory and creates if it does not exist
/C Continues copying even if an error occurs in 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.

Deploying by Using One-Click Publish


ASP.NET 4.5 helps you to publish a Web application to a remote server by using the IIS remote
management service. It helps you to create a publish profile for hosting account, testing servers, and
staging servers. The credentials of a user are saved securely in the profile. It also allows you to deploy
the application to servers by using the publish drop-down list in the Web one-click publish toolbar.
Let’s learn the deployment of an application by performing the following steps:
All Programs
1. Click Start Microsoft Visual Studio 2012
 Visual Studio 2012.
2. Select the FILENewProject option from the menu bar.
The New Project dialog box appears.
Templates
3. Select the Installed Visual C#Web option in the left pane.
4. Select the ASP.NET Web Form Application option in the middle pane.
5. Enter Oneclickpublishapplication in the Name 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.
8. Select the New
w option from the publish drop-down list of the Web One Click Publish toolbar, as
shown in Fig.ASP-15.9:

 Fig.ASP-15.9

368
Web Application Deployment

The Publish Web dialog box appears (Fig.ASP-15.10).


9. Select the Fille Syste
em option from the Publissh Method drop-down list (Fig.ASP-15.10).
10. Enter or Selecct the Target Locatio
on in the text box (Fig.ASP-15.10).
11. Enter the Destination UR RL in the text box (Fig.ASP-15.10).
12. Click the Publissh button, as shown in Fig.ASP-15.10:

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.

InstallShield Limited Edition for Visual Studio 2012


InstallShield Limited Edition for Visual Studio replaces the functionality provided by Visual Studio
Installer. It is a powerful and easy-to-use software solution for creating Windows installation packages.
With automated tools to productize, bundle, and install, InstallShield makes it easy for developers and
clients to deploy and manage applications by providing a modern installation experience. In other
words, the InstallShield Limited Edition for Visual Studio 2012 offers a subset of excellent and simple
functionalities for creating setup and deployment packages.
Let’s first create a Windows based application and then learn how to create setup of the application in
Visual Studio 2012 using the InstallShield Limited Edition.
1. Open the Visual Studio 201
12 IDE.
2. Select FILLE  New  Project option. The New Project dialog box appears (Fig.ASP-15.12).
3. Select InstalledTemplatesVisual C# option in the left pane. Then,, Select Windows Forms
Application template from the middle pane in the New Project dialog box(Fig.ASP-15.12).
4. Enter the name and location in Name text box and Location combo box and click the OK button.
In our case we have named our application as MyWindowsApp, as shown in Fig.ASP-15.12.

 Fig.ASP-15.12

5. Add a Label, a Textbox and a Button control to Form1 of MyWindowsApp.


6. Set the text properties of Labell and Button controls to Enter Message and Show Message Box
respectively.
7. Double-click the Button1 control and add the following line of code to button1_Click event.
MessageBox.Show(textBox1.Text);
8. Right-click the MyWindowsApp project node in Solution Explorer window and select the build
option from the context menu to build the application.

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

Add New Project dialog box appears (Fig.ASP-15.14).


 Other Project Types  Setup and Deployment option from the left pane and
10. Select Installed
InstallShield Limited Edition Setup and Deployment template from the middle pane
(Fig.ASP-15.14).
11. Enter the name in Namee text box and click OK button to create the setup project for MyWindowsApp.
In our case we have named the setup project as WindowsAppSetup (Fig.ASP-15.14).
12. Click the OK button, as shown in Fig.ASP-15.14:

10

11
12

 Fig.ASP-15.14

The Project Assistant window appears for MyWindowsApp project (Fig.ASP-15.15).


13. Click the Application Information icon on the Project Assistant window (Fig.ASP-15.15):

371
ASP.NET 4.5 in Simple Steps

 Fig.ASP-15.15

The Application Informatio


on page appears, as shown in Fig.ASP-15.16:

 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

The Application File


es page appears. On this page, you can add the primary output of
MyWindowsAp pp project to the WindowsAppSetu
up project (Fig.ASP-15.19).
17. Click the Add Project Outputts button on Application File
es page, as shown in Fig.ASP-15.19:

373
ASP.NET 4.5 in Simple Steps

17

 Fig.ASP-15.19

The Visual Studio Output Selecto


or dialog box appears, as shown in Fig.ASP-15.20:

 Fig.ASP-15.20

18.. Select the Primary outpu


ut check box in the Visual Studio Output Selecto
or dialog box
(Fig.ASP-15.21).
19.. Click the OK button to add the primary output of the MyWindowsAp
pp project to the
WindowsAppSetu
up project (Fig.ASP-15.21).
20.. Click the Application Shortcutts icon, as shown in Fig.ASP-15.21:

374
Web Application Deployment

19

20

 Fig.ASP-15.21

The Application Shortcutts page appears (Fig.ASP-15.22).


21
1. Click the New button on Application Shortcutts page, as shown in Fig.ASP-15.22:

21

 Fig.ASP-15.22

A Browse for a Destination Fille dialog box appears, as shown in Fig.ASP-15.23:

375
ASP.NET 4.5 in Simple Steps

 Fig.ASP-15.23

2. Select the MyWindowsApp.Primaryoutput file located inside ProgramsFilesFolder Kogent


22
Learning Solution  MyProduct Name folder (Fig.ASP-15.24).
23. Click the Open button, as shown in Fig.ASP-15.24:

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

The Application Registrry page appears (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

29.. Right-click on the WindowsAppSetuup project in the Solution Explore


er window and select the Builld
option from the context menu, as shown in Fig.ASP-15.28:

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

You might also like