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

aspnet

The document outlines the syllabus for the B.C.A III Year V Semester course on Programming using ASP.NET, detailing various units covering topics such as ASP.NET overview, web forms, validation controls, data presentation, and error handling. It emphasizes the advantages of ASP.NET over traditional ASP, including improved deployment, application structure, and state management. Additionally, it provides a comprehensive breakdown of course content, including short questions and answers related to key concepts in ASP.NET.

Uploaded by

arsalaan272158
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

aspnet

The document outlines the syllabus for the B.C.A III Year V Semester course on Programming using ASP.NET, detailing various units covering topics such as ASP.NET overview, web forms, validation controls, data presentation, and error handling. It emphasizes the advantages of ASP.NET over traditional ASP, including improved deployment, application structure, and state management. Additionally, it provides a comprehensive breakdown of course content, including short questions and answers related to key concepts in ASP.NET.

Uploaded by

arsalaan272158
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 136

AS PER (CBCS) LATEST SYLLABUS

B.C.A
(BACHELOR OF COMPUTER APPLICATIONS)
III YEAR V SEMESTER

PROGRAMMING USING
ASP.NET
P.VIVEKANAND.
LECTURER IN COMPUTER SCIENCE
GIRIRAJ GOVERNMENT COLLEGE, NIZAMABAD.

© Copyrights Reserved with the Publisher


Despite of Every Effort Taken The Book Without Errors, Some Errors Might Have Crept In. We Do Not
Take any Legal Responsibility For Such Errors and Omissions. However, If They Are Brought To Our Notice,
They Will Be Corrected In The Next Edition.

S.V. PUBLICATIONS
HYDERBAD.
PREFACE
ASP.NET is a part of the .NET framework. As a programmer, you interact with it
by using the appropriate types in the class library to write programs and design web
forms. When a client requests a page, the ASP.NET service runs (inside the CLR
environment), executes your code,and creates a final HTML page to send to the client.

To understand ASP.NET's features, it helps to understand ASP's limitations. In


other words, before you can understand the .NET solution, you need to understand the
problems developers are struggling with today.
 Scripting limitations ASP applications rely on VBScript, which suffers from a
number of limitations. To overcome these problems, developers usually need to
add separately developed components, which add a new layer of complexity.
In ASP.NET, web pagesare designed in a modern .NET language, not a
scripting language.
 Headaches with deployment and configuration Because of the way COM and
ASPwork, you can't easily update the components your web site uses. Often,
you need to manually stop and restart the server, which just isn't practical on a
live web server.
 Changing configuration options can be just as ugly. ASP.NET introduces a
slew of new features to allow web sites to be dynamically updated and
reconfigured.
 No application structure ASP code is inserted directly into a web page along
with HTML markup. The resulting tangle has nothing in common with today's
modern, object-oriented languages. As a result, web form code can rarely be
reused or modified without hours of effort.
 State limitations One of ASP's strongest features is its integrated session state
facility. However, session state is useless in scenarios where a web site is hosted
by several separate web servers. In this scenario, a client might access server B
while itssession information is trapped on server A and essentially abandoned.
ASP.NET corrects this problem by allowing state to be stored in a central
repository: either a separate process or a database that all servers can access.

A u t h or ….
Syllabus
Unit – I
Asp.Net Overview- Introduction to ASP.Net, Introduction to web Applications
with web servers, web server role-IIS,APACHE etc, Web-browsers, web
support languages, understanding ,http, TCP/IP role in web
development.ASP.Net role-ASP.Net framework, Name spaces ,New scenario in
development process with IDE.

Unit – II
ASP.Net web forms-Introduction to web forms, page directives and its use,
separating code & design, new code behind techniques, ASP.Net server
controls-Working with server controls, applying styles to controls, themes,
skins etc.

Unit – III
Web form validation controls-Required field validation Control Computer
Validation Control, Custom Validation Control, Group Validation and
Accounting Validation.ADO.Net Database Services- Overview of ADO.Net,
XML, XML to HTML, XML & Databases XML Support in .Net retrieve data
with datasets & Data Adapters.

Unit – IV
Presenting Data Using ASP.Net-Bound Controls- Data Source Controls,
Repeater and its uses, Data list control, data grid control view and its
importance, form view detail’s view, list view. User controls- Adding member
to user controls, registering user control, properties & methods ,Dynamically
loading user controls, master pages.

Unit – V
ASP .Net Error Handling & Debug- Error handling & .Net returns, Structured
Error handling, Catching General Exception, Catching Specific Exceptions,
Throwing Exception Custom Exceptions ,Page level Error handling,
Application level Error Handling. Configuring ASP.Net- Web machine
Configuration, Global Assembly cache, working with Assembling information,
Managing Application State, Http handlers, Applications & Server Events.
Contents
Short Answers (Part – A) 1 – 10

UNIT-I
Asp.Net Overview
1.1 Introduction to ASP.Net 11 – 12
1.2 Introduction to Web Application with Web Servers 12 – 15
1.2.1 Web Server Roles 15 - 16
1.2.2 IIS (Internet Information Services) 16 - 18
1.2.3 Apache Web Server 18 - 19
1.3 Web Browsers 19 - 21
1.3.1 Web Support Languages 21 – 23
1.4 HTTP 23 – 24
1.5 TCP/IP Role in Web Development 24 – 27
1.6 ASP.Net Role 27 - 31
1.6.1 New scenario in development process with IDE 31 – 32

UNIT-II
Asp.Net Web Forms
2.1 Introduction to Web forms 33 – 34
2.2 Page Directives and Its Uses in Asp.net 34 – 36
2.3 Separating Code & Design 37 - 38
2.3.1 New Code Behind Techniques 38 – 39
2.4 ASP.Net Server Controls -Working 39 – 40
2.4.1Applying Styles to Controls 41 - 42
2.4.2 Themes & Skins 43 – 44
UNIT-III
Web Form Validation Control
3.1 Web form validation controls 45 – 47
3.2 Custom Validator Control 48
3.3 Group Validation and Accounting Validation 48 – 51
3.4 ADO.Net Database Services 51 - 53
3.4.1 Overview of ADO.Net 54 - 57
3.4.2 XML 57 – 61
3.5 XML to HTML 61 – 65
3.6 XML & Databases 65 – 67
3.7 XML Support in .Net retrieve data with datasets & Data Adapters 67 – 69

UNIT-IV
Presenting Data Using ASP.Net
4.1 Bounded Controls 70 – 73
4.2 Repeater and its uses 73 – 75
4.3 Data List Control 75 – 83
4.4 User Controls 83 – 84
4.5 Adding member to user controls 84 – 85
4.6 Registering User Control 85 - 86
4.7 Properties & Methods 86 – 88
4.8 Dynamically Loading User Controls 88 – 90
4.9 Master Pages 90 – 92

UNIT-V
Asp.Net Error Handling & Debug
5.1 ASP .Net Error Handling & Debug 93 – 96
5.2 Error handling & .Net returns 96 – 98
5.3 Structured Error Handling 98 – 100
5.4 Catching General Exception 100 – 102
5.5 Catching Specific Exceptions 102 – 104
5.6 Throwing Exception Custom Exceptions 105 – 106
5.7 Page level Error handling 106 – 107
5.8 Application level Error Handling 108 - 109
5.9 Configuring ASP.Net and Web machine 109 – 116
5.10 Global Assembly Cache 116 – 118
5.11 Working with Assembling Information 118 - 119
5.12 Managing Application State 119 - 121
5.13 Http Handlers 121 – 123
5.14 Applications & Server Events 123 – 126
Multiple Questions
Fill in the Blanks 127 - 130
Important Questions
BCA III YEAR - V SEM 1

PART
SHORT QUESTIONS
a
Q1. What is ASP.NET?
Ans:
ASP.NET is a server-side technology used for developing dynamic websites
and web applications on the internet. It also produces data-driven web
applications.

Microsoft released ASP.NET in 2002 to build dynamic websites and web


applications using the .NET framework.

Q2. What is the ASP.NET Life Cycle, and list the types of Life Cycle?
Ans:
When ASP.NET pages run, it goes through several steps of the life cycle, which
performs a series of actions like initialization, running, restoring, and rendering.

Life Cycle is classified into two categories.


1. Application Life Cycle: The user requests for accessing the application.
2. Page Life Cycle: Page Life Cycle has phases like initialization, restoring,
execution, and page rendering.

Q3. What is Common Language Runtime (CLR)?


Ans:
CLR is the basic and Virtual Machine component of the .NET Framework. It is
the run-time environment in the .NET Framework that runs the codes and helps in
making the development process easier by providing various services such as
remoting, thread management, type-safety, memory management, robustness, etc.
Basically, it is responsible for managing the execution of .NET programs regardless
of any .NET programming language. It also helps in the management of code, as
code that targets the runtime is known as the Managed Code, and code that doesn‟t
target to runtime is known as Unmanaged code.

Q4. Write down the features of ASP.NET?


Ans:
There are a lot of reasons which make ASP.NET popular among developers.
Some reasons are listed below:
1. Extending .NET Framework: ASP.NET is a subset of the .NET Framework
as it extends the .NET Framework with some libraries and tools to develop
web apps. The thing that it adds to the .NET Framework is Libraries for

S V PUBLICATIONS
2 BCA III YEAR - V SEM

common web patterns like MVC, Editor Extensions, the base framework to
process the web requests, and web-page templating syntax like Razor, etc.
2. Performance: It is faster than the other web frameworks available in the
market.
3. Backend Code: With the help of ASP.NET you can write the backend code
for data access and any logic in C#.
4. Dynamic Pages: In ASP.NET, Razor provides the syntax for developing
dynamic web pages with the help of C# and HTML. ASP.NET can be
integrated with JavaScript and it also includes the frameworks like React
and Angular for the SPA(Single Page Application.)
5. Supporting different OS: You can develop and execute ASP.NET apps on
Windows, Linux, Docker, and macOS. The Visual Studio provides the tools
to build .NET apps with different OS.

Q5. Write a step for Request Flow in ASP.NET MVC framework?


Ans:
The sequence for Request Flow in ASP.NET MVC is as follows:
 Request: In this step firstly request is received. After that, in the
Global.asax file, route objects are added to the Route table object.
 Routing: At the second step routing is performed. After the application gets
from the client, it uses URL Routing Module to deal with the request. The
Route Table guides URLs to handlers. A routing is coordinating with a
system that matches with the request‟s URL against the URL patterns which
are available in the Route Table. The Routing engine diverts the request to
the relating IRouteHandler when the match is found in the pattern.
Assuming relating mentioned URL is not found in the routing table, it will
return a 404 HTTP status code.
 MVC Handler: A RouteHandler responsible for deciding the HTTP handler
that will serve the request, according to the received RequestContext.
 Controller: In this step, the controller decides which action method is to be
executed.
 Action Executed: After the controller gets instantiated ActionInvoker will
determine which Action method needs to execute.
ActionNameSelectorAttribute and ActionMethodSelectorAttribute methods
used to select action method. The action method receives user input then
executes the result and returning a result type to view.

Q6. What is IIS? And why do you use it?


Ans:
Internet Information Server (IIS) is the most popular web server used to host
and provide internet-based services to ASP.NET and ASP Web applications.

S V PUBLICATIONS
BCA III YEAR - V SEM 3

IIS has its own process engine to handle the requests. Using an IIS computer can
work as a web server, and provides functionality to deploy ASP.NET Web
applications. It is also responsible for providing responses to the requests made by
the users.

Q7. List the components of ASP.NET.


Ans:
ASP.NET provides data-driven web applications on the internet using various
components.
They are:
 Common Language Runtime
 Language
 Library
 Common Type System
 Windows Forms

Q8. What is Server control?


Ans:
ASP.NET has Server Controls features, Which provide facilities to manipulated
values of the controls on the Server-Side. This is especially helpful while we want to
create validating and dynamically web forms.

Q9. Explain the Global.asax file?


Ans:
Global.asax is an optional file that resides in the application root directory. This
file is used to handle higher-level application events, for example,
Application_Start, Application_End, Session_Start, Session_End, and so on. It is
additionally known as the ASP.NET Application File..Global.asax contains a Class
representing your application as a whole. At run time, this file is parsed and
compiled into a dynamically created .NET Framework class derived from the HTTP
Application base class. We can convey this file as an assembly in the \bin catalog of
an ASP.NET application. The Global.asax record itself is designed so that if a user
demands the document, the request is denied. External users can‟t download or see
the code written inside it.

Q10. Explain the difference between Web.config and Machine.config file?


Ans:
There is some key difference between Web.config and Machine.config file
below:
 The machine.config record is the master configuration document on your
framework with a lot of default settings.And Web.config is the file for the

S V PUBLICATIONS
4 BCA III YEAR - V SEM

local settings to be applied for a website which store configuration


information in XML format.
 The settings of Machine.config file are applied to the entire asp.net
applications on your server while the settings made in the Web.config file
are applied to that specific web application only.
 Each .NET Framework form has only one machine.config file,
simultaneously, each web application has its own web.config file.
Directories inside a web application can have web.config files as well.
 The machine.config is shared values among numerous applications on the
server, while Web.config documents contain application explicit things, for
example, database connection strings.
 Suppose if you want any improvements in the web.config, then the web
application will promptly load the changes but in the machine.config case
you should restart the application.
 The machine.config document will automatically introduce when you
install Visual Studio.Net and it resides in the
c:\windows\microsoft.net\framework\version\config folder whereas
web.config will automatically be made when you make an ASP.Net web
application project.
 Machine.config is the design configuration file for all the applications in the
IIS, but Web. config is a configuration file for a specific application.

Q11. What are web controls in ASP.NET?


Ans:
Web server controls are powerful than HTML server-side controls. The only
difference is that they must have the runat = ”server” attribute set. This attribute
makes the control available for server-side programming. Each ASP.NET Server
Control is capable of exposing an object model containing properties, methods, and
events. This object model can be utilized by the ASP.NET developers to modify and
interact with the Web page. Web controls contain all basic controls of HTML
controls as well as some new controls like as DataGrid, DataList, and Calendar.

WEB CONTROL DESCRIPTION


Label Represents a label control
ListBox Represents a list box control
CheckBox Represents a Check box control
Calendar Represents a calendar control
ImageButton Represents an image button control
TableCell Represents a table cell
Panel Represents a panel control

S V PUBLICATIONS
BCA III YEAR - V SEM 5

Q12. Describe login Controls in ASP?


Ans:
The ASP.NET supports robust login controls for web-based application which
does not require any program coding. These login controls coordinate with
ASP.NET participation and form authentication to help automated client
verification for a server webpage. By default, the ASP.NET login controls work in
plain text over HTTP. The ASP.NET supports different types of Login Controls like:
 Login Control
 LoginView Control
 LoginStatus Control
 LoginName Control
 PasswordRecovery Control
 CreateUserWizard Control
 ChangePassword Control

Q13. Explain ADO.net?


Ans:
ASP.NET has introduced the next generation of ADO known as ADO.NET with
respect to data access. ADO.NET places more emphasis on disconnected recordsets
by employing XML as a medium of communication between these record sets and
the DataStore.ADO.NET is the latest of the database access technologies that began
with the Open Database Connectivity (ODBC) application programming interface
(API). Microsoft introduced open database connectivity with the promise of
creating a singular common access methodology for databases. ODBC has come a
long way since those early days. Almost every major database in use today
supports ODBC drivers, and third-party developers provide optimized driver
versions. The primary focus of the ODBC is to provide a consistent interface to
database data sources.

Q14. List advantages of using HTML Server controls.


Ans:
HTML Server Controls are the standard HTML controls used to enable server-
side processing.

Some advantages of using HTML Server Controls are:


 HTML Server Control does not possess any mechanism to identify the
capabilities of a client browser.
 Coding can be easy by adding the runat=”server” attribute.
 Controls can interact with the Client-Side Scripting.

S V PUBLICATIONS
6 BCA III YEAR - V SEM

Q15. List all templates of the Repeater control.


Ans:
1. ItemTemplate
2. AlternatingltemTemplate
3. SeparatorTemplate
4. HeaderTemplate
5. FooterTemplate

Q16. What are the 6 different validation controls provided by ASP.NET?


Ans:
 RequiredFieldValidator: Checks whether a control contains data
 CompareValidator: Checks whether an entered item matches an entry in
another control
 RangeValidator: Checks whether an entered item is between two values
 RegularExpressionValidator: Checks whether an entered item matches a
specified format
 CustomValidator: Checks the validity of an entered item using a client-side
script or a server-side code, or both
 ValidationSummary: Displays validation errors in a central location or
display a general validation error description

Q17. Explain in simple steps how to use validation controls?


Ans:
1. Draw a validation control on a Web form and set its ControlToValidate
property to the control you want to validate.
2. If you‟re using the CompareValidator control, you also need to specify the
ControlToCompare property.
3. Set the validation control‟s ErrorMessage property to the error message you
want displayed if the control‟s data is not valid.
4. Set the validation control‟s Text property if you want the validation control
to display a message other than the message in the ErrorMessage property
when an error occurs. Setting the Text property lets you briefly indicate
where the error occurred on the form and display the longer ErrorMessage
property in a ValidationSummary control.
5. Draw a ValidationSummary control on the Web form to display the error
messages from the validation controls in one place.
6. Provide a control that triggers a postback event. Although validation occurs
on the client side, validation doesn‟t start until a postback is requested.
Q18. List and what are CompareValidator Control
Ans:
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.

S V PUBLICATIONS
BCA III YEAR - V SEM 7

It has the following specific properties:


Properties Description
Type It specifies the data type.
ControlToCompare It specifies the value of the input control to compare with.
ValueToCompare It specifies the constant value to compare with.
It specifies the comparison operator, the available values
Operator are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

Q19. What does Validation Groups mean?


Ans:
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation separately
for separate group. This kind of situation is handled using validation groups.

To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting their ValidationGroup
property.

Q20. What are Master Pages in ASP.NET?


Ans:
Master Pages provide a template for other pages in an ASP.NET application.
They define a consistent layout and structure, allowing content pages to focus on
specific functionality while inheriting the common elements from the master page.
This promotes consistency and reduces code duplication.

Q21. What is Repeater Control?


Ans:
Repeaters are data-bound controls. Data binding controls are container controls.
Create a link between the data source and the presentation UI to display the data.
Repeater controls are used to display a repeating list of items.

The main use of repeater controls is to display a repeating list of items bound to
the control. Repeater controls are faster and lighter for displaying data than
GridView or DataGrid. Repeater controls allow you to view your data in a custom
format. The main drawback of repeater controllers is that they do not support
paging and sorting.

Q22. What are the 3 approaches to handle exceptions in a Web application?


Ans:
1. Use exception-handling structures to deal with exceptions within the scope
of a procedure. This technique is called structured exception handling (SEH)
in the Visual Studio .NET documentation.

S V PUBLICATIONS
8 BCA III YEAR - V SEM

a. try
b. catch
c. finally
2. Use error events to deal with exceptions within the scope of an object.
a. Page_Error
b. Global_Error
c. Application_Error
3. Use custom error pages to display informational messages for unhandled
exceptions within the scope of a Web application.

Q23. How do you raise an exception?


Ans:
Use the throw keyword to raise an exception. Use this keyword within your
exception-handling structure to immediately pass control flow to the catch
statement.

Will the following code block compile?


try
{
throw new System.IO.FileNotFoundException();
}
catch (Exception E)
{
Response.Write(E.Message);
}
catch (System.IO.FileNotFoundException FNFE)
{
Response.Write(FNFE.Message);
}

Q24. What is the difference between custom controls and user controls?
Ans:
User Control Custom Control
User controls are created just like a A custom control is one that is made or
web form. They make use of the created by the programmer to serve the
existing controls to define their business needs, by extending the functionality
own logic. of existing controls.
The creation of custom control is not easy as
We can User control easily.
compare to user control
These control do not run on their
While these control can run on their own dl.
own dll.
We can not add to the toolbox. While we can add to the toolbox.we

S V PUBLICATIONS
BCA III YEAR - V SEM 9

User Control Custom Control


This control is not flexible. This control is more flexible.
We can not call or use a single copy of this
Once we created a single copy of
control in different applications. For this, we
this control, we can use this copy
need to create a control for each and every
to different projects as well.
application.

Q25. Describe the various ways to handle exceptions in ASP.NET Web Forms
applications.
Ans:
In ASP.NET Web Forms applications, exceptions can be handled at various
levels to ensure proper error handling, logging, and user experience.

Global Exception Handling:


 Provides a centralized way to handle exceptions throughout the application.
 The Application_Error event in the Global.asax file can be used to catch
unhandled exceptions and perform error logging, notifying administrators,
or displaying a custom error page to the user.
 Global exception handling should be used as a catch-all mechanism for
unhandled exceptions that are not caught at the page or control levels.
Page-Level Exception Handling:
 Suitable for handling exceptions specific to a single page.
 The Page_Error event is used to handle exceptions that occur within a
specific page‟s execution.
 Page-level exception handling allows for more detailed error messages or
recovery actions for particular scenarios tied to a specific page.
Control-Level Exception Handling:
 Appropriate for handling exceptions that occur within a specific control,
like a user control, custom control, or grid view.
 Exceptions can be captured and handled within the control‟s event
handlers, such as click events or data binding events.
 Control-level exception handling can provide more granular error messages
or actions relevant to the control‟s operation.

Q26. What is the role of the HttpHandlers and HttpModules in an ASP.NET Web
Forms.
Ans:
HttpHandlers and HttpModules are two components in the ASP.NET Web
Forms pipeline that allow developers to intercept and process HTTP requests and
responses.

HttpHandlers:
 Act as the endpoint that processes an HTTP request and generates the final
response.

S V PUBLICATIONS
10 BCA III YEAR - V SEM

 Each handler is associated with specific file types or URL patterns.


 Custom HttpHandlers can be created to process specific types of requests,
such as generating dynamic images or processing custom file formats.
HttpModules:
 Intercept and modify HTTP requests and responses at various stages of the
request pipeline.
 Allow developers to implement custom logic, such as authentication,
logging, error handling, or modifying the request/response headers.
 Multiple HttpModules can be chained together to perform different tasks in
the request pipeline.

Q27. Describe dynamic data binding and templated controls in ASP.NET Web
Forms.
Ans:
Dynamic data binding and templated controls in ASP.NET Web Forms allow
developers to create more advanced user interfaces for displaying and
manipulating data, providing greater control over the presentation and behavior of
data-bound content.

Dynamic Data Binding:


 Refers to the process of binding data from a data source, such as a database,
XML file, or object model, to UI elements on a page at runtime.
 Data-binding expressions can be used to bind properties of controls (such as
Text, ImageUrl, or Visible) to fields from the data source.
 Supports two-way data binding, allowing user changes to be automatically
synchronized with the data source.
Templated Controls:
 Controls that allow developers to define customizable templates for
different parts of the control, which can be modified to match the desired
appearance and behavior of the data-bound content.
 Examples of templated controls include Repeater, DataList, GridView,
FormView, and DetailsView.
 Templates can include static HTML, server controls, and data-binding
expressions to create a flexible and customizable UI.

S V PUBLICATIONS
BCA III YEAR - V SEM 11

Asp.Net Overview
UNIT Asp.Net Overview- Introduction to ASP.Net, Introduction to web
Applications with web servers, web server role-IIS,APACHE etc,

I Web-browsers, web support languages, understanding ,http, TCP/IP


role in web development.ASP.Net role:-ASP.Net framework, Name
spaces ,New scenario in development process with IDE.

1.1 Introduction to ASP.Net

Q1. What is ASP.NET? What is the ASP.NET version?


Ans:
ASP.Net is a web development platform provided by Microsoft. It is used for
creating web-based applications. ASP.Net was first released in the year 2002.

The first version of ASP.Net deployed was 1.0. The most recent version of
ASP.Net is version 4.6. ASP.Net is designed to work with the HTTP protocol. This
is the standard protocol used across all web applications.

ASP.Net applications can also be written in a variety of .Net languages. These


include C#, VB.Net, and J#. In this chapter, you will see some basic fundamental of
the .Net framework.

