You are on page 1of 22

Unit – 5 Web App Development and Data Accessusing ADO.

NET

Multitier Application Architecture

The multitier architecture, also known as the n-tier architecture, is a design pattern
used in ASP.NET applications to separate different layers of functionality into distinct
tiers or layers. Each tier is responsible for specific tasks and has its own set of
responsibilities. Here's a brief explanation of the multitier architecture in ASP.NET:
Presentation Tier (UI Layer):
The presentation tier, also known as the user interface (UI) layer, is responsible for
rendering the user interface and handling user interactions. It includes components
like web pages, forms, controls, and views. The primary goal of this layer is to present
data and interact with the users.
Business Logic Tier (Business Layer):
The business logic tier, also known as the business layer, contains the core business
logic and rules of the application. It encapsulates the logic for processing data,
implementing business rules, and performing operations on the data. This layer is
responsible for handling business processes, calculations, validations, and other
business-related operations.
Data Access Tier (Data Layer):
The data access tier, also known as the data layer, is responsible for managing data
storage and retrieval. It interacts with the underlying data storage systems, such as
databases, files, or external services. This layer handles tasks like connecting to the
database, executing queries, and retrieving or updating data. It abstracts the
underlying data storage details from the business layer.
Integration Tier:
In some cases, an additional integration tier may exist between the business logic tier
and the data access tier. This tier handles interactions with external systems, such as
web services, APIs, or third-party components. It is responsible for integrating
external services into the application and managing the communication between the
application and these services.

Benefits of Multitier Architecture:


Separation of concerns: Each tier has its own responsibilities and can be developed,
tested, and maintained independently, promoting modular and reusable code.
Scalability: The multitier architecture allows for scaling individual tiers based on
demand. For example, scaling the data access tier separately from the business logic
tier.
Security: By separating concerns, it becomes easier to enforce security measures at
different tiers, such as authentication and authorization.

Maintainability: Changes or updates in one tier do not affect the others, making the
application easier to maintain and modify.
Building a basic ASP.net WebTime Application:
To create a basic web time application using ASP.NET, you can follow these steps:

Step 1: Create a new ASP.NET Web Application project in Visual Studio.


Open Visual Studio and select "Create a new project."

Choose the ASP.NET Web Application template and provide a suitable name and
location for your project.

Select the desired framework version (e.g., ASP.NET Web Forms or ASP.NET MVC).

Click "Create" to create the project.

Step 2: Design the User Interface (UI).


Open the default page (e.g., Default.aspx or Index.cshtml) in the project.
Design the UI by adding relevant HTML elements and server controls to display the
time.
For ASP.NET Web Forms:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="YourNamespace.Default" %>

<!DOCTYPE html>
<html>

<head>

<title>Time Application</title>

</head>

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

<div>

<h1>Current Time:</h1>

<asp:Label ID="lblTime" runat="server"></asp:Label>


</div>
</form>

</body>

</html>

Step 3: Add code to display the current time.


In the code-behind file (e.g., Default.aspx.cs for Web Forms or Controller for MVC),
add the necessary logic to display the current time.

For ASP.NET Web Forms:


csharp
using System;

namespace YourNamespace

