aspnet
aspnet
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.
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.
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.
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.
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.
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.
S V PUBLICATIONS
4 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 5
S V PUBLICATIONS
6 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 7
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.
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.
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.
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
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.
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
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.
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,
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.
The full form of ASP is Active Server Pages, and .NET is Network Enabled
Technologies.
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.
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.
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.
S V PUBLICATIONS
BCA III YEAR - V SEM 15
S V PUBLICATIONS
16 BCA III YEAR - V SEM
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.
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.
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.
S V PUBLICATIONS
BCA III YEAR - V SEM 19
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.
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
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
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.
S V PUBLICATIONS
22 BCA III YEAR - V SEM
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
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.
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.
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
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
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.
S V PUBLICATIONS
28 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 29
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.
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.
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.
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.
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.
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.
S V PUBLICATIONS
34 BCA III YEAR - V SEM
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:
S V PUBLICATIONS
36 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 37
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.
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.
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.
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:
S V PUBLICATIONS
40 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 41
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
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>
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" />
S V PUBLICATIONS
BCA III YEAR - V SEM 43
S V PUBLICATIONS
44 BCA III YEAR - V SEM
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.
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
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
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.
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.
<!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>
S V PUBLICATIONS
50 BCA III YEAR - V SEM
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)
}
}
}
S V PUBLICATIONS
52 BCA III YEAR - V SEM
The .NET Framework provides the following data providers that we can use in
our application.
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
S V PUBLICATIONS
54 BCA III YEAR - V SEM
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:
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
S V PUBLICATIONS
56 BCA III YEAR - V SEM
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
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.
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
S V PUBLICATIONS
BCA III YEAR - V SEM 59
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:
S V PUBLICATIONS
BCA III YEAR - V SEM 61
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.
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.
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>
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>
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.
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.
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.
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();
}
}
}
}
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();
}
}
}
}
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.
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
S V PUBLICATIONS
72 BCA III YEAR - V SEM
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.
#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.
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
S V PUBLICATIONS
BCA III YEAR - V SEM 75
S V PUBLICATIONS
76 BCA III YEAR - V SEM
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
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
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");
S V PUBLICATIONS
BCA III YEAR - V SEM 83
con.Close();
if (res == 1)
{
Response.Write("<script>alert('Successfully deleted')</script>");
Bind();
}
}
}
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
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.
S V PUBLICATIONS
BCA III YEAR - V SEM 85
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>
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
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:
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.
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>
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
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
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.
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
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>
S V PUBLICATIONS
BCA III YEAR - V SEM 95
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" %>
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
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.
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
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.
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
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.
S V PUBLICATIONS
BCA III YEAR - V SEM 101
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);
}
});
});
S V PUBLICATIONS
102 BCA III YEAR - V SEM
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.
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
Example:
public static int MultipleCatches(string numeratorParam, string
denominatorParam)
{
try
{
var numerator = Convert.ToUInt32(numeratorParam);
var denominator = Convert.ToUInt32(denominatorParam);
S V PUBLICATIONS
104 BCA III YEAR - V SEM
S V PUBLICATIONS
BCA III YEAR - V SEM 105
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 ()
{
}
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
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.
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.
S V PUBLICATIONS
108 BCA III YEAR - V SEM
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&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);
}
}
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.
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>
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>
<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.
<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.
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
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" />
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.
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.
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.
Resources
Contains the resources needed by the application such as images and text.
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.
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.
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
}
}
<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.
S V PUBLICATIONS
BCA III YEAR - V SEM 123
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.
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.
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 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
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.
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
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
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
S V PUBLICATIONS
BCA III YEAR - V SEM 129
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