C# - Unit IV
C# - Unit IV
Web Forms are web pages built on the ASP.NET Technology. It executes on the server and
generates output to the browser. It is compatible to any browser to any language supported by .NET
common language runtime. It is flexible and allows us to create and add custom controls.
We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated Development
Environment) that allows us to drag and drop server controls to the web forms. It also allows us to set
properties, events and methods for the controls. To write business logic, we can choose any .NET
language like: Visual Basic or Visual C#.
Web Forms are made up of two components: the visual portion (the ASPX file), and the code
behind the form, which resides in a separate class file.
The following table contains the server-side controls for the Web Forms.
Example Programs
Button Event
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace sample3
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void bb1(object sender, EventArgs e)
{ t1.Text = "welcome"; } } }
using System;
namespace WebApplication
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void che(object sender, EventArgs e)
{
if (c1.Checked)
{
l1.Text = "Thank you for agreeing to the terms and conditions!";
l1.ForeColor = System.Drawing.Color.Green;
}
else
{
l1.Text = "Please agree to the terms and conditions.";
l1.ForeColor = System.Drawing.Color.Red;
}
} } }
using System;
namespace WebApplication
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void rad(object sender, EventArgs e)
{
if (r1.Checked)
{ l1.Text = "You selected C#."; }
else if (r2.Checked)
{ l1.Text = "You selected Java."; }
else if (r3.Checked)
{ l1.Text = "You selected Python."; }
} } }
ListBox to select multiple items
using System;
using System.Text;
namespace WebApplication
{
public partial class ListBoxEventDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btnShowSelected_Click(object sender, EventArgs e)
{
StringBuilder selectedItems = new StringBuilder();
foreach (var item in lstFruits.Items)
{
if (((System.Web.UI.WebControls.ListItem)item).Selected)
{
selectedItems.Append(((System.Web.UI.WebControls.ListItem)item).Text + ", ");
}
}
if (selectedItems.Length > 0)
{
selectedItems.Length -= 2;
lblSelectedFruits.Text = "You selected: " + selectedItems.ToString();
}
else
{
lblSelectedFruits.Text = "No fruit selected.";
}
} } }
using System;
namespace WebApplication
{
public partial class Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void dd1(object sender, EventArgs e)
{
string s1 = dd.SelectedValue;
if (s1 != "None")
{
im.ImageUrl = s1;
im.Visible = true;
l1.Text = $"You selected: {dd.SelectedItem.Text}";
}
else
{
im.Visible = false;
l1.Text = "Please select an image to display.";
}
} } }
using System;
namespace WebApplication
{
public partial class ImageButtonDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void im1(object sender, System.Web.UI.ImageClickEventArgs e)
{
int x = e.X; int y = e.Y;
l1.Text = "You clicked at: (" + x.ToString() + ", " + y.ToString() + ")"; } } }
namespace WebApplication
{
public partial class HyperLinkDemo : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void ddlWebsites_SelectedIndexChanged(object sender, EventArgs e)
{
string selectedUrl = ddlWebsites.SelectedValue;
if (!string.IsNullOrEmpty(selectedUrl))
{ hyperLinkWebsite.NavigateUrl = selectedUrl; }
else
{ hyperLinkWebsite.NavigateUrl = "#"; }
} } }
Add 2 Numbers
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AddNumbers.aspx.cs"
Inherits="WebApplication.AddNumbers" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Add Two Numbers</title>
</head>
<body>
<form id="form1" runat="server">
<div class="form-container">
<h2>Add Two Numbers</h2>
<asp:Label ID="l1" runat="server" Text="First Number"></asp:Label>
<asp:TextBox ID="t1" runat="server"></asp:TextBox>
<asp:Label ID="l2" runat="server" Text="Second Number"></asp:Label>
<asp:TextBox ID="t2" runat="server"></asp:TextBox>
<asp:Button ID="btnAdd" runat="server" Text="Add Numbers" OnClick="bb1" />
<asp:Label ID="lr" runat="server" CssClass="result"></asp:Label>
</div>
</form>
</body>
</html>
using System;
namespace WebApplication
{
public partial class AddNumbers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void bb1(object sender, EventArgs e)
{
try
{
double f1 = Convert.ToDouble(t1.Text);
double f2 = Convert.ToDouble(t2.Text);
double result = f1 + f2;
lr.Text = "Result: " + result.ToString();
}
catch (Exception)
{ lr.Text = "Please enter valid numbers."; }
} } }
Login Form
using System;
namespace WebApplication
{
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btnLogin_Click(object sender, EventArgs e)
{
string username = "admin";
string password = "password123";
if (t1.Text == username && t2.Text == password)
{ Response.Redirect("Home.aspx"); }
else
{ l1.Text = "Invalid username or password. Please try again."; }
}
}
}
ASP.NET web form control inherits the DataBind method from its parent Control class, which
gives it an inherent capability to bind data to at least one of its properties. This is known as simple data
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
DataBoundControl
HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
ListControl
CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these
controls are:
BulletedList
CheckBoxList
DropDownList
ListBox
RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the
abstract class CompositeDataBoundControl. These controls are:
DetailsView
FormView
GridView
RecordList
State Management is a process by which state and page information is maintained over multiple
requests for same or different pages. As HTTP is a stateless protocol, server does not store any
information once the response is sent back to client based on his request. When user submits request
again, the server treats it as a new user. This is called stateless model. This model was workable when
static web sites were developed and hosted in the past. Now, with interactive web sites or dynamic web
site, there is a need to preserve some information to identify user, interact with user again and again
within same session and same application. This concept is known as Stateful protocol. The information
can be related to user, data objects, web pages or server objects.
4.6.Tracing in ASP.NET
ASP.NET tracing enables you to view diagnostic information about a single request for an
ASP.NET page. ASP.NET tracing enables you to follow a page's execution path, display diagnostic
information at run time, and debug your application. ASP.NET tracing can be integrated with system-
level tracing to provide multiple levels of tracing output in distributed and multi-tier applications.
There are two ways:
Page Level Tracing
Application Level Tracing
Page Level Tracing
We can control whether tracing is enabled or disabled for individual pages. If tracing is enabled,
when the page is requested, ASP.NET appends to the page a series of tables containing execution details
about the page request. Tracing is disabled by default in an ASP.NET application.
Caching is a technique of storing frequently used data/information in memory, so that, when the
same data/information is needed next time, it could be directly retrieved from the memory instead of
being generated by the application.
Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are
dynamically generated here. It is especially important for data related transactions, as these are expensive
in terms of response time.
Caching places frequently used data in quickly accessed media such as the random access
memory of the computer. The ASP.NET runtime includes a key-value map of CLR objects called cache.
This resides with the application and is available via the HttpContext and System.Web.UI.Page.
Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET
allows four types of authentications:
o Windows Authentication
o Forms Authentication
o Passport Authentication
o Custom Authentication
Authorization : It is the process of defining and allotting specific roles to specific users.
Confidentiality : It involves encrypting the channel between the client browser and the web
server.
Integrity : It involves maintaining the integrity of data. For example, implementing digital
signature.
4.10.ASP.NET – Deployment
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.
To understand the concept, let us create a simple user control, which will work as footer for the web
pages. To create and use the user control, take the following steps:
To add the user control to your web page, you must add the Register directive and an instance of the user
control to the page. The following code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="customcontroldemo._Default" %>
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>
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.
To use the control on a page, add the Register directive just below the @Page directive:
<%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="ccs" %>
Further, you can use the control, similar to any other controls.
<form id="form1" runat="server">
<div>
<ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" />
</div>
</form>
namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]
public class ServerControl1 : WebControl
{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string Text
{
get
{
String s = (String)ViewState["Text"];
return ((s == null) ? "[" + this.ID + "]" : s);
}
set
{
ViewState["Text"] = value;
}
}
protected override void RenderContents(HtmlTextWriter output)
{
output.Write(Text); } } }
4.12.ASP.NET Windows Communication Foundation (WCF)
WCF stands for Windows Communication Foundation. The elementary feature of WCF is
interoperability. It is one of the latest technologies of Microsoft that is used to build service-oriented
applications. Based on the concept of message-based communication, in which an HTTP request is
represented uniformly, WCF makes it possible to have a unified API irrespective of diverse transport
mechanisms.