The full form of ASP is Active Server Pages, and .NET is Network Enabled
Technologies.

ASP.NET Core Version History


Microsoft launched ASP.NET web framework along with .NET Framework 1.0
in 2002. It was designed to run on Windows platform.

In 2016, Microsoft launched ASP.NET Core framework which can run on


Windows, Mac, and Linux using .NET Core framework. It had many advantages
over traditional ASP.NET framework.

The next version of ASP.NET Core after version 3.1 was named as ASP.NET 5
which is unified framework for all types of application. So, ASP.NET 5 and later
versions are ASP.NET Core framework only. They just named back to original
name.

S V PUBLICATIONS
12 BCA III YEAR - V SEM

The .NET 5 includes core libraries of ASP.NET 5 framework so you don't need
to install ASP.NET 5 separately than .NET 5.

Version Visual Studio Release Date End of Support


ASP.NET 7 - Latest Visual Studio 2022 Nov 8, 2022 May 14, 2024
Version v17.4
ASP.NET 6 (LTS) Visual Studio 2022 Nov 9, 2021 Nov 12, 2024
ASP.NET 5 Visual Studio 2019 Nov 10, 2020 May 10, 2022
ASP.NET Core 3.1 (LTS) Visual Studio 2019 Dec 3, 2019 Dec 13, 2022
ASP.NET Core 3.0 Visual Studio 2019 Sep 23, 2019 Mar 3, 2020
ASP.NET Core 2.1 (LTS) Visual Studio 2017, May 30, 2018 Aug 21, 2021
2019
ASP.NET Core 2.0 Visual Studio 2017, Aug 14, 2017 Oct 1, 2018
2019
ASP.NET Core 1.0 Visual Studio 2017 Jun 27, 2016 Jun 27, 2019

1.2 Introduction to Web Application with Web Servers

Q2. What is a web application and web server?


Ans:
Web Server
A web server is a computer program that distributes web pages as they are
requisitioned. The basic objective of the web server is to store, process and deliver
web pages to the users. This intercommunication is done using Hypertext Transfer
Protocol (HTTP). These web pages are mostly static content that includes HTML
documents, images, style sheets, test etc. Apart from HTTP, a web server also
supports SMTP (Simple Mail transfer Protocol) and FTP (File Transfer Protocol)
protocol for emailing and for file transfer and storage.

The Web Server is requested to present the content website to the user‟s
browser. All websites on the Internet have a unique identifier in terms of an IP
address. This Internet Protocol address is used to communicate between different
servers across the Internet.

Generally, web servers are used by web hosting companies and professional
web app developers. But, actually anyone who satisfies one of the below category
can use it-
 One who owns a website (to make the local copy on their system resemble
what is on internet).
 One who wants to use server-side technologies, such as, PHP or
ColdFusion, can also use the web server.

S V PUBLICATIONS
BCA III YEAR - V SEM 13

Examples: Apache Web Server, IIS Web Server, Nginx Web Server,
LiteSpeed Web Server, Apache Tomcat, Node. js, Lighttpd.

Web Server Architecture


Web server architecture refers to the structure and design of web servers,
outlining how they handle incoming requests and deliver web content. There are
two main approaches to web server architecture:

Single-Tier (Single Server) Architecture:


In a single-tier architecture, a single server is responsible for both processing
requests and serving web content. This is suitable for small websites or applications
with low traffic. However, it has limitations in terms of scalability and fault
tolerance. If the server goes down, the entire service becomes unavailable.

Multi-Tier (Load-Balanced) Architecture:


In a multi-tier architecture, multiple servers are used to distribute the workload
and ensure high availability. This approach often involves load balancers that
evenly distribute incoming requests across a cluster of web servers. Each server can
serve web content independently, and if one server fails, the load balancer redirects
traffic to healthy servers, ensuring uninterrupted service.

Application Server:
An application server is a software framework that provides a runtime
environment in which applications (software programs) can run, handle business
logic, and interact with databases.

S V PUBLICATIONS
14 BCA III YEAR - V SEM

Functionality
Dynamic Content Processing: Application servers process dynamic content,
generate web pages on the fly, and execute server-side scripts (such as PHP,
Python, and Java).Database Interaction: They connect with databases, retrieve data,
and send it back to the client as part of the response.Examples: Apache Tomcat,
WildFly, IBM WebSphere.

Features of Web Servers


Web servers offer a range of features, including:
 Content Hosting: They store and serve web content, including HTML
pages, images, videos, and other multimedia files.
 Security: Web servers implement various security mechanisms to protect
against unauthorized access and cyberattacks.
 Load Balancing: Some web servers can distribute incoming traffic across
multiple server instances to ensure optimal performance and availability.
 Logging and Monitoring: They provide tools to track and analyze server
performance, user access, and error logs.
 Caching: Web servers can cache frequently accessed content to reduce
server load and improve response times.

Web Server Working


It can respond to the client request in either of the following two possible ways:
 Generating response by using the script and communicating with database.
 Sending file to the client associated with the requested URL.

The block diagram representation of Web Server is shown below:

 Client Request: A user enters a URL in a web browser, which sends an


HTTP request to the web server.
 DNS Resolution: The domain name is translated into an IP address through
the Domain Name System (DNS).
 Server Response:

S V PUBLICATIONS
BCA III YEAR - V SEM 15

o The web server receives the request.


o It processes the request (e.g., retrieves files, executes scripts).
o The server sends back an HTTP response, which may include HTML,
CSS, images, etc.
 Rendering: The browser receives the response and renders the content for
the user to view.

1.2.1 Web Server Roles

Q3. What is the role of a web server in web applications?


Ans:
A web server plays a crucial role in managing and serving web content to users.
Its primary functions include:

1. Handling Requests: Web servers receive and process incoming requests


from clients (typically web browsers) for web resources like HTML pages,
images, CSS files, or scripts.
2. Storing and Managing Files: Web servers store and organize the files that
make up a website. These files can include static content (e.g., images) or
dynamic content (e.g., scripts, database queries).
3. Processing Requests: Upon receiving a request, the web server processes it
by locating the requested file or generating dynamic content through
interactions with other components like databases or application servers.
4. Content Delivery: Once the requested content is located or generated, the
web server sends it back to the client's browser for display. This content
could be in the form of HTML, images, CSS, JavaScript, or other multimedia
files.
5. HTTP Protocol Handling: Web servers adhere to the rules of the Hypertext
Transfer Protocol (HTTP). They handle HTTP requests and responses,
ensuring that data is transmitted correctly between the server and the client.
6. Security: Web servers often include security features to protect against
common web vulnerabilities. They may implement encryption (HTTPS) to
secure data transmission and have mechanisms to guard against
unauthorized access.
7. Logging and Monitoring: Web servers maintain logs that record details of
incoming requests. These logs can be crucial for troubleshooting, analyzing
traffic patterns, and monitoring server performance.
8. Load Balancing: In larger-scale applications, web servers can be part of a
load balancing setup. Load balancers distribute incoming traffic across
multiple servers to ensure optimal performance and prevent server
overload.

S V PUBLICATIONS
16 BCA III YEAR - V SEM

9. Integration with Application Servers: In dynamic websites or web


applications, web servers often work in conjunction with application
servers. The web server may handle static content, while application servers
process dynamic content and interact with databases.
10. Caching: Web servers can implement caching mechanisms to store copies of
frequently requested resources. This helps reduce server load and improve
response times by serving cached content instead of generating it
repeatedly.

1.2.2 IIS (Internet Information Services)

Q4. What is the IIS web server? How to run IIS on server?
Ans:
IIS (Internet Information Services) is a web server software created by
Microsoft. It is used to host and serve web applications and websites on Windows
servers. Here are some key features and components of IIS:

Key Features
 Web Server: Hosts static and dynamic websites.
 Application Pools: Isolates web applications for better security and
reliability.
 Security: Supports SSL, authentication methods, and authorization features.
 Scalability: Handles high traffic and can be configured for load balancing.
 Management Tools: Offers a user-friendly interface (IIS Manager) for
managing websites and applications.
 Extensions: Supports various extensions like ASP.NET, PHP, and others for
dynamic content.

Basic Configuration Steps


Install IIS:
Use the Windows Features dialog (Control Panel > Programs > Turn Windows
features on or off).
Check Internet Information Services and its components.
Create a Website:
Open IIS Manager.
Right-click on "Sites" and select "Add Website."
Configure the site name, physical path, and binding settings.
Manage Application Pools:
Create and configure application pools to isolate different web applications.
Set Up Security:
Configure authentication methods (Anonymous, Basic, Windows, etc.).
Set up SSL certificates for secure connections.

S V PUBLICATIONS
BCA III YEAR - V SEM 17

Deploy Applications:
Upload your application's files to the designated folder.
Ensure that the application pool settings match the requirements of your
application.

Here are some key applications and features of IIS:


1. Web Hosting
Static Websites: Serve HTML, CSS, and JavaScript files.
Dynamic Websites: Host applications built with ASP.NET, PHP, and other
server-side technologies.
2. Application Pools
Isolate different web applications for better security and stability. Each
application pool runs its own worker process.
3. Security Features
Authentication: Supports various authentication methods, including Windows
Authentication, Basic Authentication, and Forms Authentication.
Authorization: Control access to resources using URL authorization rules.
4. URL Rewrite
Rewrite and redirect URLs to improve SEO and manage URL structures
effectively.
5. FTP Hosting
Provide FTP services for file transfers, allowing users to upload or download
files securely.
6. Logging and Diagnostics
Comprehensive logging options to monitor website traffic and diagnose issues.
7. SSL/TLS Support
Enable HTTPS for secure data transmission using SSL certificates.
8. Performance Features
Caching: Enhance performance by caching static content.
Compression: Reduce load times by compressing responses.
9. ASP.NET Integration
Full support for ASP.NET applications, including MVC and Web API.
10. Management Tools
IIS Manager: A graphical interface for managing sites, applications, and server
settings.
PowerShell: Automate server management using scripts.
11. Load Balancing
Distribute traffic across multiple servers to improve reliability and
performance.
12. Content Management
Host content management systems (CMS) like Umbraco and Sitecore.

S V PUBLICATIONS
18 BCA III YEAR - V SEM

13. WebDAV
Support for Web-based Distributed Authoring and Versioning, allowing users
to edit and manage files on a remote server.
14. Application Deployment
Integration with deployment tools like Web Deploy for easy application
publishing.

1.2.3 Apache Web Server

Q5. What is Apache and What Does it Do for Website Development?


Ans:
Apache HTTP Server, commonly referred to as Apache, is one of the most
widely used web server software solutions. It is open-source, reliable, and highly
configurable, making it a popular choice for hosting websites and applications.

Here are some key features, components, and uses of Apache:


Key Features
 Open Source: Free to use and modify, with a large community of
contributors.
 Cross-Platform: Runs on various operating systems, including Windows,
Linux, and macOS.
 Modular Architecture: Supports a wide range of modules to extend
functionality (e.g., mod_ssl for SSL/TLS, mod_rewrite for URL rewriting).
 Virtual Hosting: Allows hosting multiple websites on a single server.
 URL Rewriting: Flexible URL manipulation through the mod_rewrite
module.
 Security Features: Supports various authentication mechanisms and
encryption with SSL/TLS.
 Custom Error Pages: Ability to define custom error responses (e.g., 404
pages).
 Extensive Documentation: Comprehensive guides and community support.

Basic Configuration Steps


Installation:
 On Linux: Install using package managers (e.g., apt install apache2 for
Debian/Ubuntu or yum install httpd for CentOS).
 On Windows: Download the installer from the official Apache website
or use XAMPP for a bundled solution.
Configuration Files:
 Main configuration file is usually httpd.conf or apache2.conf.
 Site-specific configurations can be placed in the sites-available and sites-
enabled directories (on Debian-based systems).

S V PUBLICATIONS
BCA III YEAR - V SEM 19

Creating a Virtual Host:


Define virtual hosts in the configuration file to host multiple sites:
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example
<Directory /var/www/example>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
Enabling Modules:
Use a2enmod on Debian-based systems to enable desired modules (e.g.,
a2enmod rewrite).
Setting Up Security:
Configure .htaccess files or the main configuration to manage authentication,
access controls, and SSL settings.
Restarting the Server:
After making changes, restart Apache to apply them:
sudo systemctl restart apache2 # Debian/Ubuntu
sudo systemctl restart httpd # CentOS

1.3 Web Browsers

Q6. Discuss about web browser and what are the top popular web browsers?
Ans:
Web Browser is a common term which is frequently used by people while
discussing the Internet. However, the exact definition of a web browser is known
by few only.

Web Browser Definition: A software application used to access information on the


World Wide Web is called a Web Browser. When a user requests some information,
the web browser fetches the data from a web server and then displays the webpage
on the user‟s screen.

Functions of Web Browser


Our dependency on the Internet has massively increased. Stated below are
functions of web browsers and how are they useful:
 The main function is to retrieve information from the World Wide Web and
making it available for users
 Visiting any website can be done using a web browser. When a URL is
entered in a browser, the web server takes us to that website

S V PUBLICATIONS
20 BCA III YEAR - V SEM

 To run Java applets and flash content, plugins are available on the web
browser
 It makes Internet surfing easy as once we reach a website we can easily
check the hyperlinks and get more and more useful data online
 Browsers user internal cache which gets stored and the user can open the
same webpage time and again without losing extra data
 Multiple webpages can be opened at the same time on a web browser
 Options like back, forward, reload, stop reload, home, etc. are available on
these web browsers, which make using them easy and convenient

Types of Web Browser


The functions of all web browsers are the same. Thus, more than the different
types there are different web browsers which have been used over the years.

1. WorldWideWeb
 The first web browser ever
 Launched in 1990
 It was later named “Nexus” to avoid any confusion with the World Wide
Web
 Had the very basic features and less interactive in terms of graphical
interface
 Did not have the feature of bookmark
2. Mosaic
 It was launched in 1993
 The second web browser which was launched
 Had a better graphical interface. Images, text and graphics could all be
integrated
 It was developed at the National Center for Supercomputing Applications
 The team which was responsible for creating Mosaic was lead by Marc
Andreessen
 It was named “the world‟s first popular browser”
3. Netscape Navigator
 It was released in 1994
 In the 1990s, it was the dominant browser in terms of usage share
 More versions of this browser were launched by Netscape
 It had an advanced licensing scheme and allowed free usage for non-
commercial purposes
4. Internet Explorer
 It was launched in 1995 by Microsoft
 By 2003, it has attained almost 95% of usage share and had become the most
popular browsers of all

S V PUBLICATIONS
BCA III YEAR - V SEM 21

 Close to 10 versions of Internet Explorer were released by Microsoft and


were updated gradually
 It was included in the Microsoft Windows operating system
 In 2015, it was replaced with “Microsoft Edge”, as it became the default
browser on Windows 10
5. Firefox
 It was introduced in 2002 and was developed by Mozilla Foundation
 Firefox overtook the usage share from Internet Explorer and became the
dominant browser during 2003-04
 Location-aware browsing was made available with Firefox
 This browser was also made available for mobile phones, tablets, etc.
6. Google Chrome
 It was launched in 2008 by Google
 It is a cross-platform web browser
 Multiple features from old browsers were amalgamated to form better and
newer features
 To save computers from malware, Google developed the ad-blocking
feature to keep the user data safe and secure
 Incognito mode is provided where private searching is available where no
cookies or history is saved
 Till date, it has the best user interface

1.3.1 Web Support Languages

Q7. List the languages that are used for web development applications?
Ans:
Web development languages are the backbone of the internet, powering
everything from simple blogs to complex online applications. In today‟s fast-paced
digital age, staying up-to-date with the most popular web languages and tools is
more important than ever.

If you are new to web development, the toughest part of learning programming
is deciding where to start. Hundreds of web development languages are widely
used, each with complexities and idiosyncrasies.

Web development involves a variety of languages, each serving different


purposes. Here‟s a breakdown of the key languages used in web development:

1. HTML (HyperText Markup Language)


Purpose: The backbone of web pages, used to structure content.
Features: Defines elements like headings, paragraphs, links, images, and more.
2. CSS (Cascading Style Sheets)

S V PUBLICATIONS
22 BCA III YEAR - V SEM

Purpose: Styles the visual presentation of web pages.