{
public partial class Default : System.Web.UI.Page

protected void Page_Load(object sender, EventArgs e)

{
lblTime.Text = DateTime.Now.ToString("HH:mm:ss");

For ASP.NET MVC, no additional code is required as the current time is directly
displayed in the view.

Step 4: Build and run the application.


Build the project to ensure there are no errors.

Run the application by pressing F5 or using the "Start" button in Visual Studio.

The web application will display the current time when you access the page. The
displayed time will update automatically with each page refresh.
This is a basic example of creating a web time application using ASP.NET. You can
further enhance the application by adding additional features like time zones,
dynamic updates, or user interactions based on your requirements.
Understanding Master pages:
Master pages in ASP.NET provide a consistent layout and structure for web pages in
a web application. They allow you to define a common template or design that can be
shared across multiple content pages. Here's an explanation of the concept of Master
pages in ASP.NET:

Creating a Master Page:


A master page is created as a separate file with the .master extension. It contains the
common elements and layout structure that will be shared across multiple pages. The
master page typically includes elements like headers, footers, navigation menus, and
other common controls.

Defining Content Placeholders:


Within the master page, you can define one or more content placeholders using the
<asp:ContentPlaceHolder> tag. These placeholders act as "slots" where the content
specific to each page will be inserted. The content placeholders define the areas of the
master page that can be customized by individual content pages.

Example Markup (Master Page):


<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs"
Inherits="YourNamespace.SiteMaster" %>

<!DOCTYPE html>
<html>

<head runat="server">

<title>Master Page</title>

<asp:ContentPlaceHolder ID="HeadContent"
runat="server"></asp:ContentPlaceHolder>

</head>
<body>

<header>

<!-- Common header content -->


</header>

<nav>

<!-- Common navigation menu -->


</nav>

<main>

<asp:ContentPlaceHolder ID="MainContent"
runat="server"></asp:ContentPlaceHolder>

</main>

<footer>
<!-- Common footer content -->

</footer>

</body>

</html>

Creating Content Pages:


Content pages are the individual pages that use the master page as a template. They
inherit the layout and structure defined in the master page while providing their
specific content within the content placeholders.

Example Markup (Content Page):


<%@ Page Title="Home" Language="C#" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="YourNamespace.DefaultPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">

<!-- Page-specific CSS or scripts -->

</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<!-- Page-specific content -->

<h1>Welcome to My Website</h1>
<p>This is the home page content.</p>

</asp:Content>

In this example, we have a master page named "Site.master" that defines the common
structure of the web pages. It includes placeholders for the <head> section
(HeadContent) and the main content area (MainContent).

A content page named "Default.aspx" is created, which references the master page
using the MasterPageFile attribute. It provides page-specific content within the
content placeholders defined in the master page.
When a content page is requested, ASP.NET merges the content from the content page
with the layout defined in the master page. The resulting HTML is sent to the browser,
providing a consistent design across multiple pages.
Master pages in ASP.NET are beneficial for maintaining a consistent look and feel
across a website, allowing for centralized management of common elements and
layout. They help in reducing code duplication and making updates to the overall site
design more efficient.

Standard Web Controls


Control Description
Label Displays static text on a web page.
TextBox Allows users to enter and edit text.
Button Triggers an action when clicked by the user.
LinkButton Similar to a Button control, but appears as a hyperlink.
ImageButton Displays an image and triggers an action when clicked.
CheckBox Represents a checkbox that can be checked or unchecked by the user.
RadioButton Represents a radio button, allowing users to select a single option from a group of option
DropDownList Displays a list of options in a drop-down format, allowing users to select a single item.
ListBox Similar to a DropDownList, but allows users to select multiple items.
CheckBoxList Displays a group of checkboxes, allowing users to select multiple items.
RadioButtonList Displays a group of radio buttons, allowing users to select a single option from a group.
Image Displays an image on a web page.
HyperLink Represents a hyperlink that navigates to a specified URL.
Calendar Allows users to select a date from a calendar interface.
Validation Controls A set of controls (e.g., RequiredFieldValidator, RangeValidator) used for data validation
FileUpload Allows users to upload files from their local machine to the server.
GridView Displays data in a tabular format with features like sorting, paging, and editing.
DataList Allows customizing the appearance of each item in a list.
Repeater Provides maximum flexibility for creating a tabular layout by manually binding data.
ListView Displays data with customizable templates and supports sorting, paging, and editing.
Login Controls A set of controls (e.g., Login, CreateUserWizard) for implementing user authentication a
Menu Represents a menu control for creating hierarchical navigation menus.
TreeView Displays hierarchical data in a tree-like structure, commonly used for site navigation.
AdRotator Rotates advertisements on a web page.
MultiView Allows displaying multiple views and switching between them based on user interaction
Wizard Breaks a process into multiple steps, guiding users through each step.

Designing a Form
Designing a form in ASP.NET involves creating the necessary HTML structure and
using ASP.NET server controls to handle user input and perform server-side
processing. Here's an explanation along with code examples for designing a form in
ASP.NET:
<form id="myForm" runat="server">

<div>

<asp:Label ID="lblName" runat="server"


AssociatedControlID="txtName">Name:</asp:Label>

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>

</div>
<div>

<asp:Label ID="lblEmail" runat="server"


AssociatedControlID="txtEmail">Email:</asp:Label>

<asp:TextBox ID="txtEmail" runat="server"


TextMode="Email"></asp:TextBox>

</div>

<div>

<asp:Label ID="lblMessage" runat="server"


AssociatedControlID="txtMessage">Message:</asp:Label>
<asp:TextBox ID="txtMessage" runat="server"
TextMode="MultiLine"></asp:TextBox>
</div>

<div>

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


OnClick="btnSubmit_Click" />

</div>

</form>
Server side processing:
protected void btnSubmit_Click(object sender, EventArgs e)

string name = txtName.Text;

string email = txtEmail.Text;

string message = txtMessage.Text;


// Process the form data, such as saving to a database or sending an email

// Redirect to a thank you page or display a success message

Response.Redirect("ThankYouPage.aspx");

}
The above example is used to create a form with 3 controls Name email and message
which will be further stored in variables name email and message on server side for
further processing.

ASP.net Validation Controls:


ASP.NET provides a range of validation controls that help developers ensure the
validity and integrity of user input in web forms.
These controls assist in validating user input against specific criteria and displaying
error messages when validation fails. Here are the various validation controls
available in ASP.NET:

Required Field Validator:

