0% found this document useful (0 votes)
18 views25 pages

C# - Unit IV

Uploaded by

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

C# - Unit IV

Uploaded by

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

UNIT – IV WINDOWS AND WEB BASED APPLICATIONS

4.3 ASP.NET Web Forms

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.

4.4. Server Controls

The following table contains the server-side controls for the Web Forms.

Control Name Applicable Events Description


It is used to display text on the HTML
Label None
page.
It is used to create a text input in the
TextBox TextChanged
form.
Button Click, Command It is used to create a button.
It is used to create a button that looks
LinkButton Click, Command
similar to the hyperlink.
It is used to create an imagesButton.
ImageButton Click
Here, an image works as a Button.
It is used to create a hyperlink control
Hyperlink None
that responds to a click event.
It is used to create a dropdown list
DropDownList SelectedIndexChanged
control.
It is used to create a ListBox control
ListBox SelectedIndexCnhaged
like the HTML control.
CancelCommand, EditCommand,
It used to create a frid that is used to
DeleteCommand, ItemCommand,
show data. We can also perform
DataGrid SelectedIndexChanged, PageIndexChanged,
paging, sorting, and formatting very
SortCommand, UpdateCommand, ItemCreated,
easily with this control.
ItemDataBound
CancelCommand, EditCommand,
DeleteCommand, ItemCommand, It is used to create datalist that is non-
DataList
SelectedIndexChanged, UpdateCommand, tabular and used to show data.
ItemCreated, ItemDataBound
It allows us to create a non-tabular type
of format for data. You can bind the
Repeater ItemCommand, ItemCreated, ItemDataBound data to template items, which are like
bits of HTML put together in a specific
repeating format.
CheckBox CheckChanged It is used to create checkbox.
It is used to create a group of check
CheckBoxList SelectedIndexChanged
boxes that all work together.
RadioButton CheckChanged It is used to create radio button.
It is used to create a group of radio
RadioButtonList SelectedIndexChanged
button controls that all work together.
It is used to show image within the
Image None
page.
It is used to create a panel that works
Panel None
as a container.
It is used to set placeholder for the
PlaceHolder None
control.
It is used to create a calendar. We can
SelectionChanged, VisibleMonthChanged,
Calendar set the default date, move forward and
DayRender
backward etc.
Table None It is used to create table.
It is like a label in that it displays a
literal, but allows us to create new
Literal None
literals at runtime and place them into
this control.

Example Programs
Button Event

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"


Inherits="sample3.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h3>welcome</h3>
<asp:Button ID="b1" runat="server" Text="submit" OnClick="bb1" />
<p>
<asp:TextBox ID="t1" runat="server"></asp:TextBox>
</div>
</form>
</body>
</html>

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

CheckBox control with CheckedChanged event

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="WebApplication.Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>CheckBox Event Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="c1" runat="server" Text="I agree to the terms and conditions"
OnCheckedChanged="che" AutoPostBack="true" />
<asp:Label ID="l1" runat="server" Text="Please agree to the terms and conditions."
ForeColor="Red"></asp:Label>
</div>
</form>
</body>
</html>

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

RadioButton controls with CheckedChanged event

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="WebApplication.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>RadioButton Event Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Select Your Favorite Programming Language:</h2>
<asp:RadioButton ID="r1" GroupName="Languages" runat="server" Text="C#"
OnCheckedChanged="rad" AutoPostBack="true" />
<asp:RadioButton ID="r2" GroupName="Languages" runat="server" Text="Java"
OnCheckedChanged="rad" AutoPostBack="true" />
<asp:RadioButton ID="r3" GroupName="Languages" runat="server" Text="Python"
OnCheckedChanged="rad" AutoPostBack="true" />
<br /><br />
<asp:Label ID="l1" runat="server" Text="Please select a language."
ForeColor="Blue"></asp:Label>
</div>
</form>
</body>
</html>

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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListBoxEventDemo.aspx.cs"