Features: Controls layout, colors, fonts, and responsive design.
3. JavaScript
Purpose: Adds interactivity and dynamic behavior to websites.
Features: Enables client-side scripting, manipulating the DOM, handling
events, and communicating with servers (via AJAX).
4. Backend Languages
These languages run on the server side to handle database interactions,
authentication, and business logic.
PHP: Widely used for server-side scripting, often with content management
systems like WordPress.
Python: Popular for web development with frameworks like Django and
Flask.
Ruby: Known for its elegant syntax and used primarily with the Ruby on
Rails framework.
Java: Commonly used in enterprise applications, often with the Spring
framework.
C#: Used in ASP.NET applications, primarily for Windows-based
environments.
Node.js (JavaScript runtime): Enables server-side scripting using
JavaScript.
5. Database Query Languages
SQL (Structured Query Language): Used to interact with relational databases
(like MySQL, PostgreSQL, and SQLite).
NoSQL Languages: Various query languages for NoSQL databases (e.g.,
MongoDB's query language).
6. Markup and Template Languages
XML (eXtensible Markup Language): Used to store and transport data.
JSON (JavaScript Object Notation): A lightweight format for data interchange,
often used in APIs.
Template Engines: Languages like Handlebars, EJS, or Jinja2 used for rendering
dynamic HTML.
7. Frameworks and Libraries
Frontend:
React: A JavaScript library for building user interfaces.
Vue.js: A progressive JavaScript framework for building UIs.
Angular: A platform for building mobile and desktop web applications.
Backend:
Express: A web application framework for Node.js.
Django: A high-level Python web framework that encourages rapid
development.
Ruby on Rails: A web application framework written in Ruby.

S V PUBLICATIONS
BCA III YEAR - V SEM 23

8. Other Languages
TypeScript: A superset of JavaScript that adds static types, often used in large
applications.
Sass/LESS: CSS preprocessors that allow for more dynamic stylesheets.
9. Web Assembly (Wasm)
A binary instruction format that allows code written in languages like C, C++,
or Rust to run in the browser, providing near-native performance.

1.4 HTTP

Q8. Discuss in detail about HTTP?


Ans:
 HTTP stands for HyperText Transfer Protocol.
 It is a protocol used to access the data on the World Wide Web (www).
 The HTTP protocol can be used to transfer the data in the form of plain text,
hypertext, audio, video, and so on.
 This protocol is known as HyperText Transfer Protocol because of its
efficiency that allows us to use in a hypertext environment where there are
rapid jumps from one document to another document.
 HTTP is similar to the FTP as it also transfers the files from one host to
another host. But, HTTP is simpler than FTP as HTTP uses only one
connection, i.e., no control connection to transfer the files.
 HTTP is used to carry the data in the form of MIME-like format.
 HTTP is similar to SMTP as the data is transferred between client and
server. The HTTP differs from the SMTP in the way the messages are sent
from the client to the server and from server to the client. SMTP messages
are stored and forwarded while HTTP messages are delivered immediately.

Features of HTTP
 Connectionless protocol: HTTP is a connectionless protocol. HTTP client
initiates a request and waits for a response from the server. When the server
receives the request, the server processes the request and sends back the
response to the HTTP client after which the client disconnects the
connection. The connection between client and server exist only during the
current request and response time only.
 Media independent: HTTP protocol is a media independent as data can be
sent as long as both the client and server know how to handle the data
content. It is required for both the client and server to specify the content
type in MIME-type header.
 Stateless: HTTP is a stateless protocol as both the client and server know
each other only during the current request. Due to this nature of the

S V PUBLICATIONS
24 BCA III YEAR - V SEM

protocol, both the client and server do not retain the information between
various requests of the web pages.
Features of HTTP
 Connectionless protocol: HTTP is a connectionless protocol. HTTP client
initiates a request and waits for a response from the server. When the server
receives the request, the server processes the request and sends back the
response to the HTTP client after which the client disconnects the
connection. The connection between client and server exist only during the
current request and response time only.
 Media independent: HTTP protocol is a media independent as data can be
sent as long as both the client and server know how to handle the data
content. It is required for both the client and server to specify the content
type in MIME-type header.
 Stateless: HTTP is a stateless protocol as both the client and server know
each other only during the current request. Due to this nature of the
protocol, both the client and server do not retain the information between
various requests of the web pages.

Versions of HTTP
 HTTP/1.0: The original version, which required a new connection for each
request.
 HTTP/1.1: Improved version with persistent connections and additional
features like chunked transfer encoding and caching mechanisms.
 HTTP/2: Introduced multiplexing, allowing multiple streams of data to be
sent over a single connection, improving performance.
 HTTP/3: Built on QUIC, a transport layer network protocol that reduces
latency and improves security.

1.5 TCP/IP Role in Web Development

Q9. What is the role of TCP/IP in the web system? Or Explain the role of TCP/IP
in web development.
Ans:
TCP/IP (Transmission Control Protocol/Internet Protocol) is a suite of
communication protocols that define the standards for transmitting data over
computer networks, including the internet. The TCP/IP protocol is the foundation
of the internet and enables devices to communicate with each other using a
common language.

The TCP/IP protocol is divided into two layers: the Transport layer and the
Internet layer. The Transport layer is responsible for ensuring that data is
transmitted reliably from one device to another. This layer is comprised of two
S V PUBLICATIONS
BCA III YEAR - V SEM 25

protocols: the Transmission Control Protocol (TCP) and the User Datagram
Protocol (UDP). TCP is used for reliable data transmission, while UDP is used for
fast transmission of data that can tolerate some packet loss.

The Internet layer is responsible for transmitting data packets between devices.
This layer is comprised of two protocols: the Internet Protocol (IP) and the Address
Resolution Protocol (ARP). IP is responsible for routing data packets between
devices, while ARP is used to map IP addresses to physical addresses.

TCP/IP also includes a number of application layer protocols that are used to
provide services to end-users. These include protocols such as HTTP (Hypertext
Transfer Protocol) for web browsing, FTP (File Transfer Protocol) for file transfer,
and SMTP (Simple Mail Transfer Protocol) for email.

TCP/IP stands for Transmission Control Protocol/ Internet Protocol. It is a set


of conventions or rules and methods that are used to interconnect network devices
on the Internet. The internet protocol suite is commonly known as TCP/IP, as the
foundational protocols in the suite are Transmission Control Protocol and Internet
Protocol. It chooses how the information will be traded over the web through end-
to-end communications that incorporate how the information ought to be
organized into bundles (bundles of data), addressed, sent, and received at the goal.
This communication protocol can also be utilized to interconnect organize devices
in a private network such as an intranet or an extranet.

Characteristics of TCP/IP
 Share Data Transfer: The TCP allows applications to create channels of
communications across a network. It also permits a message to be separated
into smaller packets before they are transmitted over the web and after that
collected in the right order at the destination address. So, it guarantees the
solid transmission of data across the channel.
 Internet Protocol: The IP address tells the packets the address and route so
that they reach the proper destination. It includes a strategy that empowers
portal computers on the internet-connected to arrange forward the message
after checking the IP address.
 Reliability: The most vital feature of TCP is solid data delivery. In arrange
to supply unwavering quality, TCP must recover information that‟s
harmed, misplaced, copied, or conveyed out of arranging by the Arrange
Layer.
 Multiplexing: Multiplexing can be achieved through the number of ports.
 Connections: Before application forms can send information by utilizing
TCP, the devices must set up a connection. The associations are made
between the harbor numbers of the sender and the collector devices.

S V PUBLICATIONS
26 BCA III YEAR - V SEM

 Compatibility: TCP/IP is designed to be compatible with a wide range of


hardware and software platforms. This makes it a versatile protocol suite
that can be used in a variety of network environments.
 Scalability: TCP/IP is highly scalable, which means that it can be used in
networks of any size, from small home networks to large enterprise
networks.
 Open standards: TCP/IP is based on open standards, which means that the
protocol specifications are publicly available and can be implemented by
anyone. This fosters innovation and competition in the networking
industry.
 Modular architecture: TCP/IP is designed with a modular architecture,
which means that different protocols can be added or removed as needed.
This allows network administrators to tailor their networks to specific
needs.
 Reliability: TCP/IP is designed to be highly reliable, with built-in error
checking and correction mechanisms that ensure data is transmitted
accurately and reliably.
 Flexibility: TCP/IP is a flexible protocol suite that can be used for a wide
range of applications, including web browsing, email, file sharing, and
more.
 End-to-end connectivity: TCP/IP provides end-to-end connectivity
between devices, which means that data can be transmitted directly from
the source device to the destination device without being routed through
intermediate devices.

TCP/IP Layers
 Application Layer - An application layer is the topmost layer within the
TCP/IP model. When one application layer protocol needs to communicate
with another application layer, it forwards its information to the transport
layer.
 Transport Layer - It is responsible for the reliability, flow control, and
correction of data that is being sent over the network. There are two
protocols used in this layer are User Datagram Protocol and Transmission
control protocol.
 Internet/Network Layer - It is the third layer of the TCP/IP Model and also
known as the Network layer. The main responsibility of this layer is to send
the packets from any network, and they arrive at the goal irrespective of the
route they take.
 Network Access Layer - It is the lowest layer of the TCP/IP Model. It is the
combination of the Physical Layer and the Data link layer which present in

S V PUBLICATIONS
BCA III YEAR - V SEM 27

the OSI Model. Its main responsibility is to the transmission of information


over the same network between two devices.

Application/Uses of TCP/IP
Some Real-Time Applications are:
 Simple Mail Transfer Protocol(SMTP): It helps to send email to another
email address.
 File Transfer Protocol(FTP): It is used for sending large files.
 Dynamic Host Configure Protocol(DHCP): It assigns the IP address.
 Telnet: Bi-directional text communication via a terminal application.
 HyperText Transfer Protocol(HTTP): Used to transfer the web pages.
 Domain Name System(DNS): It translates the website name to IP
addresses.
 Simple Network Time Protocol(SNTP): It provides the time of a day to the
network devices.

1.6 ASP.Net Role

Q10. Discuss briefly about ASP.Net framework, Namespaces.


Ans:
ASP.NET Architecture and its Components
ASP.Net is a framework which is used to develop a Web-based application. The
basic architecture of the ASP.Net framework is as shown below.

The architecture of the.Net framework is based on the following key components


 Language – A variety of languages exists for .net framework. They are
VB.net and C#. These can be used to develop web applications.
 Library – The .NET Framework includes a set of standard class libraries.
The most common library used for web applications in .net is the Web
library. The web library has all the necessary components used to
develop.Net web-based
applications.
 Common Language Runtime –
The Common Language
Infrastructure or CLI is a
platform. .Net programs are
executed on this platform. The
CLR is used for performing key
activities. Activities include Exception handling and Garbage collection.

S V PUBLICATIONS
28 BCA III YEAR - V SEM

Below are some of the key characteristics of the ASP.Net framework


 Supports Multiple Platforms: ASP.NET Core applications can run on
Windows, Linux, and Mac. So you don't need to build different apps for
different platforms using different frameworks.
 Fast: ASP.NET Core no longer depends on System.Web.dll for browser-
server communication. ASP.NET Core allows us to include packages that
we need for our application. This reduces the request pipeline and improves
performance and scalability.
 IoC Container: It includes the built-in IoC container for automatic
dependency injection which makes it maintainable and testable.
 Integration with Modern UI Frameworks: It allows you to use and manage
modern UI frameworks such as AngularJS, ReactJS, Umber, Bootstrap, etc.
using Bower (a package manager for the web).
 Hosting: ASP.NET Core web application can be hosted on multiple
platforms with any web server such as IIS, Apache etc. It is not dependent
only on IIS as a standard .NET Framework.
 Code Sharing: It allows you to build a class library that can be used with
other .NET frameworks such as .NET Framework 4.x or Mono. Thus a single
code base can be shared across frameworks.
 Side-by-Side App Versioning: ASP.NET Core runs on .NET Core, which
supports the simultaneous running of multiple versions of applications.
 Smaller Deployment Footprint: ASP.NET Core application runs on .NET
Core, which is smaller than the full .NET Framework. So, the application
which uses only a part of .NET CoreFX will have a smaller deployment size.
This reduces the deployment footprint.

ASP.Net is a development language used for constructing web-based


applications. ASP.Net is designed to work with the standard HTTP protocol.

ASP.Net Framework and Name Spaces


The ASP.NET Framework is a powerful platform for building web applications
and services. It consists of various components, including namespaces that organize
classes and functions into logical groups. Here‟s a breakdown of some key
namespaces in the ASP.NET Framework:

The ASP.NET Framework is a comprehensive web application framework


developed by Microsoft, designed to facilitate the creation of dynamic web
applications and services. It provides a robust ecosystem for building web-based
applications, ranging from simple websites to complex enterprise solutions. Here‟s
a detailed overview of the ASP.NET Framework:

S V PUBLICATIONS
BCA III YEAR - V SEM 29

Key Components of ASP.NET Framework


1. Web Forms
A component-based framework for building dynamic web pages.
Uses a drag-and-drop interface in Visual Studio, making it easy to design user
interfaces.
Supports state management through ViewState and PostBack.
2. ASP.NET MVC
A design pattern-based framework that separates an application into three main
components: Model, View, and Controller.
Promotes a more organized approach to web development and enhances
testability.
Offers powerful routing mechanisms for clean URL structures.
3. ASP.NET Web API
A framework for building RESTful services that can be consumed by various
clients (e.g., browsers, mobile apps).
Supports content negotiation, allowing clients to request data in different
formats (JSON, XML).
4. ASP.NET Core
A cross-platform, high-performance framework that unifies the MVC and Web
API frameworks.
Designed to be modular and lightweight, suitable for cloud-based applications.
Supports dependency injection and middleware for request processing.

Key Features
1. Rich Library Support
Provides a vast library of built-in classes and methods for managing common
tasks like data access, authentication, and authorization.
2. Security
Built-in authentication and authorization features, including membership and
role management.
Supports various authentication methods (e.g., forms authentication, Windows
authentication, OAuth).
3. State Management
Different mechanisms for managing state, including:
ViewState: Maintains state for web controls.
Session State: Stores user data across multiple requests.
Application State: Global data accessible to all users.
4. Server Controls
Provides a rich set of server-side controls for building user interfaces, such as
text boxes, buttons, and grids.

S V PUBLICATIONS
30 BCA III YEAR - V SEM

5. Data Access
Supports various data access technologies, including ADO.NET, Entity
Framework, and LINQ for querying data.
6. Caching
Offers caching mechanisms to improve performance and reduce server load,
including output caching and data caching.

Key ASP.NET Namespaces


1. System.Web
Contains classes and interfaces that support the ASP.NET application
framework.
Key Classes:
HttpApplication: Represents an ASP.NET application.
HttpContext: Provides information about the current HTTP request.
HttpRequest: Represents an incoming HTTP request.
HttpResponse: Represents an outgoing HTTP response.
2. System.Web.UI
Provides classes for creating web pages and controls in ASP.NET Web Forms.
Key Classes:
Page: Represents a web page in an ASP.NET application.
Control: Base class for all server-side controls.
UserControl: Represents a reusable component.
3. System.Web.Mvc
Contains classes for the ASP.NET MVC framework.
Key Classes:
Controller: Base class for MVC controllers, handling incoming requests and
returning responses.
ActionResult: Represents the result of an action method.
ViewResult: Represents a view rendered to the client.
4. System.Web.Http
Used for building HTTP services, primarily in ASP.NET Web API.
Key Classes:
ApiController: Base class for Web API controllers.
HttpResponseMessage: Represents an HTTP response message.
5. System.Web.Routing
Provides routing functionality to map URLs to specific handlers.
Key Classes:
Route: Represents a route in the routing table.
RouteCollection: Represents a collection of routes.
6. System.Web.Security
Contains classes for managing authentication and authorization.

S V PUBLICATIONS
BCA III YEAR - V SEM 31

Key Classes:
Membership: Provides methods for managing user accounts.
Roles: Provides methods for role management.
7. System.Data
Provides classes for data access and manipulation.
Key Classes:
DataSet: Represents an in-memory cache of data.
SqlConnection: Represents a connection to a SQL Server database.

1.6.1 New scenario in development process with IDE

Q11. What is the use IDE to manage the development process of the program?
Why do Developers Use IDE (Integrated Development Environment)? How
Should I Choose an IDE?
Ans:
An IDE (Integrated Development Environment) is software that combines
commonly used developer tools into a compact GUI (graphical user interface)
application. It is a combination of tools like a code editor, code compiler, and code
debugger with an integrated terminal.

Integrating features like software editing, building, testing, and packaging in a


simple-to-use tool, IDEs help boost developer productivity. IDEs are commonly
used by programmers and software developers to make their programming
journey smoother.

Why?
By providing a single, unified environment for managing all aspects of the
development process, IDEs can help improve a developer‟s productivity, code
quality, and overall development experience.
 Productivity: By combining common activities such as editing code,
building executable, debugging, and testing as part of software/application
development, IDEs help by reducing time and increasing overall
productivity.
 Code Quality: IDEs come with built-in tools as a part of a single GUI,
through which developers can execute actions without switching between
applications. Furthermore, it can also help in Syntax highlighting, code
refactoring, and code analysis boosting overall code quality.
 Integrated Environment: IDEs come pre-built with a combination of
development tools that allow developers to start programming new
applications quickly. With IDEs, it is no longer necessary to manually
configure and integrate numerous utilities as part of the setup procedure.
Additionally, since every utility is available on the same workbench,

S V PUBLICATIONS
32 BCA III YEAR - V SEM

developers don‟t have to spend hours learning how to use each one
separately.
 Customizability: By incorporating customization options ranging from
custom color schemes, and keyboard shortcuts, to choosing unique layouts,
different plugins, and add-ons; IDEs enable developers to customize their
environment to their unique needs and tastes, improving the comfort and
efficiency of the development process.

Choose an IDE
One can find many IDEs available in the market, while some are open-source
and free to use, others may work with subscription models. Popular IDEs include
Visual Studio, PyCharm, Android Studio, etc.
1. Programming Language: The choice of IDE (Integrated Development
Environment) mainly lies with the programming language you decide on.
Dedicated IDEs have automated features that best suit the programming
languages they support. While there also exist IDEs that support multiple
programming languages.
2. Operating System: Mostly all IDEs work with different Operating systems,
but there exist IDEs that might only work best on specific platforms. You
may take into account the IDEs‟ compatibility with various platforms and
operating systems.
3. Pricing Model: Some IDEs might be freely available while some may
require a premium subscription model to unlock the majority of the
features. Taking your budget and your needs, go with the IDE that suits
you the best.
4. Features: Features like version control, debugger, code highlighter,
integrated terminal, and code refactoring are some of the features that can
be considered white choosing an IDE.

S V PUBLICATIONS
BCA III YEAR - V SEM 33

UNIT
Asp.Net Web Forms
ASP.Net web forms-Introduction to web forms, page directives and its use,

II
separating code & design, new code behind techniques, ASP.Net server
controls-Working with server controls, applying styles to controls, themes,
skins etc.

2.1 Introduction to Web forms

Q1. What are web forms in asp net? What are the characteristics of a web form?
Ans:
Web Forms are web pages built on the ASP.NET Technology. It executes on the
server and generates output to the browser. It is compatible to any browser to any
language supported by .NET common language runtime. It is flexible and allows us
to create and add custom controls.

We can use Visual Studio to create ASP.NET


Web Forms. It is an IDE (Integrated
Development Environment) that allows us to
drag and drop server controls to the web forms.
It also allows us to set properties, events and
methods for the controls. To write business
logic, we can choose any .NET language like: Visual Basic or Visual C#.

Web Forms are made up of two components: the visual portion (the ASPX file),
and the code behind the form, which resides in a separate class file.

Features of Web Forms


ASP.NET has multiple features and provides many tools to create and develop
web applications. Here are some of the features of web forms:

1. Web Server Controls: It provides a vast set of server controls. These


controls are like objects, and they run when they are requested and
rendered to the browser. Some web pages are similar to HTML elements
like text-box, button, checkbox, and hyperlink.
2. Mater Pages: Mater Pages is responsible for the consistent layout of our
web applications. It gives a proper appearance and standard to different
pages.
3. Routing: URL routing can be configured to a web application. A request
URL is a URL that a user enters in a browser to browse in a specific place.
4. Security: Security always plays a crucial role in software development.
ASP.NET provides different configuration options and extensibility points
to make our systems more secure.

S V PUBLICATIONS
34 BCA III YEAR - V SEM

ASP.NET Server Control


ASP.NET has web forms that can be used for making HTML elements. These
are of two types: client-based and server-based.

The following table contains some of the server controls:


Control Name Applicable Events Description
Label None Used for displaying text on an HTML page.
Text Box Text Changed Used for creating a text input in the form.
Button Click, Command Used for creating a button

Web Form User Registration


This webform has the crucial function of taking input from the user and
submitting it to the server. After submitting it, it also shows that the message has
been successfully registered. This whole process gets completed in the following
steps:
 Add a web form to the project: This form has some HTML code in it.
 Adding controls to the form: For adding the controls, you can either write
your own code or drag and drop it from the toolbox in the visual studio to
create components.
 Handling a submit request: In the code file, there is a section where you add
a message that only pops out when you submit a registration form.
 Run user registration form: This form takes the inputs from the user form
and shows a greeting message to the user.

2.2 Page Directives and Its Uses in Asp.net

Q2. What is a directive in ASP.NET?


Ans:
In ASP.NET, a directive is a special instruction that provides configuration
settings for an ASP.NET page or user control. Directives are defined at the top of an
ASP.NET file and are used to control the behavior of the page or to specify settings
that affect the compilation and execution of the page.

ASP.NET directives help you give your pages personality and capabilities. You
can cause one page to behave in one fashion, whereas another page responds to the
same stimulus in a totally different way. One page can have one set of skills or
capabilities, whereas another has a totally different set. Directives give us this
power.

A list of directives that you will commonly use, but this isn't an exhaustive list.
As is true with many aspects of the .NET Framework, the full scope of directives is

S V PUBLICATIONS
BCA III YEAR - V SEM 35

beyond the scope of this book, but you can see the full list of directives, their
functions and their players, in the .NET Framework SDK as following:

The Application Directive:


Application specific attributes are defined in an application directive.
Application directive is provided at the top of the global.aspx file.

Syntax for Application Directive


<%@ Application Language=”C#” %>

The Control Directive:


The control Directive is appears in the user control files and it is used with the
user controls.

Syntax for Control Directive


<%@ Control Language=”C#” EnableViewState=”false” %>

The Assembly Directive:


Assembly directive is used for links an assembly to the page or the application
at parse time. Assembly directive appears in the global.asax file for application a
user control file for linking to a page or user control.

Syntax for Assembly Directive


<%@ Assembly Name =”name” %>

The Implements Directive:


The Implement directive defines to indicates that the master page, web page or
user control page must implement the specified dot net framework interface.

Syntax for implements directive


<%@ Implements Interface=”interface_name” %>

The Import Directive:


The Import directive imports a namespace into a web page, user control page of
application. The Import directive is specified in the global.asax file, if it is applied to
the entire application. If import directive is in a page of user control page, then it is
applied to that page or control.

The basic syntax for import directive


<%@ namespace=”System.Drawing” %>

The Master Directive:


The Master directive is used specifies a page file as being the mater page.

Syntax for MasterPage directive


<%@MasterPageLanguage=”dotnet”AutoEventWireup=”true”
CodeFile=”SiteMater.master.cs” %>

S V PUBLICATIONS
36 BCA III YEAR - V SEM

The OutputCache Directive:


The OutputCache directive is used to controls the output caching policies of a
web page or a user control.

Syntax for OutputCache directive


<%@ OutputCache Duration=”15″ VaryByParam=”None” %>

The MasterType Directive


The MasterType directive is used to assigns a class name to the Master
property of a page, and it is make to strongly typed.

Syntax for MasterType directive


<%@ MasterType attribute=”value”[attribute=”value” …] %>

The Page Directive:


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

Syntax for Page directive


<%@PageLanguage=”C#”AutoEventWireup=”true”CodeFile=”Default.aspx.cs
” Inherits=”_Default” Trace=”true” %>

The PreviousPageType Directive:


The PreviousPageType directive is used to assigns a class to a page, so that the
page is strongly typed.s

Syntax for PreviousPagetype directive


<%@ PreviousPageType attribute=”value”[attribute=”value” …] %>

The Reference Directive:


The Reference directive is used to indicates that another page or user control
should be compiled and linked to the current page.
Syntax of Reference directive
<%@ Reference Page =”somepage.aspx” %>

The Register Directive :


The Register derivative is registering the custom server controls and user
controls.

syntax for Register directive


<%@ Register Src=”~/footer.ascx” TagName=”footer” TagPrefix=”Tfooter”
%>

S V PUBLICATIONS
BCA III YEAR - V SEM 37

2.3 Separating Code & Design

Q3. How is an ASP.NET presentation page associated with its code behind?
Ans:
Web developers are not necessarily good designers. Most companies divide the
task of building Web sites between two teams. Normally, one team is responsible
for the design content of a page, and the other team is responsible for the
application logic.

Maintaining this separation of tasks is difficult when both the design content
and application logic are jumbled together on a single page. A carefully engineered
ASP.NET page can be easily garbled after being loaded into a design program.
Likewise, a beautifully designed page can quickly become mangled in the hands of
an engineer.

Creating Business Components


How to create business components using Visual Basic and use the components
in an ASP.NET page. Business components have a number of benefits:
1. Business components enable you to divide presentation content from
application logic. You can design an attractive ASP.NET page and package
all the page's application logic into a business component.
2. Business components promote code reuse. You can write a library of useful
subroutines and functions, package them into a business component, and
reuse the same code on multiple ASP.NET pages.
3. Business components are compiled. You therefore can distribute a
component without worrying about the source code being revealed or
modified.
4. Business components can be written in multiple languages. Some
developers like working with Visual Basic, some prefer C# or C++, and
some even like COBOL and Perl. You can write components with different
languages and combine the components into a single ASP.NET page.
5. You can even call methods from a component written in one language from
a component written in another language.
6. Business components enable you to build multitiered Web applications. For
example, you can use components to create a data layer that abstracts away
from the design specifics of a particular database. Or you can write a set of
components that encapsulate your business logic.

Creating a Simple Business Component


A business component is a Visual Basic class file. Whenever you create a
component, you need to complete each of the following three steps:

S V PUBLICATIONS
38 BCA III YEAR - V SEM

 Create a file that contains the definitions for one or more Visual Basic classes
and save the file with the extension .vb.
 Compile the class file.
 Copy the compiled class file into your Web application‟s /BIN directory.
 Start by creating a simple component that randomly displays different
quotations. You can call this component the quote component. First, you
need to create the Visual Basic class file for the component.

2.3.1 New Code Behind Techniques

Q4. What is the code-behind technique?


Ans:
In ASP.NET, particularly with the rise of ASP.NET Core and Blazor, new
techniques for managing Code Behind in components have emerged. Here are
some modern approaches and best practices specifically for ASP.NET components:

1. Blazor Components
Overview: Blazor allows building interactive web UIs using C#. Components
are self-contained and can include both rendering logic and event handling.
Benefit: Promotes reusability and encapsulation of UI and logic, enabling easier
maintenance.
2. Injecting Services
Overview: Use dependency injection to inject services into Blazor components
directly.
Benefit: Facilitates access to services such as data repositories, logging, and API
clients, while maintaining loose coupling.
3. Event Callbacks
Overview: Use EventCallback to handle events and communicate between
parent and child components.
Benefit: Allows for a clean way to propagate events and data changes,
enhancing component interaction.
4. Data Binding
Overview: Leverage one-way and two-way data binding to synchronize
component state with UI elements.
Benefit: Simplifies the management of UI state and reduces boilerplate code for
updating the UI.
5. Parameter Binding
Overview: Use [Parameter] attribute to pass data from a parent component to a
child component.
Benefit: Promotes component reusability and makes it easier to manage
component state.

S V PUBLICATIONS
BCA III YEAR - V SEM 39

6. Scoped Services
Overview: Use scoped services to maintain state across components during a
single user interaction session.
Benefit: Helps manage state without relying on static variables or complex state
management patterns.
7. Custom Render Fragments
Overview: Create custom render fragments for dynamic content rendering
within components.
Benefit: Enables flexible UI composition and enhances component reusability.
8. Lifecycle Methods
Overview: Utilize component lifecycle methods such as OnInitialized,
OnParametersSet, and OnAfterRender.
Benefit: Provides hooks for executing code at specific points in a component's
lifecycle, improving control over rendering and data loading.

By leveraging modern practices such as dependency injection, lifecycle


management, and state management, developers can create efficient, maintainable,
and reusable components, leading to better overall application architecture.

2.4 ASP.Net Server Controls -Working

Q5. What are ASP.NET Server Control? How many types of ASP.NET controls
are there?
Ans:
ASP.NET Server Controls are components that run on the server and generate
HTML output for web pages. They provide a rich set of functionalities for building
dynamic web applications. Here‟s an overview of key ASP.NET Server Controls,
their types, and their uses:

1. Types of ASP.NET Server Controls


a. HTML Server Controls
Description: Standard HTML elements enhanced with server-side
capabilities.
Examples: <input>, <div>, <span>, and <table> marked with the
runat="server" attribute.
Use Case: Useful for scenarios where you need to manipulate standard
HTML elements on the server side.
b. Web Server Controls
Description: Higher-level controls that provide rich functionality and
encapsulate HTML markup.
Examples:
Button: <asp:Button> for handling click events.

S V PUBLICATIONS
40 BCA III YEAR - V SEM

Label: <asp:Label> for displaying text.


TextBox: <asp:TextBox> for user input.
DropDownList: <asp:DropDownList> for selection lists.
Use Case: Ideal for creating interactive forms and managing user inputs.
c. Data Controls
Description: Controls specifically designed to display and manipulate data
from data sources.
Examples:
GridView: <asp:GridView> for displaying tabular data.
ListView: <asp:ListView> for flexible item rendering.
Repeater: <asp:Repeater> for custom data presentation.
Use Case: Perfect for scenarios requiring data binding and
manipulation.
d. Validation Controls
Description: Controls that provide client-side and server-side validation of
user input.
Examples:
RequiredFieldValidator: Ensures a field is not empty.
RangeValidator: Validates that a value falls within a specified range.
CustomValidator: Allows for custom validation logic.
Use Case: Enhances user experience by providing immediate feedback on
input validation.
e. Navigation Controls
Description: Controls designed for site navigation.
Examples:
Menu: <asp:Menu> for hierarchical navigation.
TreeView: <asp:TreeView> for displaying hierarchical data.
Use Case: Useful for creating intuitive navigation systems in web
applications.
2. Features of ASP.NET Server Controls
ViewState Management: Automatically manages the state of controls across
postbacks, simplifying state management.
Event Handling: Server controls can raise events (e.g., button clicks), allowing
for an event-driven programming model.
Rich Properties: Controls have numerous properties to customize their
appearance and behavior.
Data Binding: Controls can easily bind to data sources (like databases) and
display data dynamically.

S V PUBLICATIONS
BCA III YEAR - V SEM 41

2.4.1Applying Styles to Controls

Q6. How to: Set ASP.NET Server Control Style Properties Programmatically. Or
How to Set ASP.NET Server Control Style Properties Using ASP.NET.
Ans:
Getting your custom control to behave the way you want it to is only half the
work. Once you get to the visual side of things you have to create the logic that
generates the actual HTML shown in the browser. If you want the control to
display properly, this can be a tedious task, especially if you want it to render
properly in different browsers. A control's Render method will render a control in
the last step of a control's life cycle, just before the control is disposed.

Applying styles to controls in ASP.NET can enhance the look and feel of your
web applications. There are several methods to apply styles, including inline styles,
CSS classes, and stylesheets. Here‟s a comprehensive guide on how to style
ASP.NET controls effectively:

1. Inline Styles
You can directly apply styles to an ASP.NET control using the style attribute.
Example:
<asp:Button ID="btnSubmit" runat="server" Text="Submit" style="background-
color: blue; color: white;" />
2. CSS Classes
Using CSS classes is a more maintainable approach. You can define styles in
a <style> block or an external CSS file and then apply them to your ASP.NET
controls using the CssClass property.
Example:
Define CSS in a <style> block or an external stylesheet:
.btn-custom {
background-color: green;
color: white;
font-size: 16px;
padding: 10px 20px;
}
Apply CSS Class to an ASP.NET Control:
<asp:Button ID="btnCustom" runat="server" Text="Custom Button"
CssClass="btn-custom" />
3. Using Themes
ASP.NET supports themes, which allow you to define a consistent look and
feel for your application.

S V PUBLICATIONS
42 BCA III YEAR - V SEM

Steps to Use Themes:


Create a Theme Folder: Create a folder named App_Themes in your project.
Add a Theme: Inside the App_Themes folder, create a new folder for your
theme (e.g., MyTheme).
Add a CSS File: Inside your theme folder, add a CSS file (e.g., styles.css).

Example of Theme Structure:


App_Themes
├── MyTheme
│ ├── styles.css
│ └── MyTheme.skin

Apply Theme: Set the theme in the Web.config or directly in the page.
Web.config Example:
<configuration>
<system.web>
<pages theme="MyTheme" />
</system.web>
</configuration>

5. Using Control Properties


Many ASP.NET controls have properties that can be styled directly.
Example:
<asp:Label ID="lblMessage" runat="server" Text="Hello, World!" Font-
Bold="true" ForeColor="Red" />
6. Responsive Design
Utilizing CSS frameworks like Bootstrap can greatly enhance the
responsiveness of your web pages.

Integrate Bootstrap:
Include Bootstrap CSS in your <head> section.
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap
/4.5.2/css/bootstrap.min.css">
Use Bootstrap classes in your ASP.NET controls.
<asp:Button ID="btnBootstrap" runat="server" Text="Bootstrap Button"
CssClass="btn btn-primary" />

7. CSS Specificity and Inheritance


Be mindful of CSS specificity and inheritance, especially when using
multiple styles. Use more specific selectors if styles are not applying as
expected.

S V PUBLICATIONS
BCA III YEAR - V SEM 43

2.4.2 Themes & Skins

Q7. How to apply themes and styles in ASP.net.


Ans:
Sometimes we need to change the layout of application for different-different
user. For example if a single application is used by different-different client and
every client has his own color schema, logo, font etc. requirements then we use
themes A theme is a collection of skin files, css, graphics, images etc.

Deploying Skin Files to a Website


 Launch the ASPxThemeDeployer tool.
 If you already have a custom theme assembly, do the following.
 In the Theme Deployer window, click File | Import Custom Themes…
 In the invoked dialog box, select the required assembly and click Open.

 Specify the path to your site in the Site path box.


 Select the required products from the Products check box list.
 In the Themes check box list, select the required pre-packaged or custom
theme.
 Since the assembly contains all other required image and CSS files, leave the
Only skin files option checked - to add skin files to the project.
 After copying is complete, click Copy Files and close the Theme Deployer
window.
 Click the Refresh button ( ) in Solution Explorer to see that the required
pre-packaged or custom theme was added to the application‟s App_Themes
folder.

S V PUBLICATIONS
44 BCA III YEAR - V SEM

Apply a Theme to a Web Page


Declarative approach:
To specify a theme for a page, set the @Page directive‟s Theme attribute to the
theme name.
<%@ Page Theme="Aqua" ... %>
Programmatic approach:
Specify the page‟s Page.Theme property in the Page.PreInit event handler.
protected void Page_PreInit(object sender, EventArgs e)
{
this.Theme = "Aqua";
...
}

Apply a Theme to a Website


Declarative approach:
Set the theme attribute to the theme name in the pages element within the
web.config file.
Asp file:
<system.web>
<pages theme="Aqua" />
...
</system.web>

We recommend that you utilize the DevExpress theming mechanism instead of


the ASP.NET mechanism.
XML file:
<devExpress>
<themes theme="" ... />
...
</devExpress>

S V PUBLICATIONS
BCA III YEAR - V SEM 45

Web Form
UNIT Validation Control
III
Web form validation controls-Required field validation Control
Computer Validation Control, Custom Validation Control, Group
Validation and Accounting Validation.ADO.Net Database Services-
Overview of ADO.Net, XML, XML to HTML, XML & Databases XML
Support in .Net retrieve data with datasets & Data Adapters.

3.1 Web form validation controls


Q1. Where do the ASP.NET validation controls validate data on the client or on
the web server?
Ans:
Validation controls in ASP.NET are a set of pre-built controls that help ensure
that user input meets certain criteria before it is processed by the server. These
controls provide an easy way to validate user input and prevent errors or malicious
data from being submitted. By using validation controls, developers can enhance
the usability and security of their web applications, as well as improve the overall
user experience by providing clear feedback to users when their input does not
meet the specified requirements.

When it comes to understanding the working of ASP.NET Validation Controls,


having knowledge of the class that inherits all the controls is necessary. This class is
called „The BaseValidator Class‟. All the validation controls in .NET inherit the
methods and properties of the BaseValidator class. This enables the developers to
make a generic suite of validation controls.

BaseValidator class
 ControlToValidate – This is a property that indicates the input control to
validate. Basically, the input value throughout the form must be unique.
And this is why it is a mandatory attribute as it helps in associating the
input control with a data validation control.
 ErrorMessage – This property holds the message that is to be displayed in
the event when the validation fails.
 Text – The value in this property is going to be displayed when
ValidationSummary control is used or there is a missing Text property.
 Enabled – It is a property that enables or disables the validator.
 Validate() – It helps in revalidating the control and updating the IsValid.
 IsValid – It is an attribute that specifies whether the input control is valid or
not.

S V PUBLICATIONS
46 BCA III YEAR - V SEM

Validation Controls in ASP.NET


Validator Description
It is used to compare the value of an input control
CompareValidator
against a value of another input control.
It evaluates the value of an input control to check
RangeValidator
the specified range.
It evaluates the value of an input control to
RegularExpressionValidator determine whether it matches a pattern defined by
a regular expression.
RequiredFieldValidator It is used to make a control required.
It displays a list of all validation errors on the Web
ValidationSummary
page.

RequiredFieldValidator Control
RequiredFieldValidator is known as an elementary validation control. There is
no form that doesn‟t consist of fields that are mandatory to be filled. If the users
want to proceed with the form, they will have to mandatorily fill these fields. To
ensure that such fields are not left empty, RequiredFieldValidator is used. Basically,
this validation checks that there must be some value-added within the control.
Some important properties of RequiredFieldValidator are-
 Initial value: Initial value is displayed by default to guide the users on how
the value must be added. This property is also used by the developers for a
drop-down list.
 ControlToValidate: This control is used to set the field of the text box for
validation.
 Text: The text value is set for the validation under this property.
<asp:requiredfieldvalidator id="UniqueId" runat="server"
controltovalidate="UniqueControlId" errormessage="ErrorMessageForFailure"
initialvalue="aPlaceholderValue">
</asp:requiredfieldvalidator>

S V PUBLICATIONS
BCA III YEAR - V SEM 47

RangeValidator
The RangeValidator is a validation control that is used by the .NET developers
to check whether the value of the input control is inside some specific range or not.
This type of control is used when it comes to getting inputs like Age, Date of Birth,
or mobile numbers from the user on the websites. Some of the major properties of
RangeValidator control are-
 Minimum Value: This property is used by the developers to hold the valid
range‟s minimum value.
 Maximum value: This property is used to hold a valid range‟s maximum
value.
 ControlToValidate: ControlToValidate enables the developers to set the
specific control that needs to be validated.
 Type: Here, Type properties are set after the above properties if necessary.
RangeValidator can compare the following data types:
1. String
2. Integer
3. Double
4. Date
5. Currency
<asp:rangevalidator id="UniqueId" runat="server"
controltovalidate="UniqueControlId" errormessage="ErrorMessageForFailure"
type="Integer" minimumvalue="”10”" maximumvalue="”500”">
</asp:rangevalidator>

CompareValidator Control
CompareValidator control compares the input control of one field to fixed value
or another control. This checks whether the entered value is the same or not. So, if
in any case, both entered values are not the same, it will give validation errors to
the users. This type of validation control is generally used in change password
functionality to confirm new password and date range fields like start date and end
date pair. Some of the most specific properties used under this control for different
types of comparisons are –
 Equal: This property of CompareValidator is used by developers to check if
the user input data is equal.
 Not Equal: It is a property that is used to check if the controls are not equal.
 LessThan: It checks out for less than a relationship.
 LessThanEqual: It figures out for less than equal relationships.
 Greater than: This property is used to check for a greater than relationship.
 GreaterThanEqual: It is a property that is used by the developers to check
for the GreaterThanEqual relationship.

S V PUBLICATIONS
48 BCA III YEAR - V SEM

3.2 Custom Validator Control

Q2. How to use a .NET CustomValidator control with server-side validation


Ans:
CustomValidator is a control that is used by the .NET software development
companies to customize and implement data validation as per the requirements
and conditions that occur. For instance, if the developer wants to check whether the
entered number is even or odd, then the existing controls cannot be used and for
this, the developers use CustomValidation controls. Some of the major properties of
custom validator controls in .NET are-
 ClientValidationFunction:- This property is used to set the name of the
function in the custom client-side script that is used for validation. In simple
words, this property is used to do client-side validation as well as server-
side validation and must be written in a scripting language, such as
JavaScript or VBScript.
 ValidateEmptyText:- It is a property that is used by the .NET developers to
set a Boolean value that indicates whether the empty text is valid or not.
Syntax of CustimValidator
<asp:customvalidator id="UniqueId" runat="server"
controltovalidate="UniqueControlId" errormessage="ErrorMessageForFailure"
clientvalidationfunction="”functionName”">
</asp:customvalidator>

ValidationSummary Control
ValidationSummary is a control that is used to display error messages. It is a
control that collects every type of validation control error message and is used by
the other validation controls on a web page. It then displays the error message on
the screen. Some of the major properties of validation summary control are –
 Forecolor: This is a property that is used to set the foreground color.
 DisplayMode: It is a property that is used by the developers to set the
display mode of the control.
 HeaderText: Header text is set at the top of the summary.

3.3 Group Validation and Accounting Validation

Q3. How to use Validation groups in ASP.NET 4.0? or What is an Validation


Groups in 2.0 and how can u create them?
Ans:
Validation Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation separately
for separate group. This kind of situation is handled using validation groups.

S V PUBLICATIONS
BCA III YEAR - V SEM 49

To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting their ValidationGroup
property.

Example
The following example describes a form to be filled up by all the students of a
school, divided into four houses, for electing the school president. Here, we use the
validation controls to validate the user input.

How to Implement Group Validation


Here's a step-by-step guide to creating a simple example of group validation in
an ASP.NET Web Forms application.

Step 1: Create a New Web Form


Create a new Web Form (e.g., GroupValidation.aspx) and add the following
markup:
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="GroupValidation.aspx.cs" Inherits="GroupValidation" %>

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Group Validation Example</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>User Registration</h2>

<asp:Label ID="LabelEmail" runat="server" Text="Email:"></asp:Label>


<asp:TextBox ID="TextBoxEmail" runat="server"></asp:TextBox>
<asp:RegularExpressionValidator
ID="RegularExpressionValidatorEmail"
runat="server"
ControlToValidate="TextBoxEmail"

S V PUBLICATIONS
50 BCA III YEAR - V SEM

ErrorMessage="Invalid email format!"


ValidationExpression="^[^@\s]+@[^@\s]+\.[^@\s]+$"
ForeColor="Red"
ValidationGroup="UserGroup" />
<br /><br />

<asp:Label ID="LabelPassword" runat="server" Text="Password:">


</asp:Label>
<asp:TextBox ID="TextBoxPassword" runat="server"
TextMode="Password"> </asp:TextBox>
<asp:RequiredFieldValidator
ID="RequiredFieldValidatorPassword" runat="server"
ControlToValidate="TextBoxPassword"
ErrorMessage="Password is required!" ForeColor="Red"
ValidationGroup="UserGroup" /> <br /><br />
<asp:Label ID="LabelConfirmPassword" runat="server"
Text="Confirm Password:"></asp:Label>
<asp:TextBox ID="TextBoxConfirmPassword" runat="server"
TextMode="Password"></asp:TextBox>
<asp:CompareValidator
ID="CompareValidatorPassword"
runat="server"
ControlToCompare="TextBoxPassword"
ControlToValidate="TextBoxConfirmPassword"
ErrorMessage="Passwords do not match!"
ForeColor="Red"
ValidationGroup="UserGroup" />
<br /><br />

<asp:Button ID="ButtonSubmit" runat="server" Text="Submit"


ValidationGroup="UserGroup" OnClick="ButtonSubmit_Click" />
<asp:ValidationSummary ID="ValidationSummary" runat="server"
HeaderText="Please correct the following errors:"
ForeColor="Red" ValidationGroup="UserGroup" />
</div>
</form>
</body>
</html>
Step 2: Code-Behind Logic
In the code-behind file (e.g., GroupValidation.aspx.cs), handle the submission
logic. Here‟s an example:

S V PUBLICATIONS
BCA III YEAR - V SEM 51

using System;
public partial class GroupValidation : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
string email = TextBoxEmail.Text; // Handle valid form submission here
string password = TextBoxPassword.Text;
// Perform further processing (e.g., save to database)
}
}
}