 Ensures that a specific field has a value before allowing form submission.
 Displays an error message if the field is left empty.
Control Name: RequiredFieldValidator

Purpose: Ensures that a field is not left empty.


Important Properties:
Control To Validate: Specifies the ID of the input control to validate.

ErrorMessage: Specifies the error message to display when validation fails.

Display: Determines how the error message is displayed (e.g., as text, as a message
box, or as a validation summary).
Range Validator:

 Checks if the input value falls within a specified range of values.


 Supports both numeric and date range validations.
 Displays an error message if the input value is outside the specified range.
Control Name: RangeValidator

Purpose: Validates that the input falls within a specified range.


Important Properties:
ControlToValidate: Specifies the ID of the input control to validate.

MinimumValue and MaximumValue: Define the range of acceptable values.

Type: Specifies the data type of the input (e.g., Integer, Double, Date).

ErrorMessage: Specifies the error message to display when validation fails.

Regular Expression Validator:

 Validates input against a specified regular expression pattern.


 Useful for validating complex patterns such as email addresses, phone numbers,
or ZIP codes.
 Displays an error message if the input does not match the specified pattern.

Control Name: RegularExpressionValidator


Purpose: Validates input based on a regular expression pattern.
Important Properties:
ControlToValidate: Specifies the ID of the input control to validate.

ValidationExpression: Specifies the regular expression pattern to match against.


ErrorMessage: Specifies the error message to display when validation fails.

CompareValidator:

 Compares the input value with another input control or a constant value.
 Allows for comparing numeric, date, or string values.
 Displays an error message if the comparison fails.
Control Name: CompareValidator

Purpose: Compares the values of two input controls.


Important Properties:
ControlToValidate: Specifies the ID of the input control to validate.

ControlToCompare: Specifies the ID of the control to compare against.


Type: Specifies the data type of the input (e.g., String, Integer, Date).

Operator: Defines the comparison operator (e.g., Equal, NotEqual, GreaterThan).

ErrorMessage: Specifies the error message to display when validation fails.

Custom Validator:

 Enables custom validation logic using server-side or client-side code.