Inherits="WebApplication.ListBoxEventDemo" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ListBox Event Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div class="form-container">
<h2>Select Fruits</h2>
<asp:ListBox ID="lstFruits" runat="server" SelectionMode="Multiple" Rows="5">
<asp:ListItem Text="Apple" Value="Apple"></asp:ListItem>
<asp:ListItem Text="Banana" Value="Banana"></asp:ListItem>
<asp:ListItem Text="Cherry" Value="Cherry"></asp:ListItem>
<asp:ListItem Text="Mango" Value="Mango"></asp:ListItem>
<asp:ListItem Text="Orange" Value="Orange"></asp:ListItem>
</asp:ListBox>
<asp:Button ID="btnShowSelected" runat="server" Text="Show Selected Fruits"
OnClick="btnShowSelected_Click" />
<asp:Label ID="lblSelectedFruits" runat="server" CssClass="message"></asp:Label>
</div>
</form>
</body>
</html>

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.";
}
} } }

Dropdown list to select an image

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="WebApplication.Default" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Image Display Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<h2>Select an Image to Display:</h2>
<asp:DropDownList ID="dd" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="dd1">
<asp:ListItem Value="None" Text="Select an Image" />
<asp:ListItem Value="apple.jpg" Text="Apple" />
<asp:ListItem Value="orange.jpg" Text="Orange" />
<asp:ListItem Value="grapes.jpg" Text="Grapes" />
</asp:DropDownList>
<br /><br />
<asp:Image ID="im" runat="server" Width="400px" Height="300px" Visible="false" />
<br /><br />
<asp:Label ID="l1" runat="server" ForeColor="Blue"></asp:Label>
</div>
</form>
</body>
</html>

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.";
}
} } }

ImageButton to trigger an event on click

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ImageButtonDemo.aspx.cs"


Inherits="WebApplication.ImageButtonDemo" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>ImageButton Event Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div class="form-container">
<h2>Click the Image</h2>
<asp:ImageButton ID="i1" runat="server" ImageUrl="rose.jpg" OnClick="im1" Width="300px"
Height="200px" />
<asp:Label ID="l1" runat="server" CssClass="message"></asp:Label>
</div>
</form>
</body>
</html>

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() + ")"; } } }

HyperLink control to navigate to the selected website

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HyperLinkDemo.aspx.cs"


Inherits="WebApplication.HyperLinkDemo" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>HyperLink Event Demo</title>
</head>
<body>
<form id="form1" runat="server">
<div class="form-container">
<h2>Select a Website to Visit</h2>
<asp:DropDownList ID="ddlWebsites" runat="server" AutoPostBack="true"
OnSelectedIndexChanged="ddlWebsites_SelectedIndexChanged">
<asp:ListItem Text="--Select a Website--" Value=""></asp:ListItem>
<asp:ListItem Text="Google" Value="https://www.google.com"></asp:ListItem>
<asp:ListItem Text="Bing" Value="https://www.bing.com"></asp:ListItem>
<asp:ListItem Text="Yahoo" Value="https://www.yahoo.com"></asp:ListItem>
<asp:ListItem Text="DuckDuckGo" Value="https://www.duckduckgo.com"></asp:ListItem>
</asp:DropDownList>
<asp:HyperLink ID="hyperLinkWebsite" runat="server" Text="Visit Website" NavigateUrl="#"
Target="_blank"></asp:HyperLink>
</div>
</form>
</body>
</html>

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

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Login.aspx.cs"


Inherits="WebApplication.Login" %>
<!DOCTYPE html>
<html>
<head runat="server">
<title>Login Page</title>
</head>
<body>
<form id="form1" runat="server">
<div class="login-form">
<h2>Login</h2>
<asp:Label ID="l1" runat="server" ForeColor="Red" CssClass="error"></asp:Label>
<asp:Label runat="server" Text="Username"></asp:Label>
<asp:TextBox ID="t1" runat="server"></asp:TextBox>
<asp:Label runat="server" Text="Password"></asp:Label>
<asp:TextBox ID="t2" runat="server" TextMode="Password"></asp:TextBox>
<asp:Button ID="btnLogin" runat="server" Text="Login" OnClick="btnLogin_Click" />
</div>
</form>
</body>
</html>

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."; }
}
}
}

4.5. ASP.NET - Data Binding

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

binding or inline data binding.


Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into their structure through a
DataSource control. These controls derive from the BaseDataBoundControl class. This is called

declarative data binding.


The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.

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

Simple Data Binding


Simple data binding involves the read-only selection lists. These controls can bind to an array list
or fields from a database. Selection lists takes two values from the database or the data source; one value
is displayed by the list and the other is considered as the value corresponding to the display.
Choosing a data source for the bulleted list control involves:

 Selecting the data source control


 Selecting a field to display, which is called the data field
 Selecting a field for the value