Explanation of Group Validation


1. ValidationGroup Property: Each validation control (e.g.,
RegularExpressionValidator, RequiredFieldValidator, CompareValidator,
and ValidationSummary) has a ValidationGroup property set to
"UserGroup". This groups these validations together.
2. Button Validation: The submit button also has the ValidationGroup
property set to "UserGroup", meaning it will only trigger validations within
that group.
3. Validation Summary: The ValidationSummary control will only display
errors for validations in the "UserGroup".

3.4 ADO.Net Database Services

Q4. Discuss in brief about ADO.net Database services?


Ans:
The .NET Framework includes its own data access technology i.e. ADO.NET.
ADO.NET is the latest implementation of Microsoft‟s Universal Data Access
strategy. ADO.NET consists of managed classes that allows .NET applications to
connect to data sources such as Microsoft SQL Server, Microsoft Access, Oracle,
XML, etc., execute commands and manage disconnected data.

ADO.NET Framework Data Providers


Data provider is used to connect to the database, execute commands and
retrieve the record. It is lightweight component with better performance. It also
allows us to place the data into DataSet to use it further in our application.

S V PUBLICATIONS
52 BCA III YEAR - V SEM

The .NET Framework provides the following data providers that we can use in
our application.

.NET Framework data provider Description


It provides data access for Microsoft SQL Server.
.NET Framework Data Provider
It requires the
for SQL Server
System.Data.SqlClient namespace.
.NET Framework Data Provider It is used to connect with OLE DB. It requires
for OLE DB the System.Data.OleDb namespace.
It is used to connect to data sources by using
.NET Framework Data Provider
ODBC. It requires
for ODBC
the System.Data.Odbc namespace.
.NET Framework Data Provider It is used for Oracle data sources. It uses
for Oracle the System.Data.OracleClient namespace.
It provides data access for Entity Data Model
EntityClient Provider applications. It requires
the System.Data.EntityClient namespace.
It provides data access for Microsoft SQL Server
.NET Framework Data Provider
Compact 4.0. It requires
for SQL Server Compact 4.0.
the System.Data.SqlServerCe namespace.

.NET Framework Data Providers Objects


Following are the core object of Data Providers.
Object Description
Connection It is used to establish a connection to a specific data source.
Command It is used to execute queries to perform database operations.
It is used to read data from data source. The DbDataReader is a base
DataReader
class for all DataReader objects.
It populates a DataSet and resolves updates with the data source.
DataAdapter The base class for all DataAdapter objects is the DbDataAdapter
class.

.NET Framework Data Provider for SQL Server


Data provider for SQL Server is a lightweight component. It provides better
performance because it directly access SQL Server without any middle connectivity
layer. In early versions, it interacts with ODBC layer before connecting to the SQL
Server that created performance issues.

The .NET Framework Data Provider for SQL Server classes is located in the
System.Data.SqlClient namespace. We can include this namespace in our C#
application by using the following syntax.
using System.Data.SqlClient;

S V PUBLICATIONS
BCA III YEAR - V SEM 53

This namespace contains the following important classes.


Class Description
It is used to create SQL Server connection. This class cannot be
SqlConnection
inherited.
It is used to execute database queries. This class cannot be
SqlCommand
inherited.
It represents a set of data commands and a database connection
SqlDataAdapter
that are used to fill the DataSet. This class cannot be inherited.
It is used to read rows from a SQL Server database. This class
SqlDataReader
cannot be inherited.
This class is used to throw SQL exceptions. It throws an
SqlException exception when an error is occurred. This class cannot be
inherited.

.NET Framework Data Provider for Oracle


It is used to connect with Oracle database through Oracle client. The data
provider supports Oracle client software version 8.1.7 or a later version. This data
provider supports both local and distributed
transactions.

Oracle Data Provider classes are located into


System.Data.OracleClient namespace. We must use
both System.Data.OracleClient and System.data to
connect our application with the Oracle database.
1. using System.Data;
2. using System.Data.OracleClient;

Which .NET Framework Data Provider is better


Selection of data provider is depends on the design and data source of our
application. Choice of optimum .NET Framework data provider can improve the
performance, capability and integrity of our application. The following table
demonstrates advantages and disadvantages of data provider.

Data Provider Note


.NET Framework Data It is good for middle-tier applications, single-tier
Provider for SQL Server applications that use Microsoft SQL Server.
.NET Framework Data It is good for single-tier applications that use
Provider for OLE DB Microsoft Access databases.
.NET Framework Data It is good for middle and single-tier applications
Provider for ODBC that use ODBC data sources.
.NET Framework Data It is good for middle and single-tier applications
Provider for Oracle that use Oracle data sources.

S V PUBLICATIONS
54 BCA III YEAR - V SEM

3.4.1 Overview of ADO.Net

Q5. What is ADO.NET? Discuss how does it work with few advantages of its
working?
Ans:
ADO.NET is a set of classes and tools in the .NET framework that enables
developers to interact with databases. It provides a bridge between the front-end
applications and the back-end database systems. Here‟s an overview of its key
components and features:

Key Components of ADO.NET


Connection:
 Represents a connection to a specific data source (like SQL Server, Oracle,
etc.).
 Example: SqlConnection for SQL Server.
Command:
 Used to execute commands against the database (e.g., SQL queries, stored
procedures).
 Example: SqlCommand for executing SQL statements.
DataReader:
 Provides a way to read a forward-only stream of data from a database.
 Example: SqlDataReader for reading data efficiently.
DataAdapter:
 Acts as a bridge between a DataSet and the database for retrieving and
saving data.
 Example: SqlDataAdapter for populating a DataSet from a SQL Server
database.
DataSet:
 An in-memory representation of data that can contain multiple tables and
relationships.
 Supports disconnected data access.
DataTable:
 Represents a single table of in-memory data.
 Contains rows and columns, similar to a database table.

Features of ADO.NET
 Disconnected Architecture: ADO.NET allows applications to work with
data while being disconnected from the database. You can load data into a
DataSet, work with it, and then save changes back to the database.
 Strongly Typed Data: You can create strongly-typed datasets that allow for
compile-time checking of data types.

S V PUBLICATIONS
BCA III YEAR - V SEM 55

 Support for Multiple Data Sources: ADO.NET can connect to different


types of databases (SQL Server, Oracle, MySQL, etc.) using different
provider classes.
 XML Support: ADO.NET can easily work with XML data, allowing you to
read and write XML documents.
 Performance: The use of DataReader for forward-only access provides high
performance for reading large amounts of data.

Common Use Cases


 Web Applications: Interacting with databases for dynamic web content.
 Windows Applications: Managing data in desktop applications.
 Data Processing: Reading, processing, and saving large datasets.

ADO.NET Code Examples


To retrieve data from a database, you can use the following ADO.NET
technologies:
 SqlClient: The code that follows assumes that you can connect to the
Northwind sample database on Microsoft SQL Server. It creates a
xref:System.Data.SqlClient.SqlCommand to fetch rows from the Products
table, adds a xref:System.Data.SqlClient.SqlParameter to restrict the results
to rows with a highest UnitPrice of 5, and connects using
System.Data.SqlClient.SqlConnection. After the code exits, resources are
closed and disposed, and the datareader is used to retrieve the results. In
System.Data.SqlClient, Microsoft.Data.SqlClient should be upgraded
instead for the time being. For more information, see Introducing the new
Microsoft.Data.SqlClient.
 OleDb: Assuming you can access the Microsoft Access Northwind sample
database, the code creates a OleDbCommand to select records from the
Products table, adds an OleDbParameter that restricts the result to rows

S V PUBLICATIONS
56 BCA III YEAR - V SEM

with a price greater than 5, and uses a OleDbConnection to open a


Datareader inside a using block. The code exits when the code finishes
executing or closes the resources it opened. The results are displayed in the
console window.
 Odbc: This code assumes that you have access to the Microsoft Access
Northwind sample database. It creates a System.Data.Odbc.OdbcCommand
to select rows from the Products table, adds a
System.Data.Odbc.OdbcParameter to restrict the results to rows with a
higher UnitPrice than the specified parameter value, in this case 5, and
opens a System.Data.Odbc.OdbcConnection inside a using block. After the
code exits, resources are closed and disposed of and resources are reopened.
A System.Data.Odbc.OdbcDataReader is used to read and display the data.
 OracleClient: This example requires you to connect to DEMO.CUSTOMER
on an Oracle server. You also need to include a reference to
System.Data.OracleClient.dll. The code displays the data in an
xref:System.Data.OracleClient.OracleDataReader.
 LINQ to Entities: The code used in this example returns data as an object
that represents Categories, which are projected as an anonymous type with
only the CategoryID and CategoryName properties. For more information,
see LINQ to Entities Overview.
 LINQ to SQL: This code creates an anonymous type that contains only the
CategoryID and CategoryName properties. It then projects the type to an
instance of Categories. The LINQ query returns data as Category objects.

Advantages of ADO.NET
 Interoperability: ADO.NET allows communication across heterogeneous
environments, meaning it can connect and interact with different types of
data sources and systems without being restricted to a single protocol or
data format. This flexibility is crucial for modern applications that may need
to integrate with various services and databases.
 Scalability: ADO.NET is designed to handle a growing number of clients
efficiently. Its architecture supports scalability, allowing applications to
expand and serve more users without a significant drop in performance.
This is particularly important for enterprise-level applications that
anticipate growth.
 Productivity: The framework provides a rich and extensible component
object model, which simplifies the development process. Developers can
quickly build robust data access applications, enhancing productivity and
reducing development time.
 Performance: ADO.NET improves performance over previous data access
technologies by utilizing a disconnected data model. This means that data
can be retrieved and manipulated without maintaining a constant

S V PUBLICATIONS
BCA III YEAR - V SEM 57

connection to the database, which can lead to better resource management


and faster application response times.
 Security: ADO.NET encapsulates data access operations, which helps in
hiding the underlying mechanisms of data movement. This encapsulation
adds an additional layer of security, protecting sensitive data and
operations from unauthorized access.
 Support for Multiple Data Sources: ADO.NET can connect to both
relational and non-relational databases, making it versatile for various
application needs. This capability allows developers to work with a wide
range of data sources, including SQL Server, Oracle, and even XML files.
 Rich Data Manipulation Capabilities: The framework provides a
comprehensive set of classes and methods for data manipulation, including
DataSets, DataTables, and DataAdapters. These components facilitate
complex data operations and make it easier to manage data in memory.

3.4.2 XML