 Developers can define their own validation routine and error message.
 Displays an error message when the custom validation logic fails.
Control Name: CustomValidator

Purpose: Allows custom validation logic using server-side or client-side code.


Important Properties:
ControlToValidate: Specifies the ID of the input control to validate.

ClientValidationFunction: Specifies the JavaScript function for client-side validation.

ServerValidate: Specifies the server-side validation event handler function.

ErrorMessage: Specifies the error message to display when validation fails.

Validation Summary:

 Displays a summary of all validation errors on a form.


 Consolidates error messages from multiple validation controls.
 Provides a centralized location to view and correct all validation errors.

Control Name: ValidationSummary


Purpose: Displays a summary of all validation errors on the form.
Important Properties:
ShowMessageBox: Determines whether to display the validation summary as a
JavaScript alert.

ShowSummary: Determines whether to display the validation summary as text.


HeaderText: Specifies the text to display as the header of the validation summary.

DisplayMode: Defines how the summary is displayed (e.g., BulletList, List,


SingleParagraph).

These validation controls can be added to ASP.NET web forms by dragging and
dropping them from the toolbox or programmatically adding them in the code-behind
file. They provide a convenient way to enforce data integrity, improve user
experience, and minimize errors in web form submissions.

Grid View Control:


The GridView control in ASP.NET is used to display tabular data in a grid format. It
provides features for sorting, paging, editing, and deleting data, making it a versatile
control for working with data in a tabular form. Here's a detailed explanation of the
GridView control with a code example:

1. Grid View is a powerful control in ASP.NET used to display data in a tabular


format on a web page.
2. It allows you to bind data from various data sources, such as databases or
collections, and display it in a structured grid.
3. The GridView control automatically generates columns based on the data source
schema or allows you to define custom columns.
4. It provides built-in features like sorting, paging, editing, and deleting data, making
it convenient for data manipulation.
5. You can customize the appearance of the GridView, including the layout, styling,
and formatting of cells and headers.
6. It supports different types of data controls, such as checkboxes, buttons, or
textboxes, within each grid cell for data interaction.

ASPX Markup code:


<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">

<Columns>

<asp:BoundField DataField="Id" HeaderText="ID" ReadOnly="true" />


<asp:BoundField DataField="Name" HeaderText="Name" />

<asp:BoundField DataField="Age" HeaderText="Age" />


<asp:CommandField ShowEditButton="true" ShowDeleteButton="true" />

</Columns>

</asp:GridView>

Behind the file Code:


protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindGridView();
}
}

private void BindGridView()


{
// Simulating data from a data source
DataTable dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));

dt.Rows.Add(1, "John", 25);


dt.Rows.Add(2, "Jane", 30);
dt.Rows.Add(3, "Mark", 28);

GridView1.DataSource = dt;
GridView1.DataBind();
}

DropDownList control in ASP.net


The DropDownList control in ASP.NET is used to display a list of items in a drop-
down format on a web page. It allows users to select a single item from the list. Here's
an overview of the DropDownList control in ASP.NET:

To create a DropDownList control, you can add the DropDownList control to the web
form either by dragging and dropping it from the toolbox onto the design surface or
by manually adding the DropDownList control markup in the ASPX file.

Example:

<asp:DropDownList ID="DropDownList1" runat="server">


<asp:ListItem Text="Option 1" Value="1"></asp:ListItem>

<asp:ListItem Text="Option 2" Value="2"></asp:ListItem>

<asp:ListItem Text="Option 3" Value="3"></asp:ListItem>


<!-- Add more list items as needed -->

</asp:DropDownList>

Binding Data to DropDownList


DataTable dt = GetDataFromDataSource();

// Bind the data to the DropDownList


DropDownList1.DataSource = dt;

DropDownList1.DataTextField = "Name";

DropDownList1.DataValueField = "Id";

DropDownList1.DataBind();

To retrieve value from a DropDownList