Declarative Data Binding


We have already used declarative data binding in the previous tutorial using GridView control.
The other composite data bound controls capable of displaying and manipulating data in a tabular manner
are the DetailsView, FormView, and RecordList control.

 A dataset that stores the data retrieved from the database.


 The data provider, which retrieves data from the database by using a command over a connection.
 The data adapter that issues the select statement stored in the command object; it is also capable
of update the data in a database by issuing Insert, Delete, and Update statements.

Example
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
namespace databinding
{
public class booklist
{
protected String bookname;
protected String authorname;
public booklist(String bname, String aname)
{
this.bookname = bname;
this.authorname = aname;
}
public String Book
{
get
{ return this.bookname; }
set
{ this.bookname = value; }
}
public String Author
{
get
{ return this.authorname; }
set
{ this.authorname = value; }
} } }

4.5 ASP.NET Sate Management?

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.

Server Side State Management Options


 Application State: Application state allows saving of data at application level which is
accessible throughout the life of an application. The life of application starts when IIS is started
and ends when IIS is stopped.
 Session State: The session state persists till the user is active or session time expires. When a
user submits request, a session is started. The session gets over either when time expires or user
explicitly abandons the sessions. The required information can be saved in session for later user
by same user within the same application.
 Profile Properties: This option also allows saving of user specific data. It is similar to Session
state except the data stored in Profile state never expires on use this property, the
SQLProfileProvider class needs to be configured. It allows storing of data in SQL database. Since
data is stored in database and not in application memory, therefore there is no risk of losing data
even if IIS is restarted again and again.
 Cache: Caching is a technique by which frequently used data and web pages are stored in cache
so that repeated cost of retrieval can be avoided. Storing frequently used data in cache ensures
high availability, improved performance and scalability. Cache is object of System.Web.Caching
Cache class. The main disadvantage of using Cache is that it is unreliable. The previously stored
data stored in cache is deleted automatically to meet memory requirement of current process.

Client Side State Management Options


 View State: View state provides facility to preserve page and values of controls at the client side.
The information is stored after post back. Post back is a request from user for the page which is
not for the first time. If value of IsPostBack property is true, it means page is not requested for
the first time. The view state can be at page level, application level, machine level and control
level. In page level state management, as long as the user is on current page, the information is
retained. Whenever user submits form, the current state of page and controls are hashed into a
string and saved in hidden field of the page. More than one hidden field can be used if data
exceed limit set by MaxPageStateFieldLength property. When page is sent to server, the page
parses the view state string and restores the information. This is default mechanism. The view
state can be disabled at any stage. The property EnableViewState="false" is used in code when
it is required to disable view state
 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 value of other controls. The hidden file can be created in source
file as given below.<input type="hidden" id="username" name="username" value=""

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.

Application Level Tracing


Instead of enabling tracing for individual pages, you can enable it for your entire application. In
that case, every page in your application displays trace information. Application tracing is useful when
you are developing an application because you can easily enable it and disable it without editing
individual pages. When your application is complete, you can turn off tracing for all pages at once.

4.7. ASP.NET - Data Caching

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.

The data will not be available in the following cases:


 If its lifetime expires,
 If the application releases its memory,
 If caching does not take place for some reason.

ASP.NET provides the following different types of caching:


 Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of
pages sent to the client. When the next client requests for this page, instead of regenerating the
page, a cached copy of the page is sent, thus saving time.
 Data Caching : Data caching means caching data from a data source. As long as the cache is not
expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh
data is obtained by the data source and the cache is refilled.
 Object Caching : Object caching is caching the objects on a page, such as data-bound controls.
The cached data is stored in server memory.
 Class Caching : Web pages or web services are compiled into a page class in the assembly, when
run for the first time. Then the assembly is cached in the server. Next time when a request is
made for the page or service, the cached assembly is referred to. When the source code is
changed, the CLR recompiles the assembly.
 Configuration Caching : Application wide configuration information is stored in a configuration
file. Configuration caching stores the configuration information in the server memory.

4.8. ASP.NET - Error Handling