Q6. What is XML used for in Web services? And How to Create XML Documents
in .NET
Ans:
XML is a cross-platform, hardware and software independent, text based
markup language, which enables you to store data in a structured format by using
meaningful tags. XML stores structured data in XML documents that are similar to
databases. Notice that unlike Databases, XML documents store data in the form of
plain text, which can be used across platforms.
In an XML document, you specify the structure of the data by creating a DTD or
an XML schema. When you include a DTD in an XML document, the software
checks the structure of the XML document against the DTD. This process of
checking the structure of the XML document is called validating. The software
performing the task of validating is called a validating parser.

.NET Support for XML


The .NET Framework has extensive support for working with XML documents.
In the .NET framework, the support for XML documents includes:
1. XML namespace
2. XML designer
3. XML Web Server control
4. XML DOM support

XML Namespace
The System.Xml namespace provides a rich set of classes for processing XML
data. The commonly used classes for working with XML data are:

S V PUBLICATIONS
58 BCA III YEAR - V SEM

 XmlTextReader: Provides forward only access to a stream of XML data and


checks whether or not an XML document is well formed. This class neither
creates as in-memory structure nor validates the XML document against the
DTD. You can declare an object of the XmlTextReader class by including the
System. Xml namespace in the application. The syntax to declare an object
of this class is as follows:
XmlTextReader reader = new XmlTextReader("XML1.xml");
It is important to note that the .xml file you pass as an argument to the
constructor of the XmlTextReader class exists in the \WINNT\System32
folder.
 XmlTextWriter: Provides forward only way of generating streams or files
containing XML data that conforms to W3C XML 1.0. If you want to declare
an object of the XmlTextWriter class, you must include the System.Xml. The
syntax to decare an object of this class is as follows:
XmlTextWriter writer = new XmlTextWriter(Response.Output);
Here Response.Output represents an outgoing HTTP response stream to
which you want to send the XML data.
 XmlDocument: Provides navigating and edinting features of the nodes in
an XML document tree. XmlDocument is the most frequently used class in
ASP.NET applications that use XML documents. It also supports W3C XML
DOM. XML DOM is an in-memory representation of an XML document. It
represents data in the form of hierarchically organized object nodes and
allows you to programmatically access and manipulate the elements and
attributes present in an XML document.
XmlDocument doc = new XmlDocument();
 XmlDataDocument: Provides support for XML and relational data in W3C
XML DOM. You can use this class with a dataset to provide relational and
non- relational views of the same set of data. This class is primarily used
when you want to access the functions of ADO.NET. The syntax to declare
an object of this class is as follows:
DataSet ds=new DataSet();
XmlDataDocument doc=new XmlDocument(ds)
 XmlPathDocument: Provides a read-only cache for XML document
processing by using XSLT. This class is optimizied for XSLT processing and
does not check for the conformity of W3C DOM. For this reason, you can
create an instance of this class to process an XML document faster. To create
an instance of the XPathDocument class, you need to include the
System.Xml.XPath namespace in the application. The Syntax to declare an
object of this class is as follows:
XmlPathDocument doc=new XmlPathDocument("XML1.xml");
 XmlNodeReader: Provides forward-only access to the data represented by
the XmlDocument or XmlDataDocument class. If you want to create an

S V PUBLICATIONS
BCA III YEAR - V SEM 59

instance of the XmlNodeReader class, you need to include the System.Xml


namespace. The syntax to declare an object of this class is as follows:
XmlDocument doc=new XmlPathDocument();
XmlNodeReader reader=new XmlNodeReader(doc);
 XslTransform: Provides support for a XSLT 1.0 style sheet syntax that
enables you to transform an XML document by using XSL style sheets. If
you want to create an instance of the XslTransform class, you need to
include the System.Xml.Xsl namespace in the application. The syntax to
declare an object of this class is as follows:
Xsltransform xslt = new XslTransform ();

XML Designer
Visual Studio .NET provides the XML designer that you can use to create and
edit XML documents. For example, if you need to create an XML document that
contains the details of books available in an online bookstore, you need to perform
the following steps by using the XML designer of Visual Studio .NET:
1. Create a new ASP.NET Web application.
2. Select the Add New Item option
3. Select XML File as the template from the right pane. Specify the name as
"books.xml" and click open.
4. The XML designer is displayed. The XML designer has automatically
generated a line that notifies the browser that the document being processed
is an XML document, as displayed in the figure:

5. At the bottom of the designer window, there are two tabs, XML and Data. In
the XML tab enter the following lines of code after the first line in the XML
designer:

S V PUBLICATIONS
60 BCA III YEAR - V SEM

6. The Data view displays the XML data represented by the XML document.
When you switch to the Data view, the data appears, as displayed in the
following figure:

In addition to just viewing data in the Data view, you can also add data directly
to an existing XML document. For this, just click on the new row below the existing
data and enter your values, and shown in the figure:

XML Web Server Control


An XML Web Server control is used to display the contents of an XML
document without formatting or using XSL Transformations. You can optionally
specify a XSLT style sheet that formats the XML document before it is displayed in
an XML server control. The XML Web Server control belongs to the
System.Web.UI.WebControls namespace. You can add an XML Web Server control
to a Web form by dragging the control from the Web forms tab of the toolbox.

S V PUBLICATIONS
BCA III YEAR - V SEM 61

The XML Web Server control has the following properties:


 DocumentSource: Allows you to specify the URL or the path of the XML
document to be displayed in the Web form.
 TransformSource: Allows you to specify the URL of the XSLT file, which
transforms the XML document into the required format before it is
displayed in the Web form.
 Document: Allows you to specify a reference to an object of the
XMLDocument class. This property is available only at runtime.
 Transform: Allows you to specify a reference to an object of the
XMLTransform class. This property is available only at runtime.

XML Document Object Model Support


When you want to access and display XML data in Web Applications, you use
the XML Web server control and set its properties at design time. In certain
situation, you may need to display the XML data based on specific conditions. In
such cases, you will have to access the XML data programmatically.

An XML document consists of elements and attributes. For this reason, you can
access XML data programmatically. Note that XML DOM allows you to access and
manipulate the elements and attributes present in an XML document
programmatically.

To implement XML DOM, the .NET framework provides a set of additional


classes included in the System.Xml namespace. These classes enable you to access
the XML data programmatically. Some of the classes in the System.Xml namespace
are as follows:
 XmlDocumentType: Represents the DTD used by an XML document.
 XmlElement: Represents one element from an XML document.
 XmlAttribute: Represents one attribute of an element.

3.5 XML to HTML

Q7. How to convert the XML to HTML by applying an XSL style sheet?
Ans:
XML (Extensible Markup Language) is a versatile markup language designed
for carrying and storing data. It allows users to define their custom tags, making it
highly flexible. XML is often used for data interchange between different systems,
enabling the sharing of structured information.

XML is also used to create web pages and web applications. It is dynamic
because it is used to transport the data not for displaying the data. The design goals
of XML focus on simplicity, generality, and usability across the Internet. It is a

S V PUBLICATIONS
62 BCA III YEAR - V SEM

textual data format with strong support via Unicode for different human
languages. Although the design of XML focuses on documents, the language is
widely used for the representation of arbitrary data structures such as those used in
web services.

Displaying XML Using XSLT


XSLT stands for Extensible Stylesheet Language Transformation.
 XSLT is used to transform XML document from one form to another form.
 XSLT uses Xpath to perform matching of nodes to perform these
transformation .
 The result of applying XSLT to XML document could be an another XML
document, HTML, text or any another document from technology
perspective.
 The XSL code is written within the XML document with the extension of
(.xsl).
 In other words, an XSLT document is a different kind of XML document.

XML Namespace: XML Namespaces are the unique names.


 XML Namespace is a mechanism by which element or attribute is assigned
to a group.
 XML Namespace is used to avoid the name conflicts in the XML document.
 XML Namespace is recommended by W3C.

XML Namespace Declaration:


It is declared using reserved attribute such as the attribute is xmlns or it can
begin with xmlns:
Syntax:
<element xmlns:name = "URL">
where
 Namespace starts with the xmlns.
 The word name is the namespace prefix.
 the URL is the namespace identifier.
Example:
Consider the following xml document named Table.xml :-
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="rule.css"?>
<tables>
<table>
<tr>
<td>Apple</td>
<td>Banana</td>
</tr>
</table>

S V PUBLICATIONS
BCA III YEAR - V SEM 63

<table>
<height>100</height>
<width>150</width>
</table>
</tables>

Xpath:
 Xpath is an important component of XSLT standard.
 Xpath is used to traverse the element and attributes of an XML document.
 Xpath uses different types of expression to retrieve relevant information
from the XML document.
 Xpath contains a library of standard functions.
Example:
bookstore/book[1] => Fetches details of first child of bookstore element.
bookstore/book[last()] => Fetches details of last child of bookstore
element.

Templates:
 An XSL stylesheet contains one or more set of rules that are called
templates.
 A template contains rules that are applied when the specific element is
matched.
 An XSLT document has the following things:
o The root element of the stylesheet.
o A file of extension .xsl .
o The syntax of XSLT i.e what is allowed and what is not allowed.
o The standard namespace whose URL is
http://www.w3.org/1999/XSL/Transform.

Example:
XML file:
Creating Students.xml as:
<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl "href="Rule.xsl" ?>
<student>
<s>
<name> Divyank Singh Sikarwar </name>
<branch> CSE</branch>
<age>18</age>
<city> Agra </city>
</s>
<s>
<name> Aniket Chauhan </name>

S V PUBLICATIONS
64 BCA III YEAR - V SEM

<branch> CSE</branch>
<age> 20</age>
<city> Shahjahanpur </city>
</s>
<s>
<name> Simran Agarwal</name>
<branch> CSE</branch>
<age> 23</age>
<city> Buland Shar</city>
</s>
<s>
<name> Abhay Chauhan</name>
<branch> CSE</branch>
<age> 17</age>
<city> Shahjahanpur</city>
</s>
<s>
<name> Himanshu Bhatia</name>
<branch> IT</branch>
<age> 25</age>
<city> Indore</city>
</s>
</student>

Updating Rule.xsl as:

<?xml version="1.0" encoding="UTF-8"?>


<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
<body>
<h1 align="center">Students' Basic Details</h1>
<table border="3" align="center" >
<tr>
<th>Name</th>
<th>Branch</th>
<th>Age</th>
<th>City</th>
</tr>
<xsl:for-each select="student/s">

S V PUBLICATIONS
BCA III YEAR - V SEM 65

<tr>
<td><xsl:value-of select="name"/></td>
<td><xsl:value-of select="branch"/></td>
<td><xsl:value-of select="age"/></td>
<td><xsl:value-of select="city"/></td>
</tr>
</xsl:for-each>
</table>
</body>
</html>
</xsl:template>
</xsl:stylesheet>

3.6 XML & Databases

Q8. What Is A XML Database? What are the two types of XML data?
Ans:
XML (eXtensible Markup Language) and databases often work together in
various applications. Here‟s an overview of how they interact and some key
concepts:

What is XML?
 Structure: XML is a markup language that encodes documents in a format
that is both human-readable and machine-readable. It uses a tree-like
structure consisting of elements, attributes, and text.
 Purpose: It is primarily used for data interchange between systems,
allowing different applications to share structured information.

XML databases are a type of document-oriented database that can store and
manage XML data efficiently.

There are two main types of XML databases:

S V PUBLICATIONS
66 BCA III YEAR - V SEM

 XML-enabled databases: They are relational databases that can store XML
data as tables, columns, or blobs, and provide functions or extensions to
convert, query, or manipulate XML data.
 Native XML databases: They are databases that are designed to store XML
data natively, as containers or collections, and provide native support for
XML standards and features.

XML-enable Database
XML-enable database works just like a relational database. It is like an extension
provided for the conversion of XML documents. In this database, data is stored in
table, in the form of rows and columns.

Native XML Database


Native XML database is used to store large amount of data. Instead of table
format, Native XML database is based on container format. You can query data by
XPath expressions.

Native XML database is preferred over XML-enable database because it is


highly capable to store, maintain and query XML documents.

XML and Databases Features


Storage:
 XML Databases: Some databases are specifically designed to store XML
data, such as BaseX, eXist-db, and MarkLogic. They allow for the storage,
retrieval, and manipulation of XML documents directly.
 Relational Databases: Many relational databases (like MySQL, PostgreSQL,
and Oracle) can store XML data in a text column or as a specific XML data
type. They usually provide functions to query XML data.
Data Interchange:
 XML is often used to transport data between heterogeneous systems. For
instance, web services use XML (such as SOAP) to facilitate communication.
Schema Definition:
 XML Schema (XSD): Defines the structure and data types of XML
documents. It ensures that XML data adheres to a specified format, making
validation possible.
 DTD (Document Type Definition): An older method for defining the
structure of XML documents, though less commonly used now compared to
XSD.
Querying XML:
 XPath: A language used to navigate through elements and attributes in an
XML document.
 XQuery: A powerful query language designed to query XML data, allowing
for complex searches and data manipulation.

S V PUBLICATIONS
BCA III YEAR - V SEM 67

Advantages:
 Flexibility: XML's hierarchical structure allows it to represent complex data
relationships.
 Self-descriptive: XML documents describe their own structure, making
them easier to understand without additional documentation.
Disadvantages:
 Verbosity: XML can become quite large due to its text-based nature.
 Performance: Parsing XML can be slower compared to more compact data
formats like JSON or binary formats.

Use Cases
 Web Services: Data exchange between client and server.
 Configuration Files: Applications often use XML for configuration settings.
 Data Serialization: Storing complex data structures in a platform-
independent way.

3.7 XML Support in .Net retrieve data with datasets & Data
Adapters

Q9. How to retrieve data from XML file in asp.net? How can you load an XML
file directly into a DataSet?
Ans:
In .NET, XML support for retrieving data using datasets and data adapters is a
powerful feature that allows developers to work with XML data easily. Here‟s an
overview of how to use datasets and data adapters with XML in .NET.

Key Concepts
 DataSet: A DataSet is an in-memory representation of data that can contain
multiple tables (DataTables), relationships, and constraints. It can be
populated from various data sources, including XML.
 DataAdapter: A DataAdapter serves as a bridge between a DataSet and a
data source, allowing for the retrieval and updating of data. For XML, the
XmlDataAdapter can be used.

Working with XML in .NET


1. Loading XML into a DataSet
You can load XML data into a DataSet using the ReadXml method. Here‟s an
example:
using System;
using System.Data;

S V PUBLICATIONS
68 BCA III YEAR - V SEM

class Program
{
static void Main()
{
DataSet dataSet = new DataSet();
dataSet.ReadXml("data.xml"); // Load XML data from a file
foreach (DataTable table in dataSet.Tables) // Display data from the DataSet
{
Console.WriteLine($"Table: {table.TableName}");
foreach (DataRow row in table.Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write($"{item} ");
}
Console.WriteLine();
}
}
}
}

2. Saving DataSet to XML


You can also save a DataSet back to XML using the WriteXml method:
dataSet.WriteXml("output.xml");

3. Using DataAdapter with XML


To use a DataAdapter with XML, you can utilize the XmlDataAdapter class.
This allows you to fill a DataSet with data from an XML source.

using System;
using System.Data;
using System.Data.SqlClient; // For SQL Server example
using System.Xml;
class Program
{
static void Main()
{
DataSet dataSet = new DataSet();
string xmlFilePath = "data.xml";
// Create an XmlDataAdapter to read from the XML file
using (XmlDataAdapter adapter = new XmlDataAdapter($"SELECT * FROM
[RootElement] FOR XML PATH('Row')", xmlFilePath))
{

S V PUBLICATIONS
BCA III YEAR - V SEM 69

adapter.Fill(dataSet);
}
foreach (DataTable table in dataSet.Tables) // Display the data
{
Console.WriteLine($"Table: {table.TableName}");
foreach (DataRow row in table.Rows)
{
foreach (var item in row.ItemArray)
{
Console.Write($"{item} ");
}
Console.WriteLine();
}
}
}
}

XML Data Access Methods in .NET


Method Use
 You only need read access
 Performance is your highest priority
XmlTextReader  You don‟t need XSD/DTD validation
 You don‟t need XSD type information at runtime
 You don‟t need XPath/XSLT services
 You need only read access
XmlValidatingReader  You need XSD/DTD validation
 You need XSD type information at runtime
 You need to update the document (read/write)
XmlDocument  Productivity is your highest priority
 You need XPath services
 You only need read access
 You need to execute an XSLT transformation
XPathNavigator
 You want to leverage an implementation (such as
XPathDocument)
 You need to update the document (read/write)
 You need greatest flexibility and functionality
ADO.NET DataSets
 You want greatest tool support
 You need interop-support

S V PUBLICATIONS
70 BCA III YEAR - V SEM

Presenting Data
UNIT Using ASP.Net
Presenting Data Using ASP.Net-Bound Controls- Data Source

IV Controls, Repeater and its uses, Data list control, data grid control
view and its importance, form view detail‟s view, list view. User
controls- Adding member to user controls, registering user control
,properties & methods ,Dynamically loading user controls, master
pages.

4.1 Bounded Controls

Q1. What are bound controls?


Ans:
Presenting data using ASP.NET
Presenting data using ASP.NET can be achieved through various methods
depending on the type of application (Web Forms, MVC, or Core). Here‟s an
overview of common approaches:
1. ASP.NET Web Forms
2. ASP.NET MVC
3. ASP.NET Core
4. DataTables and Client-Side Libraries
5. Data Binding with JavaScript (AJAX)
6. Using Charts and Graphs

Data-Bound Web Server Controls


Data-bound Web server controls are controls that can be bound to a data source
control to make it easy to display and modify data in your Web application. Data-
bound Web server controls are composite controls that combine other ASP.NET
Web controls, such as Label and TextBox controls, into a single layout.

For example, a data-bound control such as a DetailsView control can bind to a


set of results such as a table of employees containing each employee's name,
address, job title, and so on. Within the DetailsView control, you can bind Label
controls to a single data values such as the name or address field to create the data
layout in the page.

4.1.1 GridView Control


The GridView control is used to provide flexibility in working and display data
from the database. The data in the GridView control is displayed in the tabular
format. It has several properties assigned to the control. Some of the properties are
as mentioned below:

S V PUBLICATIONS
BCA III YEAR - V SEM 71

Property Description
It is a Boolean value indicating the control supports
AllowPaging
paging
It is a Boolean value indicating the control supports
AllowSorting
sorting
It accepts the current expression determining the
SortExpression
order of the row
It is used to get or set the data source object containing
Datasource
the data to populate the control
It is a Boolean value indicating that the user can edit
AutoGenerateEditButton
the record in the control
DataSourceID It indicates the data source control to be used
It is a Boolean value indicating that the user can delete
AutoGenerateDeleteButton
the record in the control
It is a Boolean value to indicate the columns are
AutoGenerateColumns
automatically created for each field of the data source
It is a Boolean value to indicate the column should be
AutoGenerateSelectButton
added to select the particular record
It gets the sorting direction of the column for the
SortDirection
control
It indicates the text to appear when there is no record
EmptyDataText
in the data source

4.1.2 DetailsView control


Details view control is used as a data bound control. It is used to render one
record at a time. User can insert, update and delete the record from the control.
Some of the properties of the DetailsView control is as shown below:
Property Description
It is a Boolean value to indicate the control supports
AllowPaging
navigation
It is used to populate the control with the data source
DataSource
object
It indicates the bound data source control with
DataSourceID
corresponding adapters
It is a Boolean value to indicate the column can be
AutoGenerateEditButton
edited by the user
It is a Boolean value to indicate the records can be
AutoGenerateDeleteButton
deleted
It is used to indicate the default display mode of the
DefaultMode
control

S V PUBLICATIONS
72 BCA III YEAR - V SEM

It is a Boolean value to indicate the rows are


AutoGenerateRows
automatically created for each field in the data source

Another important feature of DataBound controls is their built-in support for


CRUD functionality. Another important feature is that they are built to work with
DataSource controls (although you can still write your own code-behind that
manually sets the DataSource property and calls the DataBind()method, along with
handling the various CRUD-based events of the control).

DataBound controls have many key properties and methods; at their heart are
two central properties and one method:
 DataSource property - This can be assigned various kinds of collections,
such as List<T>, ICollection, an array, etc.
 DataSourceID property - This is the ID of some DataSource control on the
page that can be used as an "intermediary" for providing access to a
collection of data along with built-in CRUD support.
 DataBind() method - Calling this method tells the control to begin "un-
packing" the data that's available in its DataSource property (or through its
DataSourceID proxy).

ObjectDataSource Control
The ObjectDataSource control is designed to provide data to databound
controls via some object, such as an instance of a BLL class. There are other
DataSource controls (see Data Source Controls Overview for a list), but for our
purposes the ObjectDataSource fits well with the Client-Server approach used in
this course.

Setting up an ObjectDataSource control is fairly simple. Just choose Configure


data source … from the control's smart tag and follow the steps in the wizard to
identify your BLL class and the methods you want to use for CRUD functionality.

#DropDownList
A DropDownList control is used to render a collection of items as key/value
pairs in <option value="key">Text to display</option> tags for an HTML <select>
tag.

#ListView
A ListView control is far more flexible than a GridView in rendering its
collection of data, but with that flexibility comes more responsibility on the part of
the developer to specify how that rendering should take place. A ListView supports
Create, Read, Update, and Delete functionality, so it is in many respects an ideal
data-bound control to use for many situations.

S V PUBLICATIONS
BCA III YEAR - V SEM 73

The ListView uses a set of templates to control the rendering of its collection of
data. For details on each of the templates and links on how to use them, see the
MSDN documentation on the ListView Templates.

#Repeater
A Repeater control is a very basic control just for rendering data. It has no built-
in support for Create, Update or Delete functionality. Like the ListView, it uses a set
of templates to show items of data in its collection of data. For details on how to use
its templates, see the MSDN documentation on the Repeater Templates.

4.1.3 Data Pager control


Data Pager control is used to create interface for navigation through multiple
pages containing multiple records. The DataPager control has some properties
associated with it. The list of the properties is as mentioned below:
Property Description
It is used to get or set the number of data items to display in a
PageSize
page
PagedControlID It is used to set the control ID for the page
StartRowIndex It is used to get the index of the first item in a page
It is used to get the maximum number of rows to retrieve from
MaximumRow
the database for a page
It is used to get the total number of rows or items in the
TotalRowCount
datasource

4.2 Repeater and its uses

Q2. How to use the repeater control in ASP.NET


Ans:
The repeater control in ASP.NET provides a way to display repeated sets of
data in a customizable manner. It allows us to define templates for items,
alternating items, header, and footer sections, giving us full control over the layout
and appearance of the repeated data.

Parameters
The commonly used parameters for the repeater control are the following:
 ID specifies a unique identifier for the repeater control. This can be used to
reference the control programmatically.
 runat specifies where the control is processed. In the example below, the
control is processed on the server side.
 DataSource specifies the data source for the repeater control. It can be set to
an object, a collection, or a data source control.

S V PUBLICATIONS
74 BCA III YEAR - V SEM

A Repeater has five inline templates to format it.


 <HeaderTemplate>: Displays Header text for a Data Source collection and
applies a different style for the Header text.
 <AlternatingItemTemplate>: Changes the background color or style of
alternating items in a Data Source collection.
 <Itemtemplate>: It defines how each item is rendered from the Data Source
collection.
 <SeperatorTemplate>: It will determine the separator element that
separates each item in the item collection. It will be a <br> or <Hr> HTML
element.
 <FooterTemplate>: Displays a footer element for the Data Source collection.

Defining the repeater layout


We can define the layout, apply different styles to items and alternating items,
and insert separators as needed. We can add HTML elements and server controls
within this template to display the data. We can use data-binding expressions like
<%# DataBinding.Eval("PropertyName") %> to display values from the data source
for each item.

Here is a sample layout that uses the repeater control:


<asp:Repeater ID="MyRepeater" runat="server">
<HeaderTemplate>
<!-- Define layout for header section -->
</HeaderTemplate>
<ItemTemplate>
<!-- Define layout for each item -->
</ItemTemplate>
<SeparatorTemplate>
<!-- Define the separator for ItemTemplate items -->
</SeparatorTemplate>
<AlternatingItemTemplate>
<!-- Define layout for alternate items -->
</AlternatingItemTemplate>
<SeparatorTemplate>
<!-- Define the separator for AlternatingItemTemplate items -->
</SeparatorTemplate>
<FooterTemplate>
<!-- Define layout for footer section -->
</FooterTemplate>
</asp:Repeater>

S V PUBLICATIONS
BCA III YEAR - V SEM 75

Binding the repeater to a data source