string selectedItemText = DropDownList1.SelectedItem.Text;

Session Tracking:
Session tracking in ASP.NET refers to the mechanism used to maintain user-specific
data across multiple requests from the same user. It enables the server to associate
data with a particular user and maintain state information throughout their
interaction with the web application. The session tracking process involves the
following steps:

Session Creation: When a user accesses a web application, ASP.NET assigns a unique
session identifier to the user and creates a session object on the server. The session
identifier is typically stored in a cookie or appended to the URL.
Data Storage: ASP.NET provides a Session object that can be used to store and retrieve
data specific to each user session. The Session object is accessible throughout the
application and can store various types of data, such as user preferences, shopping
cart items, or authentication details.

Retrieving Session Data: On subsequent requests from the same user, the server
retrieves the session identifier from the cookie or URL and uses it to locate the
corresponding session object. The data stored in the session object can then be
accessed and used in the current request.

Session Management: ASP.NET offers several options for managing sessions. By


default, session state is stored in memory on the web server. However, developers can
configure session state to be stored in other locations such as a SQL Server database
or an out-of-process state server for scalability and fault tolerance.

Expiration and Timeout: Sessions have an expiration time, after which they are
considered inactive and can be automatically removed by the server. The session
timeout duration can be configured in the application's configuration file. When a
session expires, the associated session data is no longer available.

Session Abandonment: Developers can explicitly abandon a session, which removes


the session data and releases any associated resources. This is useful, for example,
when a user logs out of the application or when a certain event occurs that requires
the session to be cleared.

Applications of Sessions:
 User Authentication and Authorization
 Shopping Carts and E-commerce
 Personalization and User Preferences
 Session Tracking and Analytics
 Multi-step Processes and Form Submissions
 Caching and Performance Optimization
 Cross-Page Communication

Advantages of Session Tracking:


Personalization: Session tracking enables the customization of content and
functionality based on individual user preferences. User-specific data stored in the
session can be used to tailor the user experience.

State Management: Web applications often require the preservation of state


information between requests. Session tracking allows developers to maintain state
information on the server, avoiding the need to send and receive the entire state with
each request.

Security: Session identifiers stored in cookies can be encrypted and tamper-proof,


making them more secure than passing sensitive information in query parameters or
form fields.

Scalability: By allowing session state to be stored outside of the web server, ASP.NET
provides scalability options for applications with high user loads. State can be stored
in a centralized and distributed manner to handle increased traffic and provide fault
tolerance.

Limitation of Session Tracking


Server Resources: Storing session state on the server consumes memory and
resources. Large or frequently accessed session data can impact server performance
and scalability.

Session Hijacking: If session identifiers are not properly protected, an attacker may
be able to hijack a user's session and impersonate them. Proper security measures,
such as using secure cookies and regularly regenerating session identifiers, should be
implemented to mitigate this risk.

Code Examples for Sessions:


// Storing data in session
Session["Username"] = "John Doe";

Example: Session["IsAdmin"] = true;

// Retrieving data from session


string username = (string)Session["Username"];
Example: bool isAdmin = (bool)Session["IsAdmin"];

// Checking if session variable exists


if (Session["Username"] != null)
{
// Session variable exists
}
else
{
// Session variable does not exist
}

// Removing data from session


Session.Remove("Username");

// Clearing all session data


Session.Clear();

//Setting Session Timeout:


<!-- Web.config file -->

<system.web>

<sessionState timeout="30"></sessionState>

</system.web>
Ajax (Asynchronous JavaScript and XML) is a technique used in web development
to create interactive and responsive web applications. It allows for asynchronous
communication between the client-side and server-side, enabling the exchange of data
without requiring a full page reload.

In ASP.NET, Ajax is implemented using the Microsoft Ajax Library and the ASP.NET
Ajax Control Toolkit. It provides developers with a set of tools and techniques to
enhance the user experience and improve the performance of web applications.

Here are some key points to understand about Ajax in ASP.NET:

Asynchronous Communication: Ajax enables asynchronous communication between


the client-side and server-side, allowing data to be sent and received without
refreshing the entire web page. This leads to a more seamless and interactive user
experience.

Partial Page Updates: With Ajax, specific portions of a web page can be updated
dynamically without reloading the entire page. This helps in creating responsive and
interactive web applications, as only the necessary data is retrieved and displayed.

XMLHttpRequest Object: Ajax in ASP.NET utilizes the XMLHttpRequest object,


which enables the client-side code to make requests to the server and handle the
responses asynchronously. This object provides methods for sending requests,
handling responses, and updating the web page accordingly.

Callbacks and Event Handlers: Ajax in ASP.NET uses callbacks and event handlers
to handle server responses. Callback functions are executed when the server sends a
response, allowing for dynamic updates of the web page based on the received data.

Server-Side Support: ASP.NET provides server-side support for Ajax through built-
in controls and libraries. The Microsoft Ajax Library offers a collection of client-side
JavaScript functions and classes that simplify the implementation of Ajax
functionality. The ASP.NET Ajax Control Toolkit provides a set of server controls that
encapsulate Ajax functionality, making it easier to incorporate Ajax features into web
applications.
Enhanced User Experience: Ajax in ASP.NET helps improve the user experience by
reducing page reloads, providing real-time updates, and enabling interactive features
like auto-complete, drag-and-drop, and dynamic content loading.
Cross-Browser Compatibility: Ajax techniques in ASP.NET are designed to work
across different web browsers, ensuring a consistent experience for users regardless
of the browser they are using.
Performance Optimization: Ajax can help optimize the performance of web
applications by minimizing the amount of data transferred between the client and
server. Only the necessary data is exchanged, reducing network latency and
improving overall application responsiveness.
AJAX Server Controls:
In ASP.NET, AJAX server controls are a set of controls that provide built-in support
for AJAX (Asynchronous JavaScript and XML) functionality. These controls enable
developers to create interactive and responsive web applications without writing
extensive JavaScript code. Here are a few examples of AJAX server controls in
ASP.NET:

ScriptManager Control:
The ScriptManager control is required to enable AJAX functionality in an ASP.NET
web page. It manages the client-side script resources and provides the necessary
JavaScript libraries for AJAX controls to work correctly.
Example:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

UpdatePanel Control:
The UpdatePanel control is used to create partial page updates without refreshing
the entire page. It allows specific regions of the page to be updated asynchronously.
Any controls placed inside the UpdatePanel can trigger an asynchronous postback
and update the content within the panel without refreshing the entire page.

Example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<!-- Content to be updated -->


</ContentTemplate>

</asp:UpdatePanel>

Timer Control:
The Timer control is used to trigger asynchronous postbacks at regular intervals. It
allows you to update specific parts of the page periodically without user interaction.
Example:

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="5000"
OnTick="Timer1_Tick"></asp:Timer>

<!-- Content to be updated -->

</ContentTemplate>

</asp:UpdatePanel>

UpdateProgress Control:
The UpdateProgress control displays a loading indicator or progress bar during an
asynchronous postback. It provides a visual indication to the user that an update is
in progress.

Example:
<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<!-- Content to be updated -->

</ContentTemplate>
<Triggers>

<asp:AsyncPostBackTrigger ControlID="Button1" EventName="Click" />

</Triggers>

</asp:UpdatePanel>

<asp:UpdateProgress ID="UpdateProgress1" runat="server"


AssociatedUpdatePanelID="UpdatePanel1">
<ProgressTemplate>

<!-- Loading indicator or progress bar -->

</ProgressTemplate>

</asp:UpdateProgress>
These are just a few examples of AJAX server controls in ASP.NET. AJAX server
controls simplify the implementation of AJAX functionality by providing a server-
side approach to asynchronous updates and interactions in web applications. They
help enhance the user experience by making the application more responsive and
interactive.

You might also like