Error handling in ASP.NET has three aspects:


 Tracing - tracing the program execution at page level or application level.
 Error handling - handling standard errors or custom errors at page level or application level.
 Debugging - stepping through the program, setting break points to analyze the code
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="errorhandling._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Tracing, debugging and error handling
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblheading" runat="server" Text="Tracing, Debuggin and Error Handling">
</asp:Label>
<br /> <br />
<asp:DropDownList ID="ddlquotes" runat="server" AutoPostBack="True"
onselectedindexchanged="ddlquotes_SelectedIndexChanged">
</asp:DropDownList>
<br /> <br />
<asp:Label ID="lblquotes" runat="server">
</asp:Label>
<br /> <br />
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="mylink.htm">Link
to:</asp:HyperLink>
</div>
</form>
</body>
</html>

4.9. ASP.NET – Security

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

Implementing Forms-Based Security


To set up forms-based authentication, you need the following:
 A database of users to support the authentication process
 A website that uses the database
 User accounts
 Roles
 Restriction of users and group activities
 A default page, to display the login status of the users and other information.
 A login page, to allow users to log in, retrieve password, or change password

4.10.ASP.NET – Deployment

There are two categories of ASP.NET deployment:


 Local deployment : In this case, the entire application is contained within a virtual directory and
all the contents and assemblies are contained within it and available to the application.
 Global deployment : In this case, assemblies are available to every application running on the
server.
There are different techniques used for deployment, however, we will discuss the following most
common and easiest ways of deployment:
 XCOPY deployment
 Copying a Website
 Creating a set up project

4.11.ASP.NET – User and Custom Controls


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

Create a new web application.


<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs"
Inherits="customcontroldemo.footer" %>
Add the following code to the file:
<table>
<tr>
<td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
</tr>
<tr>
<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>

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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Welcome to ASP.Net Tutorials "></asp:Label>
<br /> <br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Copyright Info" />
</div>
<Tfooter:footer ID="footer1" runat="server" />
</form>
</body>
</html>

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>

Working with Custom Controls


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

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.

A WCF application consists of three components −


 WCF service,
 WCF service host, and
 WCF service client.
Fundamental Concepts of WCF
Message
This is a communication unit that comprises of several parts apart from the body. Message instances are
sent as well as received for all types of communication between the client and the service.
Endpoint
It defines the address where a message is to be sent or received. It also specifies the communication
mechanism to describe how the messages will be sent along with defining the set of messages. A structure
of an endpoint comprises of the following parts −
Address
Address specifies the exact location to receive the messages and is specified as a Uniform Resource
Identifier (URI). It is expressed as scheme://domain[:port]/[path]. Take a look at the address mentioned
below −
net.tcp://localhost:9000/ServiceA
Here, 'net.tcp' is the scheme for the TCP protocol. The domain is 'localhost' which can be the name of a
machine or a web domain, and the path is 'ServiceA'.
Binding
It defines the way an endpoint communicates. It comprises of some binding elements that make the
infrastructure for communication. For example, a binding states the protocols used for transport like TCP,
HTTP, etc., the format of message encoding, and the protocols related to security as well as reliability.
Contracts
It is a collection of operations that specifies what functionality the endpoint exposes to the client. It
generally consists of an interface name.
Hosting
Hosting from the viewpoint of WCF refers to the WCF service hosting which can be done through many
available options like self-hosting, IIS hosting, and WAS hosting.
Metadata
This is a significant concept of WCF, as it facilitates easy interaction between a client application and a
WCF service. Normally, metadata for a WCF service is generated automatically when enabled, and this is
done by inspection of service and its endpoints.
WCF Client
A client application that gets created for exposing the service operations in the form of methods is known
as a WCF client. This can be hosted by any application, even the one that does service hosting.
Channel
Channel is a medium through which a client communicates with a service. Different types of channels get
stacked and are known as Channel Stacks.
SOAP
Although termed as ‘Simple Object Access Protocol’, SOAP is not a transport protocol; instead it is an
XML document comprising of a header and body section.
Advantages of WCF
 It is interoperable with respect to other services. This is in sharp contrast to .NET Remoting in
which both the client and the service must have .Net.
 WCF services offer enhanced reliability as well as security in comparison to ASMX (Active
Server Methods) web services.
 Implementing the security model and binding change in WCF do not require a major change in
coding. Just a few configuration changes is required to meet the constraints.
 WCF has built-in logging mechanism whereas in other technologies, it is essential to do the
requisite coding.
 WCF has integrated AJAX and support for JSON (JavaScript object notation).
 It offers scalability and support for up-coming web service standards.
 It has a default security mechanism which is extremely robust.

You might also like