 We can use the following process to bind the Repeater control to a data
source:
 In the code-behind file (default.aspx.cs), write the necessary code to retrieve
data from a data source.
 Assign the retrieved data to the Repeater's DataSource property. For
example: MyRepeater.DataSource = myData;.
 Call the DataBind method to bind the data to the Repeater:
MyRepeater.DataBind();.

public partial class Default : Page


{
protected void Page_Load(object sender, EventArgs e)
{
// Data source
List<string> myData = new List<string>
{
"Data Item 1",
"Data Item 2",
"Data Item 3",
"Data Item 4",
"Data Item 5"
};
// Set the data source for the Repeater control
MyRepeater.DataSource = myData;
MyRepeater.DataBind();
}
}

4.3 Data List Control

Q3. How To Use Data List Control In ASP.NET With Example.


Ans:
DataList is a Databound control to display and manipulate data in a web
application. It is a composite control that can combine other ASP.Net controls and it
is present in the form. The DataList appearance is controlled by its template fields.

The following template fields are supported by the DataList control:


 Itemtemplate: It specifies the Items present in the Datasource, it renders
itself in the browser as many rows present in the data source collection.
 EditItemTemplate: Used to provide edit permissions to the user.

S V PUBLICATIONS
76 BCA III YEAR - V SEM

 HeaderTemplate: Used to display header text to the data source collection.


 FooterTemplate: Used to display footer text to the data source collection.
 ItemStyle: Used to apply styles to an ItemTemplate.
 EditStyle: Used to apply styles to an EditItemTemplate
 HeaderStyle: Used to apply styles to a HeaderTemplate
 FooterStyle: Used to apply styles to a FooterTemplate.

Frequently used properties with DataList

Frequently used Events with DataList control


 Event: Event is a precise time that something happened.

The following is an example demonstrate the DataList Control with a bound


image and a FileUpload control:

S V PUBLICATIONS
BCA III YEAR - V SEM 77

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>
<style>
.itemstyle {
border-collapse: collapse;
background-color: aquamarine;
border: 1px solid red;
border-radius: 8px;
padding:4px;
}
tr {
height:40px;
}
table {
width: initial;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:DataList ID="dl1" runat="server"
RepeatDirection="Horizontal"
RepeatColumns="3"
OnEditCommand="dl1_EditCommand"
OnCancelCommand="dl1_CancelCommand"
OnUpdateCommand="dl1_updateCommand"
OnDeleteCommand="dl1_DeleteCommand" >
<HeaderTemplate>
<table>
<tr>
<td>
<h1>Student Information</h1>
</td>
</tr>

S V PUBLICATIONS
78 BCA III YEAR - V SEM

</table>
</HeaderTemplate>
<ItemStyle CssClass="itemstyle" />
<ItemTemplate>
<table border="1">
<tr>
<td>Employee ID:</td>
<td>
<asp:Label ID="lblempid" runat="server" Text='<%#
Eval("EmpId") %>'>
</asp:Label>
</td>
<td rowspan="5">
<asp:Image ID="empimg" runat="server" ImageUrl='
<%# "~/Images/" + Eval("EmpImage") %>' Height="180px"
Width="200px" />
</td>
</tr>
<tr>
<td>Employee Name:</td>
<td>
<asp:Label ID="lblempname" runat="server" Text='<%#
Eval("EmpName") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>Employee EmailId:</td>
<td>
<asp:Label ID="lblemailid" runat="server" Text='<%#
Eval("EmpEmailId") %>'>
</asp:Label>
</td>
</tr>
<tr>
<td>Employee Mobile Number</td>
<td>
<asp:Label ID="lblmbnum" runat="server" Text='<%#
Eval("EmpMobileNum") %>'>
</asp:Label>
</td>

S V PUBLICATIONS
BCA III YEAR - V SEM 79

</tr>
<tr>
<td colspan="3" style="text-align:left">
<asp:Button ID="btn1" runat="server"
CommandName="edit" Text="Edit" />
<asp:Button ID="btn2" runat="server" Text="Delete"
CommandName="delete" />
</td>
</tr>
</table>
</ItemTemplate>
<EditItemStyle CssClass="itemstyle" />
<EditItemTemplate>
<table border="1">
<tr>
<td>Employee Id:</td>
<td>
<asp:TextBox ID="txtempid" ReadOnly="true"
runat="server" Text='<%# Eval("EmpId") %>'>
</asp:TextBox>
</td>
<td rowspan="5">
<asp:Image ID="empimg" runat="server" ImageUrl='
<%# "~/Images/" + Eval("EmpImage") %>'
Height="180px" />
<br />
<asp:FileUpload ID="fu1" runat="server" />
</td>
</tr>
<tr>
<td>Employee Name</td>
<td>
<asp:TextBox ID="txtempname" runat="server" Text='<%#
Eval("EmpName") %>'>
</asp:TextBox>
</td>
</tr>
<tr>
<td>Employee EmailId</td>
<td>

S V PUBLICATIONS
80 BCA III YEAR - V SEM

<asp:TextBox ID="txtempmail" runat="server" Text='<%#


Eval("EmpEmailId") %>'>
</asp:TextBox>
</td>
</tr>
<tr>
<td>Employee Mobile Number</td>
<td>
<asp:TextBox ID="txtmbnum" runat="server" Text='<%#
Eval("EmpMobileNum") %>'>
</asp:TextBox>
</td>
</tr>
<tr>
<td colspan="3" style="text-align:left;">
<asp:Button ID="btn3" runat="server"
CommandName="update" Text="update" />
<asp:Button ID="btn4" runat="server"
CommandName="cancel" Text="Cancel" />
</td>
</tr>
</table>
</EditItemTemplate>
</asp:DataList>
</div>
</form>
</body>
</html>

Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;

S V PUBLICATIONS
BCA III YEAR - V SEM 81

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


{
SqlConnection con = new
SqlConnection(WebConfigurationManager.ConnectionStrings["myconnection"].Co
nnectionString);
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Bind();
}
}
public void Bind()
{
SqlCommand cmd = new SqlCommand("select * from Employee", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds, "Employee");
dl1.DataSource = ds.Tables[0];
dl1.DataBind();
}
protected void dl1_EditCommand(object sender, DataListCommandEventArgs e)
{
dl1.EditItemIndex = e.Item.ItemIndex;
Bind();
}
protected void dl1_CancelCommand(object sender,
DataListCommandEventArgs e)
{
dl1.EditItemIndex = -1;
Bind();
}
protected void dl1_updateCommand(object sender,
DataListCommandEventArgs e)
{
int index = e.Item.ItemIndex;
int empid =
Convert.ToInt32(((TextBox)dl1.Items[index].FindControl("txtempid")).Text);
string empname =
((TextBox)dl1.Items[index].FindControl("txtempname")).Text;
string empmail = ((TextBox)dl1.Items[index].FindControl("txtempmail")).Text;

S V PUBLICATIONS
82 BCA III YEAR - V SEM

long empmbnum =
Convert.ToInt64(((TextBox)dl1.Items[index].FindControl("txtmbnum")).Text);
FileUpload fu = (FileUpload)dl1.Items[index].FindControl("fu1");
// to update image name in data base and image in server, If he selectted new
Image
if (fu.HasFile)
{
string filepath = System.IO.Path.Combine(Server.MapPath("~/Images/"),
fu.FileName);
fu.SaveAs(filepath);
SqlCommand fcmd = new SqlCommand();
fcmd.CommandText = "update employee set EmpImage='"+fu.FileName+"'";
fcmd.Connection = con;
con.Open();
fcmd.ExecuteNonQuery();
con.Close();
}
SqlCommand cmd = new SqlCommand("update Employee set EmpName = '"
+ empname + "',EmpEmailId='" + empmail + "',EmpMobileNum =" + empmbnum
+ " where EmpId = " + empid + "", con);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i == 1)
{
Response.Write("<script>alert('Successfully updated')</script>");
dl1.EditItemIndex = -1;
Bind();
}
}
protected void dl1_DeleteCommand(object sender, DataListCommandEventArgs
e)
{
int index = e.Item.ItemIndex;
Label empid;
empid = (Label)dl1.Items[index].FindControl("lblempid");

SqlCommand cmd = new SqlCommand("delete from employee where EmpId


= " + Convert.ToInt32(empid.Text) + "", con);
con.Open();
int res = cmd.ExecuteNonQuery();

S V PUBLICATIONS
BCA III YEAR - V SEM 83

con.Close();
if (res == 1)
{
Response.Write("<script>alert('Successfully deleted')</script>");
Bind();
}

}
}

4.4 User Controls

Q4. What are user controls? How many types of control are there in ASP?
Ans:
A user control is an ASP.NET page that has been converted into a control. User
control enables you to reuse the same content and programming logic on multiple
ASP.NET pages. A user control has the extension, .ascx. It cannot be opened
directly in a browser. It must be used in another ASP.NET page.

You can use a user control to display the same static content such as header and
footer on multiple pages. This enables you to create the common content just once
and use it as many times as required. If the content changes, you just have to
modify it only in one file instead of on multiple pages.

Before using user control on .aspx page, you must first register it. The Register
directive has 3 attributes:
 TagPrefix: It is an alias for the user control‟s namespace. You can assign a
unique namespace to the user control using this attribute.
 TagName: It is an alias for the user control‟s class. You can use it to name
the user control. The user control name is used at the time of instantiating
the user control on the page.
 src: It is used to specify the virtual path to the user control file. You can
specify either the relative or absolute path to the file.

S V PUBLICATIONS
84 BCA III YEAR - V SEM

<%@ Register TagPrefix=”ankit” TagName=”uc1” src=”simpleusercontrol.ascx”


%>
Advantages of User Controls
 Re-usability: User controls can be reused on the same or on multiple pages.
 Independence: Each instance of a user control in a ASP.NET page is
independent of other instances of the user control.
 Language Independence: A user control can be written in a language
different from that used to develop the hosting page. Different user controls
on a page can be written in different languages.

ASP.NET allows the users to create controls. These user defined controls are
categorized into:
 User controls
 Custom controls

User Controls
User controls behaves like miniature ASP.NET pages or web forms, which
could be used by many other pages. These are derived from the
System.Web.UI.UserControl class. These controls have the following characteristics:
 They have an .ascx extension.
 They may not contain any <html>, <body>, or <form> tags.
 They have a Control directive instead of a Page directive.

Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into
a Dynamic Link Library (DLL) and used as any other ASP.NET server control. They
could be created in either of the following way:
 By deriving a custom control from an existing control
 By composing a new custom control combing two or more existing controls.
 By deriving from the base control class.

4.5 Adding member to user controls

Q5. How to add user control on run time in ASP.NET?


Ans:
To use a user control, you include it in an ASP.NET Web page. When a request
arrives for a page and that page contains a user control, the user control goes
through all of the processing stages that any ASP.NET server control performs. For
more information about these processing stages, see ASP.NET Page Life Cycle
Overview.

S V PUBLICATIONS
BCA III YEAR - V SEM 85

1. To include a user control in a Web Forms page


 In the containing ASP.NET Web page, create an @ Register directive that
includes:
 A TagPrefix attribute, which associates a prefix with the user control. This
prefix will be included in opening tag of the user control element.
 A TagName attribute, which associates a name with the user control. This
name will be included in the opening tag of the user control element.
 A Src attribute, which defines the virtual path to the user control file that
you are including.
2. In the body of the Web page, declare the user control element inside the form
element.
3. Optionally, if the user control exposes public properties, set the properties
declaratively.

Example:
<%@ Page Language="VB" %>
<%@ Register TagPrefix="uc" TagName="Spinner"
Src="~/Controls/Spinner.ascx" %>
<html>
<body>
<form runat="server">
<uc:Spinner id="Spinner1"
runat="server"
MinValue="1"
MaxValue="10" />
</form>
</body>

4.6 Registering User Control

Q6. How user controls can be included or added into asp net web pages explain
each step briefly?
Ans:
In order to user a User Control in an ASP.NET Web Form, it must first be
registered. Registering a User Control means adding the @Register directive to fully
identify the user control (name and path). The @Register directive takes three
attributes: TagPrefix, TagName, and Src. The first attribute identifies which prefix
to use when adding the user control, the second attribute is the name of the control,
and the third attribute identifier the relative path the .ascx file. The @Register
directive must be added to the top of each ASP.NET page that wants to use that
User Control. A typical @Register directive looks like:

S V PUBLICATIONS
86 BCA III YEAR - V SEM

<%@ Register TagName="Copyright" TagPrefix="dt"


Src="/controls/Copyright.ascx" %>
Now once the User Control has been registered, it can be placed any where on
the ASP.NET Web Form in the same fashion you would for any built-in control.
The syntax would be:
<tagprefix:tagname id="copyright1" runat="server" />

A User Control can have any number of instances in a Web Form, with each
instance running in its own sandbox, protecting the Web Form from any naming
conflicts. The following shows an example of an ASP.NET Web Form using a User
Control:

<%@ Register TagPrefix="uc1" TagName="Copyright" Src="Copyright.ascx" %>


<%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false"
Inherits="UserControls.WebForm1" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
...
<HEAD>
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="Form1" method="post" runat="server">
<uc1:Copyright id="Copyright1" runat="server"></uc1:Copyright>
</form>
</body>
</HTML>

4.7 Properties & Methods

Q7. Explain about Properties and Methods of user controls inASP.Net.


Ans:
In ASP.NET, user controls are reusable components that encapsulate a portion
of a web page's functionality. They are defined with the .ascx extension and can
include both markup and code. Here are some key properties and methods
associated with user controls in ASP.NET:

Properties
 ID: The unique identifier for the control on the page.
 Visible: A Boolean property that determines whether the control is
rendered on the page.
 Parent: A reference to the control‟s parent container, which is useful for
navigating the control hierarchy.

S V PUBLICATIONS
BCA III YEAR - V SEM 87

 Page: The Page object that contains the user control, providing access to the
page-level properties and methods.
 Context: Provides information about the HTTP request, such as the user‟s
session and application state.
 ClientID: A property that gets the client-side ID of the control, useful for
client-side scripting.
 EnableViewState: A Boolean property that indicates whether the control
maintains its state across postbacks.

Methods
 Load: This method is called when the control is loaded into the page. It's
often overridden to initialize data or settings.
 Render: This method outputs the control‟s markup to the page. It can be
overridden to customize the rendering process.
 OnInit: Called during the initialization phase of the control's lifecycle,
useful for setting up any required data or state.
 OnLoad: Called after the control is loaded but before the event handling
phase; ideal for tasks that require the control's properties to be set.
 OnPreRender: Called just before the control is rendered; useful for final
adjustments before the output is generated.
 FindControl: This method allows you to search for a child control by its ID
within the user control.
 DataBind: This method binds data from a data source to the user control,
typically used in data-driven applications.

Event Handling
User controls can also have custom events, allowing them to communicate with
the parent page or other controls. You can define events and raise them within the
control using EventHandler
delegates.

User Control Methods


//UserControl-Method.ascx
<script runat="server">
public string pattern = "*";
public void setPattern(int num)
{
for (int i=1; i<=num; i++)
Response.Write(pattern);
}
</script>

S V PUBLICATIONS
88 BCA III YEAR - V SEM

Method.aspx
<%@ Register TagPrefix="ankit" TagName="uc1" src="SimpleUserControl.ascx" %>
<script runat="server">
protected void Page_Load(object sender, EventArgs e)
{
UserControl1.setPattern(100);
}
</script>
<html>
<head>
<style>
body{font-family:Arial, sans-serif; font-size:10pt; background-color:Orange}
</style>
</head>
<body>
<ankit:uc1 id="UserControl1" pattern="@" runat="server"/>
<p>User Control Method</p>
</body>
</html>

4.8 Dynamically Loading User Controls

Q8. How to dynamically load a user control and specify parameters?


Ans:
Dynamically loading a user control in ASP.NET can be done using the
LoadControl method. This allows you to create instances of user controls at
runtime, which can be useful for scenarios like creating a dashboard with multiple
widgets or loading controls based on user actions.

Here‟s a step-by-step guide to dynamically load a user control:

Step 1: Create a User Control


Create a User Control:
Add a new User Control to your project (e.g., MyUserControl.ascx).
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind =
"MyUserControl.ascx.cs" Inherits="YourNamespace.MyUserControl" %>
<div>
<h2>Hello from MyUserControl!</h2>
</div>
Step 2: Load the User Control Dynamically
Load the Control in the Code-Behind:

S V PUBLICATIONS
BCA III YEAR - V SEM 89

In your ASPX page or another user control where you want to load this control,
use the following code to load it dynamically:
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
LoadMyUserControl();
}
}
private void LoadMyUserControl()
{
MyUserControl myControl = (MyUserControl)LoadControl
("~/MyUserControl.ascx");
Placeholder placeholder = new Placeholder(); // Create a placeholder or use an existing one
placeholder.Controls.Add(myControl);
Controls.Add(placeholder);
}
Step 3: Add a Placeholder in ASPX
Add a Placeholder in Your ASPX Page:
In your ASPX file, add a PlaceHolder control where the user control will be
loaded.
<asp:PlaceHolder ID="placeholder" runat="server"></asp:PlaceHolder>
Step 4: Handling Events (if needed)
Handle Events:
If your user control has events, you might need to handle them in the parent
page to ensure proper functionality.
Example with Event Handling
If your user control has a button and you want to handle its click event:
<asp:Button ID="btnClick" runat="server" Text="Click Me"
OnClick="btnClick_Click" /> // Inside MyUserControl.ascx
public event EventHandler ButtonClicked; // Inside MyUserControl.ascx.cs
protected void btnClick_Click(object sender, EventArgs e)
{
ButtonClicked?.Invoke(this, EventArgs.Empty);
}
// Inside your ASPX page code-behind
private void LoadMyUserControl()
{
MyUserControl myControl =
(MyUserControl)LoadControl("~/MyUserControl.ascx");

S V PUBLICATIONS
90 BCA III YEAR - V SEM

myControl.ButtonClicked += MyControl_ButtonClicked; // Subscribe to the


event
placeholder.Controls.Add(myControl);
}
private void MyControl_ButtonClicked(object sender, EventArgs e)
{
// Handle the event
}

4.9 Master Pages.

Q9. What is Master Page in ASP.NET? How to use master page and content page?
Ans:
A master page in ASP.NET is a template that defines the layout and visual
structure of one or more web pages on a website. It allows developers to create a
consistent look and feel across multiple pages by defining common elements such
as headers, footers, and navigation menus in a single location. Child pages can then
inherit the layout and visual elements of the master page, while still being able to
define their own unique content. This makes it easier to maintain and update the
overall design of a website, as changes only need to be made in one place.

Master Pages can also improve the performance and security of a website by
caching common elements on the browser and separating them from the unique
content. It can also enhance SEO by providing a consistent layout and navigational
links.

Benefits of MasterPage:
There are several benefits of using a Master Page in ASP.NET:
 Consistent layout: A Master Page allows for a consistent layout across all
pages in a website, which helps to improve the user experience.
 Code reuse: By defining a common layout in a Master Page, developers can
reduce the amount of code that needs to be written and maintained,
resulting in less time and effort required to create and update a website.

S V PUBLICATIONS
BCA III YEAR - V SEM 91

 Easy maintenance: By centralizing the layout on a Master Page, it is much


easier to make updates or changes to the overall look and feel of a website.
 Improved organization: Master Pages can help to organize the codebase of
a website, making it easier for developers to understand the structure and
layout of the site.
 Enhance security: By using Master Pages, the common elements like the
header, footer, and menus are separate and can be easily secured without
affecting the other pages.
 Better SEO: With a consistent layout and navigational links, Master Pages
can help improve the SEO of the website.
 Better performance: By using Master Pages, the common elements are
cached on the browser which improves the performance of the website.

Terminologies used in Masterpage


Below are several key terminologies used in Master Pages in ASP.NET:
1. Master Page: A file that defines the layout and common elements of a
website, such as a header, footer, and navigation menu.
2. Content Page: A file that "inherits" the layout defined in a Master Page and
contains unique content for a specific page.
3. ContentPlaceHolder: A control that marks a region in a Master Page where
content from a Content Page will be displayed.
4. MasterType: A directive that allows a Content Page to access properties and
methods of Master Page.
5. Content: A control that defines the content that will be displayed in a
ContentPlaceHolder.
6. MasterPageFile: A property that specifies Master Page that a Content Page
will inherit from.
7. Page directive: A control that specifies Master Page that a Content Page will
inherit from and other properties of the page.
8. Event handling: Master Pages can raise events and the content pages can
handle those events through event bubbling.
9. Nested Master Pages: Master Pages can also inherit from other Master
Pages.
10. Data binding: Master Pages can access data from the content pages and
bind it to its controls.

How to create MasterPage in ASP.NET


Follow the below steps to create MasterPage in ASP.NET:
 STEP 1: Open Visual Studio and create a new web project.
 STEP 2: Right-click on the project in Solution Explorer and select "Add" >
"New Item".

S V PUBLICATIONS
92 BCA III YEAR - V SEM

 STEP 3: In the Add New Item dialog box, select "Master Page" from the list
of templates.
 STEP 4: Give the master page a name and click "Add".
 STEP 5: The master page will be added to your project and opened in the
designer. You can add any elements you want to appear on every page of
your website to the master page, such as a header, footer, or navigation
menu.
 STEP 6: Once you have finished designing the master page, you can create a
new web page that uses it.
 STEP 7: Right-click on your project in Solution Explorer and select "Add" >
"New Item".
 STEP 8: In the Add New Item dialog box, select "Web Form" from the list of
templates.
 STEP 9: Give the web page a name and click "Add".
 STEP 10: In the newly created web page, you can now select the master
page from the list of available master pages.
 STEP 11: You can now define content placeholders on the master page to
define where the content from the child pages will appear.
 STEP 12: You can now add content to the child pages and it will be
rendered within the master page.

S V PUBLICATIONS
BCA III YEAR - V SEM 93

Asp.Net Error
UNIT Handling & Debug
ASP .Net Error Handling & Debug- Error handling & .Net returns,

V
Structured Error handling, Catching General Exception, Catching
Specific Exceptions, Throwing Exception Custom Exceptions ,Page level
Error handling, Application level Error Handling. Configuring
ASP.Net- Web machine Configuration, Global Assembly cache,
working with Assembling information, Managing Application State,
Http handlers, Applications & Server Events.

5.1 ASP .Net Error Handling & Debug

Q1. What isASP.net Error Handling & Debugging in ASP?


Ans:
When errors occur in an ASP.NET application, they either get handled or
propagates unhandled to higher scopes. When an unhandled exception propagates,
the user may be redirected to an error page using different ASP.NET configuration
settings. However, such a redirection may be prevented in the first place by
handling the exceptions that get thrown. Error handling in ASP.NET therefore, may
be divided into two separate logics:
 Redirecting the user to an error page when errors go unhandled.
 Handling exceptions when they get thrown.

Error handling in ASP.NET has three aspects:


 Tracing - tracing the program execution at page level or application level.
 Error handling - handling standard errors or custom errors at page level or
application level.
 Debugging - stepping through the program, setting break points to analyze
the code

Tracing
To enable page level tracing, you need to modify the Page directive and add a
Trace attribute as shown:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind=
"Default.aspx.cs" Inherits="errorhandling._Default" Trace ="true" %>
Now when you execute the file, you get the tracing information:

S V PUBLICATIONS
94 BCA III YEAR - V SEM

It provides the following information at the top:


 Session ID
 Status Code
 Time of Request
 Type of Request
 Request and Response Encoding
The status code sent from the server, each time the page is requested shows the
name and time of error if any.

Error Handling
Although ASP.NET can detect all runtime errors, still some subtle errors may
still be there. Observing the errors by tracing is meant for the developers, not for
the users.

Hence, to intercept such occurrence, you can add error handing settings in the
web.config file of the application. It is application-wide error handling. For
example, you can add the following lines in the web.config file:
<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
<configuration>

The <customErrors> section has the possible attributes:


 Mode: It enables or disables custom error pages. It has the three possible
values:
o On: displays the custom pages.
o Off: displays ASP.NET error pages (yellow pages)
o remoteOnly: It displays custom errors to client, display ASP.NET
errors locally.

S V PUBLICATIONS
BCA III YEAR - V SEM 95

 defaultRedirect: It contains the URL of the page to be displayed in case of


unhandled errors.

To put different custom error pages for different type of errors, the <error> sub
tags are used, where different error pages are specified, based on the status code of
the errors.

To implement page level error handling, the Page directive could be modified:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind=
"Default.aspx.cs" Inherits="errorhandling._Default" Trace ="true" ErrorPage=
"PageError.htm" %>

Because ASP.NET Debugging is an important subject in itself, so we would


discuss it in the next chapter separately.

Debugging
Debugging allows the developers to see how the code works in a step-by-step
manner, how the values of the variables change, how the objects are created and
destroyed, etc.

When the site is executed for the first time, Visual Studio displays a prompt
asking whether it should be enabled for debugging:

When debugging is enabled, the following lines of codes are shown in the
web.config:

<system.web>
<compilation debug="true">
<assemblies>
..............
</assemblies>
</compilation>
</system.web>
The Debug toolbar provides all the tools available for debugging:

S V PUBLICATIONS
96 BCA III YEAR - V SEM

The Debug Windows


Visual Studio provides the following debug windows, each of which shows
some program information. The following table lists the windows:

Window Description
Immediate Displays variables and expressions.
Autos Displays all variables in the current and previous statements.
Locals Displays all variables in the current context.
Watch Displays up to four different sets of variables.
Call Stack Displays all methods in the call stack.
Threads Displays and control threads.

5.2 Error handling & .Net returns

Q2. What is the best way to manage errors in .NET Core?


Ans:
When a runtime error occurs in ASP.NET an exception is thrown. Exceptions
offer a myriad of benefits over the classic ASP error-handling model, including
object-based errors, the ability to catch errors by type, and the ease of implementing
structured error handling. But there are instances in every application when
exceptions are not caught, and the result is a dreaded sight for developers: the
default ASP.NET error page.

You can accomplish this using a few well-placed lines of code in the
Global.asax. If you're unfamiliar with the Global.asax, it contains subroutines that
handle application-level and session events such as the start of the application
(Application_Start), the start of user sessions (Session_Start), and several others.

S V PUBLICATIONS
BCA III YEAR - V SEM 97

The handler of interest in this article is the Application_Error subroutine that runs
when an exception makes its way past your application code. The process for
handling these exceptions is as follows:
 Create an ASP.NET page called error.aspx; this is your custom error page.
We'll examine the code for it in a moment.
 In the Global.asax code-behind catch the last exception thrown.
 Pull out the InnerException from the exception caught above. This is
necessary because when an unhandled exception occurs .NET wraps it in a
new exception of type HttpUnhandledException.
 Place a few key values in the Session for retrieval on the custom error page.
 Clear the error from the server.
 Redirect to the custom error page.

S V PUBLICATIONS
98 BCA III YEAR - V SEM

Return Values in ASP.NET


When designing methods that return values in ASP.NET, consider the following:
 Return Types: Use appropriate return types. For example, if returning a
collection of items, consider returning IEnumerable<T> or a list.
 Returning Nullable Types: For methods that might not always return a
value, consider using nullable types or the Nullable<T> type.
 Using Result Objects: Instead of just returning raw data, you can return a
result object that includes the data and a success indicator.

Best Practices
 User-Friendly Error Messages: Always display user-friendly messages
without exposing sensitive information.
 Centralize Error Handling: Use centralized error handling for consistency.
 Logging: Implement robust logging to track errors and user actions.
 Validation: Validate input data to prevent exceptions before they occur.
 Testing: Regularly test your error handling code to ensure it behaves as
expected.

5.3 Structured Error Handling

Q3. What is structured error handling?


Ans:
The most specific technique for exception handling, and the most useful in
terms of gracefully recovering from the exception, is structured exception handling.
Structured exception handling should be familiar to developers of Java and C++,
for which it is standard practice, but it is new to the Visual Basic .NET language.
Microsoft's new language, C#, also provides built-in support for structured
exception handling.

Structured error handling in ASP.NET is essential for managing exceptions


gracefully and providing users with meaningful error messages while ensuring
application stability. Here are key concepts and techniques for implementing
structured error handling in ASP.NET:

1. Try-Catch Blocks
Using try-catch blocks allows you to catch exceptions at specific points in your
code.
try
{
// Code that may throw an exception
}
catch (Exception ex)
{

S V PUBLICATIONS
BCA III YEAR - V SEM 99

LogException(ex); // Log the exception


// Inform the user
ShowErrorMessage("An error occurred while processing your request.");
}
2. Global Error Handling
You can handle errors globally in ASP.NET using:
a. Web.config: Configure custom error pages in the web.config file:
<configuration>
<system.web>
<customErrors mode="On" defaultRedirect="Error.aspx">
<error statusCode="404" redirect="NotFound.aspx" />
</customErrors>
</system.web>
</configuration>
b. Global.asax: Handle errors in the Application_Error method in Global.asax:
protected void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError(); // Log the exception
LogException(ex);
Server.ClearError(); // Clear the error and redirect
Response.Redirect("~/Error.aspx");
}
3. Middleware (ASP.NET Core)
In ASP.NET Core, you can use middleware for global error handling:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
4. Logging Exceptions
Always log exceptions to help with debugging. You can use logging
frameworks like NLog, Serilog, or the built-in logging in ASP.NET Core.
private void LogException(Exception ex)
{
// Log to a file, database, or any logging service
}
5. Returning Friendly Error Responses
Instead of returning stack traces or technical details, provide user-friendly error
messages. Use error view pages to display these messages.

S V PUBLICATIONS
100 BCA III YEAR - V SEM

6. Validation Errors
For validation errors in forms, use model validation and return validation
errors to the user.
if (!ModelState.IsValid)
{
return View(model);
}
7. Using Exception Filters (ASP.NET Core)
Create custom exception filters to handle exceptions at a controller level:
public class CustomExceptionFilter : IExceptionFilter
{
public void OnException(ExceptionContext context)
{
LogException(context.Exception); // Log the exception
context.Result = new ViewResult { ViewName = "Error" }; // Set result
context.ExceptionHandled = true;
}
}
8. User-Friendly Error Messages
Ensure that any error messages displayed to users are clear and non-technical.
Avoid exposing stack traces or sensitive information.
9. Testing and Monitoring
Regularly test your error handling code to ensure it functions as expected.
Consider using monitoring tools (like Application Insights) to track errors in
production.

5.4 Catching General Exception

Q4. What is catching an exception? Is catching general exceptions really a bad


thing?
Ans:
When an exception occurs, it is passed up the stack and each catch block is
given the opportunity to handle it. The order of catch statements is important. Put
catch blocks targeted to specific exceptions before a general exception catch block
or the compiler might issue an error. The proper catch block is determined by
matching the type of the exception to the name of the exception specified in the
catch block. If there is no specific catch block, the exception is caught by a general
catch block, if one exists.

The following code example uses a try/catch block to catch an


InvalidCastException. The sample creates a class called Employee with a single

S V PUBLICATIONS
BCA III YEAR - V SEM 101

property, employee level (Emlevel). A method, PromoteEmployee, takes an object


and increments the employee level. An InvalidCastException occurs when a
DateTime instance is passed to the PromoteEmployee method.

public IActionResult Get()


{
try
{
var data = GetData(); //Assume you get some data here which is also likely to throw an exception in certain cases.
return Ok(data);
}
catch (Exception ex)
{
_logger.LogError(ex.Message);
return StatusCode(500);
}
}

Default Exception Handling Middleware in .NET


To make things easier, UseExceptionHandler Middleware comes out of the box
with ASP.NET Core applications. This when configured in the Program.cs, adds a
middleware to the pipeline of the application that will catch any exceptions in and
out of the application. A very straightforward implementation of middleware.

app.UseExceptionHandler(options =>
{
options.Run(async context =>
{
context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
context.Response.ContentType = "application/json";
var exception = context.Features.Get<IExceptionHandlerFeature>();
if (exception != null)
{
var message = $"{exception.Error.Message}";
await context.Response.WriteAsync(message).ConfigureAwait(false);
}
});
});

Global Exception Handling


For ASP.NET applications, you might want to catch exceptions globally. This
can be achieved using the Application_Error method in the Global.asax file:

S V PUBLICATIONS
102 BCA III YEAR - V SEM

protected void Application_Error(object sender, EventArgs e)


{
Exception ex = Server.GetLastError();
// Log the exception
// Response.Redirect can be used to show a friendly error page
Response.Redirect("~/ErrorPage.aspx");
}

Best Practices
 Avoid Catching Exception Everywhere: Catch specific exceptions where
possible to avoid hiding bugs.
 Logging: Always log exceptions for debugging and monitoring.
 User-Friendly Messages: Don‟t expose sensitive information in error
messages shown to users.
 Custom Error Pages: Configure custom error pages to handle different
HTTP status codes gracefully.

5.5 Catching Specific Exceptions

Q5. How to Use Specific Exceptions in a Catch Block


Ans:
If we want to handle the exceptions separately and make a particular decision
for each one, we should have specific information about the exceptions that may
occur. In this case, the best way is to use an individual catch block for each
exception.

To be precise, let‟s suppose we want to take two numbers from the user and
then divide the first one by the other. Due to the string format of the input values,
we should convert them to a numerical form. But if something goes wrong, we
want to show the end-user a reason for the failed operation.

Basic Structure
When you use specific exceptions in a catch block, you can catch different
exception types separately:
try
{
// Code that may throw exceptions
}
catch (ArgumentNullException ex)
{
// Handle ArgumentNullException
Console.WriteLine("A required argument was null: " + ex.Message);
}

S V PUBLICATIONS
BCA III YEAR - V SEM 103

catch (InvalidOperationException ex)


{
// Handle InvalidOperationException
Console.WriteLine("Invalid operation: " + ex.Message);
}
catch (IOException ex)
{
// Handle IOException
Console.WriteLine("I/O error occurred: " + ex.Message);
}
catch (Exception ex)
{
// Handle any other exceptions
Console.WriteLine("An unexpected error occurred: " + ex.Message);
}

Example:
public static int MultipleCatches(string numeratorParam, string
denominatorParam)
{
try
{
var numerator = Convert.ToUInt32(numeratorParam);
var denominator = Convert.ToUInt32(denominatorParam);

return (int)(numerator / denominator);


}
catch (FormatException)
{
Console.WriteLine("Format Exception!");
}
catch (DivideByZeroException)
{
Console.WriteLine("Divide By Zero Exception!");
}
catch (OverflowException)
{
Console.WriteLine("Overflow Exception!");
}
return -1;
}

S V PUBLICATIONS
104 BCA III YEAR - V SEM

Catching Multiple Exceptions in a Single Catch Block


Sometimes, we need to do the same work for all the exceptions. To do that, we
use the single-catch-block model and group the type of exceptions we want to
handle.

public static int SingleCatchWithWhen(string numeratorParam, string


denominatorParam)
{
try
{
var numerator = Convert.ToUInt32(numeratorParam);
var denominator = Convert.ToUInt32(denominatorParam);

return (int)(numerator / denominator);


}
catch (Exception ex) when (ex is FormatException ||
ex is DivideByZeroException ||
ex is OverflowException)
{
return -1;
}
}

Tips for Using Specific Exceptions


1. Order Matters: Place more specific exceptions before more general ones. The
first matching catch block will be executed, so if a general exception comes
first, it will catch all exceptions, preventing the specific handlers from
executing.
2. Use Multiple catch Blocks: You can use as many catch blocks as needed to
handle different types of exceptions.
3. Consider Custom Exceptions: If your application has unique error
conditions, consider creating custom exception classes that derive from
Exception and catch them specifically.
4. Logging: Always log exceptions in your catch blocks for monitoring and
debugging purposes.
5. Avoid Silent Failures: Don‟t just catch exceptions and do nothing; handle
them appropriately, whether that‟s logging, displaying a message, or taking
corrective action.

S V PUBLICATIONS
BCA III YEAR - V SEM 105

5.6 Throwing Exception Custom Exceptions

Q6. How do you avoid throwing exceptions? How to Throw Exceptions in .NET
Ans:
User-defined exceptions
Developers aren‟t stuck with .NET exceptions. Developers can create their own
exceptions customized for an application. User-defined exceptions are derived from
the base class Exception. The following is an example of a user-defined exception
called CustomerOrderNullException.

using System;
public class CustomerOrderNullException : Exception
{
public CustomerOrderNullException ()
{
}

public CustomerOrderNullException (string message) : base(message)


{
}

public CustomerOrderNullException (string message, Exception inner) :


base(message, inner)
{
}
}

Examples of throwing exceptions


.NET's try/catch blocks will catch exceptions. You should "catch" specific errors
and avoid using the general Exception class. The following is an example of
catching an array reference out of its assigned boundaries.

using System;
public string GetArrayValue (string[] array, int index)
{
try
{
return array[index];
}
catch (IndexOutOfRangeException ex)
{

S V PUBLICATIONS
106 BCA III YEAR - V SEM

ArgumentException newEx = new ArgumentException("Index is out of


assigned range.", "index", ex);
throw newEx;
}
}

Throw Exception For Exceptional Cases


This one might sound obvious, but it can be tricky sometimes. There is
somethings in our program that are expected to happen and we can‟t count them as
errors. So we‟ll not throw an exception. For example a search query might return
empty or the user login attempt might fail. In these circumstances it‟s better to
return some kind of meaningful message then throwing exception. As Steve
McConnell puts it in Code Complete book, “Exceptions should be reserved for
what‟s truly exceptional” as opposed to expected ones.

public ViewResult CreateProduct(CreateProductViewModel viewModel)


{
try
{
ValidateProductViewModel(viewModel);
CreateProduct(viewModel);
}
catch (ValidationException ex)
{
return View(viewModel);
}
}

5.7 Page level Error handling

Q7. How to Handle Page-Level Errors


Ans:
A page-level handler returns the user to the page where the error occurred, but
because instances of controls are not maintained, there will no longer be anything
on the page. To provide the error details to the user of the application, you must
specifically write the error details to the page.

You would typically use a page-level error handler to log unhandled errors or
to take the user to a page that can display helpful information.

S V PUBLICATIONS
BCA III YEAR - V SEM 107

This code example shows a handler for the Error event in an ASP.NET Web
page. This handler catches all exceptions that are not already handled within
try/catch blocks in the page.

<%@ Page language="c#" Codebehind="WebForm1.aspx.cs"


AutoEventWireup="false" Inherits="WebTest.WebForm1"
errorPage="/WebTest/ErrorPages/PageError.html"%>

After you handle an error, you must clear it by calling the ClearError method of
the Server object (HttpServerUtility class), otherwise you will see an error that has
previously occurred.

Code Level Error Handling


The try-catch statement consists of a try block followed by one or more catch
clauses, which specify handlers for different exceptions. When an exception is
thrown, the common language runtime (CLR) looks for the catch statement that
handles this exception. If the currently executing method does not contain a catch
block, the CLR looks at the method that called the current method, and so on, up
the call stack. If no catch block is found, then the CLR displays an unhandled
exception message to the user and stops execution of the program.

The following code example shows a common way of using try/catch/finally to


handle errors.
try
{
file.ReadBlock(buffer, index, buffer.Length);
}
catch (FileNotFoundException e)
{
Server.Transfer("NoFileErrorPage.aspx", true);
}
catch (System.IO.IOException e)
{
Server.Transfer("IOErrorPage.aspx", true);
}
finally
{
if (file != null)
{
file.Close();
}
}

S V PUBLICATIONS
108 BCA III YEAR - V SEM

5.8 Application level Error Handling


Q8. How to handle errors met when running ASP.NET applications.
Ans:
You can handle default errors at the application level either by modifying your
application's configuration or by adding an Application_Error handler in the
Global.asax file of your application.

You can handle default errors and HTTP errors by adding a customErrors
section to the Web.config file. The customErrors section allows you to specify a
default page that users will be redirected to when an error occurs. It also allows you
to specify individual pages for specific status code errors.

<customErrors mode="On"
defaultRedirect="/WebTest/ErrorPages/AppError.html">
<error statusCode="404" redirect="/WebTest/ErrorPages/404.html" />
</customErrors>

The mode attribute specifies whether to show user-defined custom error pages
or ASP.NET error pages. Three values are supported for this attribute:
 RemoteOnly - Custom error pages are shown for all remote users. ASP.NET
error pages with rich error information are displayed only for local users.
 On - Custom error pages are always shown, unless one is not specified.
When a custom error page is not defined, an ASP.NET error page will be
displayed which describes how to enable remote viewing of errors.
 Off - Custom error pages are not shown. Instead, ASP.NET error pages will
be displayed always, which will have rich error information.

<configuration>
<system.web>
<customErrors mode="On"
defaultRedirect="ErrorPage.aspx?handler=customErrors%20section%20-
%20Web.config">
<error statusCode="404"
redirect="ErrorPage.aspx?msg=404&amp;handler=customErrors%20section%20-
%20Web.config"/>
</customErrors>
</system.web>
</configuration>

Unfortunately, when you use the configuration to redirect the user to a different
page, you do not have the details of the error that occurred.

S V PUBLICATIONS
BCA III YEAR - V SEM 109

However, you can trap errors that occur anywhere in your application by
adding code to the Application_Error handler in the Global.asax file.
void Application_Error(object sender, EventArgs e)
{
Exception exc = Server.GetLastError();

if (exc is HttpUnhandledException)
{
// Pass the error on to the error page.
Server.Transfer("ErrorPage.aspx?handler=Application_Error%20-
%20Global.asax", true);
}
}

5.9 Configuring ASP.Net and Web machine

Q9. How do you configure your ASP.NET application?


Ans:
The behavior of an ASP.NET application is affected by different settings in the
configuration files:
 machine.config
 web.config
The machine.config file contains default and the machine-specific value for all
supported settings. The machine settings are controlled by the system
administrator and applications are generally not given access to this file.

An application however, can override the default values by creating web.config


files in its roots folder. The web.config file is a subset of the machine.config file.

If the application contains child directories, it can define a web.config file for
each folder. Scope of each configuration file is determined in a hierarchical top-
down manner.
Any web.config file can locally extend, restrict, or override any settings defined
on the upper level.

Visual Studio generates a default web.config file for each project. An


application can execute without a web.config file, however, you cannot debug an
application without a web.config file.

The following figure shows the Solution Explorer for the sample example used
in the web services:

S V PUBLICATIONS
110 BCA III YEAR - V SEM

In this application, there are two web.config files for two projects i.e., the web
service and the web site calling the web service.

The web.config file has the configuration element as the root node. Information
inside this element is grouped into two main areas: the configuration section-
handler declaration area, and the configuration section settings area.

The following code snippet shows the basic syntax of a configuration file:
<configuration>
<!-- Configuration section-handler declaration area. -->
<configSections>
<section name="section1" type="section1Handler" />
<section name="section2" type="section2Handler" />
</configSections>
<!-- Configuration section settings area. -->

<section1>
<s1Setting1 attribute1="attr1" />
</section1>

<section2>
<s2Setting1 attribute1="attr1" />
</section2>

<system.web>
<authentication mode="Windows" />
</system.web>
</configuration>

Configuration Section Handler declarations


The configuration section handlers are contained within the <configSections>
tags. Each configuration handler specifies name of a configuration section,

S V PUBLICATIONS
BCA III YEAR - V SEM 111

contained within the file, which provides some configuration data. It has the
following basic syntax:

<configSections>
<section />
<sectionGroup />
<remove />
<clear/>
</configSections>

It has the following elements:


 Clear - It removes all references to inherited sections and section groups.
 Remove - It removes a reference to an inherited section and section group.
 Section - It defines an association between a configuration section handler
and a configuration element.
 Section group - It defines an association between a configuration section
handler and a configuration section.
Application Settings
The application settings allow storing application-wide name-value pairs for
read-only access. For example, you can define a custom application setting as:

<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>
For example, you can also store the name of a book and its ISBN number:

<configuration>
<appSettings>
<add key="appISBN" value="0-273-68726-3" />
<add key="appBook" value="Corporate Finance" />
</appSettings>
</configuration>
Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

Connection Strings
The connection strings show which database connection strings are available to
the website. For example:

<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"

S V PUBLICATIONS
112 BCA III YEAR - V SEM

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=E:\\projects\datacaching\ /
datacaching\App_Data\ASPDotNetStepByStep.mdb"
providerName="System.Data.OleDb" />
<add name="booksConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\ \databinding\App_Data\books.mdb"
providerName="System.Data.OleDb" />
</connectionStrings>

System.Web Element
The system.web element specifies the root element for the ASP.NET
configuration section and contains configuration elements that configure ASP.NET
Web applications and control how the applications behave.

It holds most of the configuration elements needed to be adjusted in common


applications. The basic syntax for the element is as given:

<system.web>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>

S V PUBLICATIONS
BCA III YEAR - V SEM 113

<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</system.web>
The following table provides brief description of some of common sub elements
of the system.web element:

AnonymousIdentification
This is required to identify users who are not authenticated when authorization
is required.

Authentication
It configures the authentication support. The basic syntax is as given:

<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>

Authorization
It configures the authorization support. The basic syntax is as given:
<authorization>
<allow .../>
<deny .../>
</authorization>

Caching
It Configures the cache settings. The basic syntax is as given:
<caching>
<cache>...</cache>
<outputCache>...</outputCache>
<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>

S V PUBLICATIONS
114 BCA III YEAR - V SEM

</caching>

CustomErrors
It defines custom error messages. The basic syntax is as given:
<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">
<error. . ./>
</customErrors>

Deployment
It defines configuration settings used for deployment. The basic syntax is as
follows:
<deployment retail="true|false" />

HostingEnvironment
It defines configuration settings for hosting environment. The basic syntax is as
follows:
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity
It configures the identity of the application. The basic syntax is as given:
<identity impersonate="true|false" userName="domain\username"
password="<secure password>"/>

MachineKey
It configures keys to use for encryption and decryption of Forms authentication
cookie data.

It also allows configuring a validation key that performs message


authentication checks on view-state data and forms authentication tickets. The basic
syntax is:
<machineKey validationKey="AutoGenerate,IsolateApps" [String]
decryptionKey="AutoGenerate,IsolateApps" [String]
validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 |
HMACSHA384 | HMACSHA512 | alg:algorithm_name]
decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
/>

Membership
This configures parameters of managing and authenticating user accounts. The
basic syntax is:
<membership defaultProvider="provider name"
userIsOnlineTimeWindow="number of minutes" hashAlgorithmType="SHA1">

S V PUBLICATIONS
BCA III YEAR - V SEM 115

<providers>...</providers>
</membership>

Pages
It provides page-specific configurations. The basic syntax is:
<pages asyncTimeout="number" autoEventWireup="[True|False]"
buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]"
compilationMode="[Always|Auto|Never]"
controlRenderingCompatibilityVersion="[3.5|4.0]"
enableEventValidation="[True|False]"
enableSessionState="[True|False|ReadOnly]"
enableViewState="[True|False]"
enableViewStateMac="[True|False]"
maintainScrollPositionOnPostBack="[True|False]"
masterPageFile="file path"
maxPageStateFieldLength="number"
pageBaseType="typename, assembly"
pageParserFilterType="string"
smartNavigation="[True|False]"
styleSheetTheme="string"
theme="string"
userControlBaseType="typename"
validateRequest="[True|False]"
viewStateEncryptionMode="[Always|Auto|Never]" >
<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>

Profile
It configures user profile parameters. The basic syntax is:
<profile enabled="true|false" inherits="fully qualified type reference"
automaticSaveEnabled="true|false" defaultProvider="provider name">
<properties>...</properties>
<providers>...</providers>
</profile>

RoleManager
It configures settings for user roles. The basic syntax is:
<roleManager cacheRolesInCookie="true|false" cookieName="name"
cookiePath="/" cookieProtection="All|Encryption|Validation|None"

S V PUBLICATIONS
116 BCA III YEAR - V SEM

cookieRequireSSL="true|false " cookieSlidingExpiration="true|false "


cookieTimeout="number of minutes" createPersistentCookie="true|false"
defaultProvider="provider name" domain="cookie domain">
enabled="true|false"
maxCachedResults="maximum number of role names cached"
<providers>...</providers>
</roleManager>

SecurityPolicy
It configures the security policy. The basic syntax is:
<securityPolicy>
<trustLevel />
</securityPolicy>

UrlMappings
It defines mappings to hide the original URL and provide a more user friendly
URL. The basic syntax is:
<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
</urlMappings>

WebControls
It provides the name of shared location for client scripts. The basic syntax is:
<webControls clientScriptsLocation="String" />

5.10 Global Assembly Cache

Q10. What do you mean by Global Assembly Cache? How to: Install an assembly
into the global assembly cache.
Ans:
GAC stands for Global Assembly Cache. It is an area of memory reserved to
store the assemblies of all .NET applications that are running on a certain machine.
It shares assemblies among multiple .NET applications. The assemblies must have a
strong name and must be publicly shared to be installed in the GAC.

The concept of GAC is the result of the .NET architecture whose design
addresses the issue of “DLL hell” that existed in COM (Component Object Model).
Unlike in COM, there is no need for the assembly in GAC to be registered before its
use. Each assembly is accessed globally without any conflict by identifying its
name, version, architecture, culture and public key.

S V PUBLICATIONS
BCA III YEAR - V SEM 117

Following are the reasons why it is important to install an assembly into the
global assembly cache:
 Shared location - Assemblies that should be used by applications can be put
in the global assembly cache. For example, if all applications should use an
assembly located in the global assembly cache, a version policy statement
can be added to the Machine.config file that redirects references to the
assembly.
 File security - Administrators often protect the systemroot directory using
an Access Control List (ACL) to control write and execute access. Because
the global assembly cache is installed in the systemroot directory, it inherits
that directory's ACL. It is recommended that only users with Administrator
privileges be allowed to delete files from the global assembly cache.
 Side-by-side versioning - Multiple copies of assemblies with the same
name but different version information can be maintained in the global
assembly cache.
 Additional search location -The common language runtime checks the
global assembly cache for an assembly that matches the assembly request
before probing or using the codebase information in a configuration file.

It stores assemblies specifically designated to be shared by several applications


on the computer. An assembly must have a strong name to be installed in the GAC.

Common Tasks with the GAC


1. Installing Assemblies into the GAC:
 Use the Gacutil.exe command-line tool.
For example:
gacutil -i MyAssembly.dll
 Alternatively, you can use the Windows Installer for deploying
applications that include shared assemblies.
2. Viewing Assemblies in the GAC:
 Use the command:
gacutil -l
 This will list all assemblies currently in the GAC.
3. Removing Assemblies from the GAC:
 To remove an assembly, use:
gacutil -u MyAssembly
4. Location of the GAC:
 On a typical system, the GAC is located in:
C:\Windows\assembly (for .NET Framework)
C:\Program Files\Microsoft.NET\assembly (for .NET Core and later
versions)

S V PUBLICATIONS
118 BCA III YEAR - V SEM

Best Practices
 Use for Shared Libraries: Only use the GAC for assemblies that need to
be shared among multiple applications.
 Avoid Overuse: Not every assembly should be placed in the GAC; it‟s
best to keep it for truly shared libraries to minimize complexity.
 Strong Naming: Always ensure your assemblies are strongly named
before deploying to the GAC.

5.11 Working with Assembling Information

Q11. Explain how the assemblies and DLLs work in .NET?


Ans:
Assembly contains all the compiled types in your application along with their
Intermediate Language (IL) code. It is also the basic unit of deployment in .NET. In
the latest versions of .NET, i.e. .NET Core, an assembly is a file with a .dll extension,
which stands for Dynamic Link Library.

There are primarily four items in an assembly.

Compiled Types
The compiled IL code for all the types in your application.

Assembly Manifest
Contains the metadata needed by the Common Language Runtime, such as the
dependencies and versions that this DLL references.

Its purpose is to describe the assembly to the runtime via the assembly's data,
types, and functions. It's added automatically when you compile the source code to
build the assembly.

You can use a tool such as ildasm.exe to view the contents of an assembly.
Here's some of the data that an assembly manifest contains.
 Name and version number of the assembly
 A list of assemblies that this assembly references
 A list of types defined in the assembly
 Company and the copyright information
 Additional custom data

You can either edit the .csproj file or set the properties on the project in Visual
Studio to specify the assembly attributes. You can also specify them in the source
code itself, using the AssemblyInfo.cs file.

Explore our latest online courses and learn new skills at your own pace. Enroll
and become a certified expert to boost your career.

S V PUBLICATIONS
BCA III YEAR - V SEM 119

Application Manifest
Contains the metadata for the operating system about deployment and
administration. It's added during the build process. The application manifest file is
optional. If it is present, it's processed before the runtime loads the assembly.

To add an application manifest to your application, right-click the project in


Visual Studio and select Add > New Item > Application Manifest File. When you
build the application, it will be embedded into the output assembly.

Resources
Contains the resources needed by the application such as images and text.

5.12 Managing Application State

Q12. Which of the following can be used to manage state in ASP.NET


application?
Ans:
State Management is a process by which state and page information is
maintained over multiple requests for same or different pages. As HTTP is a
stateless protocol, server does not store any information once the response is sent
back to client based on his request. When user submits request again, the server
treats it as a new user. This is called stateless model. This model was workable
when static web sites were developed and hosted in the past. Now, with interactive
web sites or dynamic web site, there is a need to preserve some information to
identify user, interact with user again and again within same session and same
application. This concept is known as Stateful protocol. The information can be
related to user, data objects, web pages or server objects.

To support this kind of model, ASP.NET provides two types of State


Management techniques, server side and client side.

Server Side State Management Options


ASP.NET provides facility to save information on server side as well as in client
side. The following options are available in Server Side State Management.
 Application State: Application state allows saving of data at application
level which is accessible throughout the life of an application. The life of
application starts when IIS is started and ends when IIS is stopped.
 Session State: The session state persists till the user is active or session time
expires. When a user submits request, a session is started. The session gets
over either when time expires or user explicitly abandons the sessions. The
required information can be saved in session for later user by same user
within the same application.

S V PUBLICATIONS
120 BCA III YEAR - V SEM

 Profile Properties: This option also allows saving of user specific data. It is
similar to Session state except the data stored in Profile state never expires
on use this property, the SQLProfileProvider class needs to be configured. It
allows storing of data in SQL database. Since data is stored in database and
not in application memory, therefore there is no risk of losing data even if
IIS is restarted again and again.
 Cache: Caching is a technique by which frequently used data and web
pages are stored in cache so that repeated cost of retrieval can be avoided.
Storing frequently used data in cache ensures high availability, improved
performance and scalability. Cache is object of System.Web.Caching Cache
class. The main disadvantage of using Cache is that it is unreliable. The
previously stored data stored in cache is deleted automatically to meet
memory requirement of current process.

Client Side State Management Options


The options available in client side state management help in storing
information either in the page or at the client computer. No information is stored at
server side. The followings options are used for client side state management.
 View State: View state provides facility to preserve page and values of
controls at the client side. The information is stored after post back. Post
back is a request from user for the page which is not for the first time. If
value of IsPostBack property is true, it means page is not requested for the
first time. The view state can be at page level, application level, machine
level and control level. In page level state management, as long as the user
is on current page, the information is retained. Whenever user submits
form, the current state of page and controls are hashed into a string and
saved in hidden field of the page. More than one hidden field can be used if
data exceed limit set by MaxPageStateFieldLength property. When page is
sent to server, the page parses the view state string and restores the
information. This is default mechanism. The view state can be disabled at
any stage. The property EnableViewState="false" is used in code when it is
required to disable view state

The demonstrate the concept of view state option, consider an ASP.NET project
haring one ben Each time a button is clicked, it displays the number of times the
button is clicked.
 Control State: This is another client side state management option. This is
used when there is a need to store control data related to Custom control.
View state can be disabled but control state cannot be disabled.
 Hidden Field State: ASP.NET allows storing information in a hidden field
which is a server control and can be used to store information at page level.
The value of the hidden field is sent to HTTP form collection along with

S V PUBLICATIONS
BCA III YEAR - V SEM 121

value of other controls. The hidden file can be created in source file as given
below.<input type="hidden" id="username" name="username" value=""

This hidden field can be accessed in code behind file as given below. Dim st as
String = Request QueryString("username")
 Cookies: Cookie is a small amount of information that is stored in client
machine.
 QueryString: A QueryString contains the information that is sent to server
with URL.

5.13 Http Handlers

Q13. What is an HTTP handler?


Ans:
An HTTP handler is a component in a web server or web application that
processes incoming HTTP requests and generates HTTP responses. Handlers are
responsible for executing the logic associated with a specific route or endpoint in a
web application.

Key Points:
 Role in Web Applications: HTTP handlers receive requests from clients
(like web browsers) and perform actions such as retrieving data, processing
forms, or interacting with databases. They then send back an appropriate
response.
 Types of Handlers:
- Static Handlers: Serve static files like HTML, CSS, images, etc.
- Dynamic Handlers: Generate responses dynamically, often by
executing server-side code (e.g., PHP, Python, Node.js).
 Framework Integration: In many web frameworks (like Express for Node.js,
Flask for Python, or ASP.NET), handlers are often defined as functions or
methods that are mapped to specific URLs or routes.
 Middleware: Handlers can sometimes be part of a middleware stack, where
multiple handlers can process a request before reaching the final response.
Example in Code (Node.js with Express):
const express = require('express');
const app = express();
// Define an HTTP handler for GET requests to the root URL
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// Start the server
app.listen(3000, () => {

S V PUBLICATIONS
122 BCA III YEAR - V SEM

console.log('Server is running on port 3000');


});

Implementing the HTTPHandler


So with our problem definition, let us try to see how we can handle the request
for .cspx pages using HTTPHandlers. First we need to have the handler class with
us, so let us create the handler class.

public class CspxHandler :IHttpHandler


{
public bool IsReusable
{
get { return false; }
}

public void ProcessRequest(HttpContext context)


{

}
}

The class should have a method ProcessRequest and a property called


IsReusable. The property tells whether this handler can be reused or not and the
method will be called whenever a request for that type comes. But wait, Where
have we defined the type of request where this handler should be invoked? This
can be defined either in IIS, if we have a handler common to all the sites running on
that server or we can configure it in web.config file, if the handler is specific for a
website. Let's do that in web.config file for now.

<httpHandlers>
<add verb="*" path="*.cspx" type="CspxHandler"/>
</httpHandlers>
Here we registered our handler to specify that if any request for .cspx file
comes, it should be forwarded to our handler.

Now, since we don't have any "real" files with .cspx extension, what we will do
is we will handle the request for .cspx and in turn push the user to the
corresponding .aspx file.

public class CspxHandler :IHttpHandler


{
public bool IsReusable
{

S V PUBLICATIONS
BCA III YEAR - V SEM 123

get { return false; }


}
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";

if (context.Request.RawUrl.Contains(".cspx"))
{
string newUrl = context.Request.RawUrl.Replace(".cspx", ".aspx");
context.Server.Transfer(newUrl);
}
}
}
Whenever a request for .cspx file comes, we will handle it in our handler and
show the corresponding .aspx file instead. Let's see how it works.

5.14 Applications & Server Events

Q14. Which are the various events in application server? What are events in web
application?
Ans:
ASP.NET provides important feature event handling to Web Forms. It let us to
implement event-based model for our application. As a simple example, we can
add a button to an ASP.NET Web Forms page and then write an event handler for
the button's click event. ASP.NET Web Forms allows events on both client and
server sides.

S V PUBLICATIONS
124 BCA III YEAR - V SEM

In ASP.NET Web Forms pages, however, events associated with server controls
originate on the client but are handled on the Web server by the ASP.NET.

ASP.NET server control events


ASP.NET web form supports many server controls like Button, TextBox etc.
Each control has associated events. There are three types of server control events.
 Postback event
 Cached event
 Validation event

Postback event
This event sends the page to server for processing. This causes the page a
round-trip to the server.

Cached event
This event stores page data that gets processed when page is submit to the
server by postback event.

Validation event
This event is handled on the page just before the page is posted back to server.
The order of server control events on a Web form is below.
1. First validations Event occurs just before the page is submitted to the server.
2. Postback Event occurs that cause the page to be submitted to the server.
3. Page_Init and Page_Load events are handled.
4. Cached events are handled.
5. Lastly, the event that caused the postback is processed.

Controls are small building blocks of the graphical user interface, which include
text boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using
these tools, the users can enter data, make selections and indicate their preferences.

Controls are also used for structural jobs, like validation, data access, security,
creating master pages, and data manipulation.

ASP.NET uses five types of web controls, which are:


 HTML controls
 HTML Server controls
 ASP.NET Server controls
 ASP.NET Ajax Server controls
 User controls and custom controls

ASP.NET server controls are the primary controls used in ASP.NET. These
controls can be grouped into the following categories:
 Validation controls - These are used to validate user input and they work
by running client-side script.

S V PUBLICATIONS
BCA III YEAR - V SEM 125

 Data source controls - These controls provides data binding to different


data sources.
 Data view controls - These are various lists and tables, which can bind to
data from data sources for displaying.
 Personalization controls - These are used for personalization of a page
according to the user preferences, based on user information.
 Login and security controls - These controls provide user authentication.
 Master pages - These controls provide consistent layout and interface
throughout the application.
 Navigation controls - These controls help in navigation. For example,
menus, tree view etc.
 Rich controls - These controls implement special features. For example,
AdRotator, FileUpload, and Calendar control.

Event Handling in ASP.NET


Events is the means by which a process communicates. For example, interrupts
are caused by the system. The application should be able to respond to and manage
events when they occur. Examples of events are a mouse click, keypress, changed
text, button click, mouse movements, or any other system-generated notification.

In ASP.NET. client-side events are raised and handled by the server. For
example, the user might click a browser button. Then a click event occurs. The
browser handles this client-side event, which sends it to the server to be processed.

The event handler is a function on the server that describes what to execute
when an event is raised. As a result, when the event message is sent to the server, it
checks to see if the click event has a handler associated with it. The event handler is
executed if it has.

WebForms is benefited from ASP.NET's feature of event handling. It enabled us


to create an event-based model for our app. We can add a simple button to an
ASP.NET Web Forms page and then construct an event handler for a button's click
event as a simple example. ASP.NET WebForms support both client and server
events.

On the other hand, events linked with server controls in ASP.NET Web Forms
pages originate on the client but are handled by the ASP.NET on the Web server.
The event-handier methods in ASP.NET WebForms follow a standard.Net
Framework approach.

All events take two arguments: an object that represents the object that
triggered the event and an event object that contains any event-specific data.

S V PUBLICATIONS
126 BCA III YEAR - V SEM

Arguments in Event Handling


The ASP.NET event handlers require two parameters and return void. The
object that is raising the event is represented by the first parameter, and the event
argument is represented by the second parameter.
An event's general syntax is as follows:
private void EventName(object sender, EventArgs e);

Application Events
Some of the application events are:
 Application Jnit: When an application initializes for the first time, the
Application Init event is triggered.
 Application_Start: When an application starts for the first time, the
Application Start event is ired.
 Application_BeginRequest: Each time a new request arrives, the
Application BeginRequest event is triggered.
 Application_EndRequest: When an application closes, the Application
EndRequest event is triggered.
 Application_AuthenticateRequest: A request is ready to be authenticated
when the Application AuthenticateRequest event occurs. This event can be
used to check for the user's responsibilities and rights if you're using Forms
Authentication.
 Application_Error: When an unhandled error occurs in the application, the
Application Error event is triggered.
 Application_End: When the application closes or times out, the Application
End event is the last of its kind. It usually provides cleanup logic for the
program.

Session Events
Some of the session events are:
 Session_Start: When a user's session is started for the first time, the Session
Start event fired. This is usually where session startup logic code is kept.
 Session_End: When a single user Session expires or times out, the Session
End Event is triggered.
Page and Control Events
Some of the common page and control events are:
 Disposed: When the page or control is released, it is raised.
 Data Binding: When a control binds to a data source, it raises the
DataBinding event.
 Init: When the page or control is initialized, it raises the init event.
 Error: When an unhandled exception is thrown, an error is thrown as a page
event.
 Load: When a page or control is loaded, this event is triggered.
 PreRender: When the page or control is about to be rendered, the
PreRender event is triggered.
 Unload: When a page or control is unloaded from memory, this event is
triggered.

S V PUBLICATIONS
BCA III YEAR - V SEM 127

MULTIPLE CHOICE QUESTIONS

1. ASP.NET is a ____. [ B ]
(A) Client-Side technology (B) Server-side technology
(C) Both (D) None
2. Which of the following programming language can be used with [ C ]
ASP.NET?
(A) C#.NET (B) VB.NET (C) Both (D) None
3. Which form does Postback occur? [ C ]
(A) Win Forms (B) HTML Forms (C) Web Forms (D) All
4. What namespace is used for ASP.NET Web Form by default? [ D ]
(A) System.Web.Form (B) System.Web.UI.Page
(C) System.Web.GUI.Page (D) System.Web.UI.Form
5. Which term is used for pages that depend on the Master page? [ A ]
(A) Content Pages (B) Master Pages (C) Web Pages (D) None
6. Which of the following is not an ASP.NET component? [ A ]
(A) LinkCounter (B) Counter (C) AdRotator (D) File Access
7. Which protocol is used to call a web service? [ B ]
(A) SOAP Protocol (B) HTTP Protocol (C) TCP Protocol (D) FTP Protocol
8. Which of the following is NOT a valid HTTP method? [ A ]
(A) FETCH (B) get (C) Post (D) Delete
9. Which method is used in ASP.Net to preserve page and control values [ C ]
between round trips?
(A) Restore (B) Modeling (C) View State (D) Model Preserve
10. The Global.asax file is derived from the ____ class. [ D ]
(A) System.UI (B) SoapApplication (C) Application (D) HttpApplication
11. IIS is a _____________ ? [ A ]
(A) Web Browser (B) Web crawler (C) Web Server (D) None
12. Which ASP.NET technology is used to handle asynchronous HTTP [ A ]
requests?
(A) ASP.NET Web API (B) ASP.NET Core
(C) ASP.NET MVC (D) ASP.NET AJAX
13. What is the purpose of the Global.asax file in an ASP.NET application? [ A ]
(A) Handling application-level events (B) Managing session data
(C) Defining routing rules (D) Configuring authentication
14. Which ASP.NET component is used to validate user input on the [ C ]
client- side?
(A) RequiredFieldValidator (B) CompareValidator
(C) RegularExpressionValidator (D) CustomValidator
15. How do you open a database connection using SqlConnection in [ C ]

S V PUBLICATIONS
128 BCA III YEAR - V SEM

ADO.NET?
(A) connection.Start(); (B) connection.Open();
(C) connection.Connect(); (D)connection.Begin();
16. How can you handle exceptions securely in an ASP.NET application? [ B ]
(A) By showing detailed error messages
(B) By logging errors and showing generic error pages
(C) By ignoring errors (D) By redirecting to a static page
17. How do you handle exceptions in a Web API? [ D ]
(A) By using try-catch blocks (B) By using exception filters
(C) By using middleware (D) All of the above
18. What is the primary purpose of ASP.NET Identity? [ C ]
(A) To manage sessions (B) To handle HTTP requests
(C) To provide authentication and authorization
(D) To manage database connections
19. What is the primary purpose of the web.config file in deployment? [ B ]
(A) To manage database connections (B) To configure application settings
(C) To handle user sessions (D) To optimize performance
20. What is the purpose of the Debug mode in ASP.NET? [ C ]
(A) To optimize the application (B) To deploy the application
(C) To allow for better error tracking and debugging
(D) To manage user sessions

FILL IN THE BLANKS

1. ASP.NET stands for ______________ .NET. (Active Server Pages)


2. ASP.NET is a ____ technology used for web development. (Server Side)
3. ________ can be used with both C#.NET and ASP.NET for web
development. (ASP.NET)
4. The extension of ASP.NET page is ________. (.aspx.)
5. It is an _______ control that is used to select a choice from the group of
choices. (ASP.NET)
6. The IIS stands for ___________. (Internet Information Services)
7. The ASP.NET web supports an ________ application model. (event-driven)
8. The term is used for pages that depend on the ____ are Content Pages.
(Master page)
9. The IIS is a web server, which is used to deploy _______. (web applications)

S V PUBLICATIONS
BCA III YEAR - V SEM 129

10. ASP.Net was developed by ______________. (Microsoft)


11. The purpose of the Global.asax file in an ASP.NET application is __________
(Handling application-level events)
12. _____________ in ASP.NET refers to preserving data over multiple requests.
(State management)
13. _____ securely involves logging errors for developers and showing generic
error pages to users to avoid revealing sensitive information. (Handling
exceptions)
14. The ______ method is used in Web API to retrieve data from a server.(GET)
15. ____ in Web API can be done using try-catch blocks, exception filters, and
middleware. (Handling exceptions)
16. ASP.NET Identity is used to manage _________ & _______in ASP.NET
applications. (authentication, authorization)
17. The __________ file is used to configure application settings during the
deployment of an ASP.NET application.(web.config)
18. Errors in an ASP.NET application can be handled globally by handling the
_________ event in the Global.asax file. (Application _Error)
19. _______ mode in ASP.NET allows developers to track and fix errors more
efficiently by providing detailed error messages and stack traces. (Debug)
20. The purpose of the App_Data folder in an ASP.NET application is
____________ (To store application data)

Important QUESTIONS

UNIT – I
1. What is ASP.Net? Explain about web Applications with web servers?
2. Write about Web servers, IIS and APACHE?
3. Discuss about Web-browser and Web support languages.
4. Discuss in detail about HTTP?
5. Explain the TCP/IP role in web development.
6. Discuss briefly about ASP.Net framework, Name spacesin IDE development
process.

S V PUBLICATIONS
130 BCA III YEAR - V SEM

UNIT – II
1. Write about ASP.Net web forms
2. What are page directives and its uses.
3. Write about separate code and design.
4. Write a short note on New Code Behind techniques.
5. Explain about the ASP.net server control and working with server control.
6. Explain about the applying styles to controls themes and skins.

UNIT – III
1. Explain about Web form validation controls
2. Write about Groups Validation and Accounting Validation.
3. Discuss about briefly ADO.Net Database Services.
4. What is ADO.Net and XML?
5. How to Convert XML to HTML?
6. Explain about XML and Databases and Support in XML.
UNIT – IV
1. Write about Bound Control- Data Source Control.
2. Write about Repeaters and its uses.
3. Explain about Data list control
4. What are Data grid control view and its importance?
5. Write about form view, detail‟s view and list view?
6. What are User controls? How to add members to user controls and register
user control?
7. Explain about properties and methods, Dynamically load user controls.
8. Write about Master Page?

UNIT – V
1. What is ASP.Net error handling and debugging?
2. Explain about error handling and .Net returns?
3. Write about structured error handlimg?
4. Discuss about the following
a. Catching general exceptions
b. Catching Specific exceptions
c. Throwing exceptions
5. Write about page level and Application level Error Handling.
6. Write about Managing Applications.
7. Explain about Http Handling and its Application.
8. Which are the various events in application server? What are events in web
application?

S V PUBLICATIONS

You might also like