Unit Iii Window and Web Based Applications

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 35

UNIT III

WINDOW AND WEB BASED APPLICATIONS

 ASP.NET Core is the new and totally re-written version of the ASP.NET web framework.

 It is a free, open-source, and cross-platform framework for building cloud-based applications .

 Example web apps, IoT apps, and mobile backends.

 It is designed to run on the cloud as well as on-premises.

 It was architected modular with minimum overhead.

 other more advanced features can be added as NuGet packages as per application requirement.

 high performance, require less memory, less deployment size, and easy to maintain.

• Supports Multiple Platforms.

ASP.NET Core applications can run on Windows, Linux, and Mac

• Fast

ASP.NET Core allows us to include packages that we need for our application.

This reduces the request pipeline and improves performance and scalability.

• IoC Container

It includes the built-in IoC container for automatic dependency injection which makes

it maintainable and testable.

• Integration with Modern UI Frameworks.

It allows you to use and manage modern UI frameworks such as AngularJS, ReactJS,

Umber, Bootstrap, etc. using Bower (a package manager for the web).

• Hosting

ASP.NET Core web application can be hosted on multiple platforms with any web

server such as IIS, Apache etc.

• Code Sharing

It allows you to build a class library that can be used with other .NET frameworks such as
.NET Framework 4.x or Mono.

• Side-by-Side App Versioning

ASP.NET Core runs on .NET Core, which supports the simultaneous running of multiple

versions of applications

• Smaller Deployment Footprint

ASP.NET Core application runs on .NET Core, which is smaller than the full .NET Framework.

Cross-platform ASP.NET Core

• ASP.NET Core applications run on the Windows, Mac or Linux OS using the .NET Core framework
(now known as .NET 5/6/7).

• ASP.NET Core web application are self-hosted using internal web server called Kestrel.

• The platform specific web server such as IIS is used as external webserver that sends requests to the
internal webserver Kestrel.
ASP.NET Core Version History

 Microsoft launched ASP.NET web framework along with .NET Framework 1.0 in 2002.

 It was designed to run on Windows platform.

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

and Linux using .NET Core framework.

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

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.

 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.
Control Name Applicable Events Description

Label None It is used to display text on the HTML page.

TextBox TextChanged It is used to create a text input in the form.

LinkButton Click, Command It is used to create a button that looks similar to the hyperlink.

ImageButton Click It is used to create an imagesButton. Here, an image works as a


Button.
Hyperlink None It is used to create a hyperlink control that responds to a click
event.

DropDownList SelectedIndexChan It is used to create a dropdown list control.


ged

ListBox SelectedIndexCnha It is used to create a ListBox control like the HTML control.
ged

Image None It is used to show image within the page.

Panel None It is used to create a panel that works as a container.

PlaceHolder None It is used to set placeholder for the control.

Calendar SelectionChanged, It is used to create a calendar. We can set the default date,
VisibleMonthChang move forward and backward etc.
ed, DayRender

AdRotator AdCreated It allows us to specify a list of ads to display. Each time the user
re-displays the page.

Table None It is used to create table.


XML None It is used to display XML documents within the HTML.

Literal None It is like a label in that it displays a literal, but allows us to


create new literals at runtime and place them into this control.

DATA BINDING:

Binding can be classified into:


 Simple data binding
 Complex data binding
Simple data binding

Simple data binding allows you to bind a control to a single data element. The most common use of
simple data binding involves binding a single data element, such as the value of a column in a table, to a
control on a form. You use this type of data binding for controls that show only one value. Uses of simple data
binding include binding data to text boxes and labels. Consider a scenario where a Windows Forms form needs
to be created to display employee details in the following way.

In the preceding form, one value needs to be displayed in each of the controls. Therefore simple data binding
will be performed for each control.
Steps

1. Press F4 to open the properties window.


2. Select the first TextBox to display its properties window.
3. Expand the (DataBindings) property.
4. Select the text property to enable the drop-down list. Click the drop-down list.
5. Add a project data source in the drop-down list.

6. Create a connection with the AdventureWorks database and select the HumanResources.employee table.
7. Select the first TextBox. Expand "Other data source" ---> "Project data source" -->
"AdventureWorksdataset" --> "Employee" --> "EmloyeeId".
8. Select the second TextBox. Expand the DataBinding property then select "Text" ---> "Employee
Binding source" then select column(National ID) from the list.
9. Similarly, bind TextBox3 and TextBox4 with the column contactid and Login ID.
10. Press F5. If everything goes well, you will see the following output:
Implementing BindingNavigator

1. Drag and drop a BindingNavigator control from the Toolbox.

2. Select BindingNavigator1; this will display the properties window.


3. Select the bindingSource property from the properties Window to enable the corresponding drop-down
list.
4. Select employeeBindingSource from the Drop-Down list as shown in the following figure.

5. Execute the Windows Forms form and verify the output. The Employee Details will be displayed as
shown in the following figure.
The following table describes the various symbols and their function in the BindingNavigator control:

Complex Data Binding


Complex data binding allows you to bind more than one data element to control. Using the column example,
complex data binding involves binding more than one column or row from the underlying record source.
Controls that support complex data binding include data grid controls, combo boxes, and list boxes.

Let's see complex data binding with a DataGridView:

1. Drag and drop a DataGridView from the Toolbox under the Data tab.

Click on the DataGridView task pop-up menu as shown in the following figure.
2. Select the choose Data Source drop-down list and then select the Add Project Data Source from the
DataGridView task pop-up menu as shown in the following figure.

3. In the database configuration wizard select database and click on "Next" as shown in the following
figure.
4. After clicking on the Next button you will get the following output.

5. Click on "New Connection" to create a new connection to your data source.


To add a connection:

Provide the server name (in my case it is (.))

o If your server is not using Windows authentication then select "Use SQL Server authentication".
o Provide the username and password.
o Provide the database name AdventureWorks from the Select or enter a database name drop-down
list.
o Click on the Test Connection Button. If everything goes well you will see a message box saying
thatTest the connection succeeded as shown in the following figure.
6. Click the OK button.
7. Click the OK button on the Add Connection dialog box.
8. Select Yes, Include sensitive data in the connection string, and click the "Next" button in the
DataSource configuration wizard. You will get a page as displayed in the following figure.
9. Ensure that the Yes, save the connection as the check box is selected and the
AdventureWorksConnection string appears in the TextBox.

Note: We will see what the use of saving the connection string in the App.config file is in my future
article on ADO.Net.

10. Click the "Next" button. The Choose Your Database Objects page is displayed as shown in the
following figure.
11. Expand the table node and select the HumanResources.Employee table is shown in the following figure.
12. Click the "Finish" button. The form is displayed, as shown in the following figure.

Press F5 to execute the application. You will get the following output.
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
 racing
 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" %>

<configuration>
<system.web>

<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">


<error statusCode="403" redirect="NoAccess.htm"/>
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>

</system.web>
<configuration>

The <customErrors> section has the possible attributes:

 Mode : It enables or disables custom error pages. It has the three possible values:
o On : displays the custom pages.
o Off : displays ASP.NET error pages (yellow pages)
o remoteOnly : It displays custom errors to client, display ASP.NET errors locally.
 defaultRedirect : It contains the URL of the page to be displayed in case of unhandled errors.

To put different custom error pages for different type of errors, the <error> sub tags are used, where different
error pages are specified, based on the status code of the errors.
To implement page level error handling, the Page directive could be modified:

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


Inherits="errorhandling._Default" Trace ="true" ErrorPage="PageE

SECURITY

Implementing security in a site has the following aspects:

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

Forms-Based Authentication

Traditionally, forms-based authentication involves editing the web.config file and adding a login page with
appropriate authentication code.

The web.config file could be edited and the following codes written on it:

<configuration>

<system.web>
<authentication mode="Forms">
<forms loginUrl ="login.aspx"/>
</authentication>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
...
...
</configuration>

The login.aspx page mentioned in the above code snippet could have the following code behind file with the
usernames and passwords for authentication hard coded into it.

protected bool authenticate(String uname, String pass)


{
if(uname == "Tom")
{
if(pass == "tom123")
return true;
}

if(uname == "Dick")
{
if(pass == "dick123")
return true;
}

if(uname == "Harry")
{
if(pass == "har123")
return true;
}
return false;
}

public void OnLogin(Object src, EventArgs e)


{
if (authenticate(txtuser.Text, txtpwd.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked);
}
else
{
Response.Write("Invalid user name or password");
}
}

Passport-based authentication

Pass-port based authentication is a centralized authentication service provided by Microsoft that offers a single
logon and core profile services for member sites

Windows-based authentication

ASP.NET uses Windows authentication in conjunction with Microsoft Internet Information Services (IIS)
authentication. Authentication is performed by IIS in one of three ways: basic, digest, or integrated Windows
authentication. When IIS authentication is complete, ASP.NET uses the authenticated identity to authorize
access. For more information, see the following resources
Authorization

The purpose of authorization is to determine whether an identity should be granted the type of access that is
requested by a resource. There are two fundamental ways to authorize access to a given resource:

 File authorization

File authorization is performed by the and is active when you use Windows authentication. It does an
access-control-list (ACL) check of the .aspx or .asmx handler file to determine if a user should have
access. Applications can also use impersonation to get resource checks on resources that they are
accessing.

URL authorization

URL authorization is performed by which maps users and roles to pieces of the URL namespace. This
module implements both positive and negative authorization assertions. That is, the module can be used to
selectively allow or deny access to arbitrary parts of the URL namespace for certain sets, users, or roles.

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
XCOPY Deployment

XCOPY deployment means making recursive copies of all the files to the target folder on the target machine.
You can use any of the commonly used techniques:

 FTP transfer
 Using Server management tools that provide replication on a remote site
 MSI installer application

XCOPY deployment simply copies the application file to the production server and sets a virtual directory
there. You need to set a virtual directory using the Internet Information Manager Microsoft Management
Console (MMC snap-in).

Copying a Website

The Copy Web Site option is available in Visual Studio. It is available from the Website -> Copy Web Site
menu option. This menu item allows copying the current web site to another local or remote location. It is a
sort of integrated FTP tool.

Using this option, you connect to the target destination, select the desired copy mode:

 Overwrite
 Source to Target Files
 Sync UP Source And Target Projects

Then proceed with copying the files physically. Unlike the XCOPY deployment, this process of deployment is
done from Visual Studio environment. However, there are following problems with both the above deployment
methods:

 You pass on your source code.


 There is no pre-compilation and related error checking for the files.
 The initial page load will be slow.
VALIDATION CONTROL

ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or
contradictory data don't get stored.

ASP.NET provides the following validation controls:

 RequiredFieldValidator
 RangeValidator
 CompareValidator
 RegularExpressionValidator
 CustomValidator
 ValidationSummary

BaseValidator Class

The validation control classes are inherited from the BaseValidator class hence they inherit its properties and
methods. Therefore, it would help to take a look at the properties and the methods of this base class, which are
common for all the validation controls:

Members Description

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

EnableClientScript Indicates whether client side validation will take.

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.


IsValid Indicates whether the value of the control is valid.

It indicates whether in case of an invalid control, the focus should switch to


SetFocusOnError
the related input control.

ValidationGroup The logical group of multiple validators, where this control belongs.

Validate() This method revalidates the control and updates the IsValid property.

RequiredFieldValidator Control

The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a text
box to force input into the text box.

The syntax of the control is as given:

<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

RangeValidator Control

The RangeValidator control verifies that the input value falls within a predetermined range.

It has three specific properties:

Properties Description

It defines the type of the data. The available values are: Currency, Date,
Type
Double, Integer, and String.
MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"


ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control

The CompareValidator control compares a value in one control with a fixed value or a value in another control.

It has the following specific properties:

Properties Description

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare with.

ValueToCompare It specifies the constant value to compare with.

It specifies the comparison operator, the available values are: Equal,


Operator NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and
DataTypeCheck.
The basic syntax of the control is as follows:

<asp:CompareValidator ID="CompareValidator1" runat="server"


ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular
expression. The regular expression is set in the ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular expressions:

Character Escapes Description

\b Matches a backspace.

\t Matches a tab.

\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.
Apart from single character match, a class of characters could be specified that can be matched, called the meta
characters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

[2-7a-mA-M] Matches any character specified in the range.

\w Matches any alphanumeric character and underscore.

\W Matches any non-word character.

\s Matches whitespace characters like, space, tab, new line etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.


{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"


ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator

The CustomValidator control allows writing application specific custom validation routines for both the client
side and the server side validation.

The client side validation is accomplished through the ClientValidationFunction property. The client side
validation routine should be written in a scripting language, such as JavaScript or VBScript, which the browser
can understand.

The server side validation routine must be called from the control's ServerValidate event handler. The server
side validation routine should be written in any .Net language, like C# or VB.Net.

The basic syntax for the control is as given:

<asp:CustomValidator ID="CustomValidator1" runat="server"


ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>
Validation Summary

The Validation Summary control does not perform any validation but shows a summary of all errors in the
page. The summary displays the values of the ErrorMessage property of all validation controls that failed
validation.

The following two mutually inclusive properties list out the error message:

 ShowSummary : shows the error messages in specified format.


 ShowMessageBox : shows the error messages in a separate window.

The syntax for the control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server"


DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

Validation Groups

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

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.

Ad Rotator Control

The Ad Rotator control randomly selects banner graphics from a list, which is specified in an external XML
schedule file. This external XML schedule file is called the advertisement file.

The Ad Rotator control allows you to specify the advertisement file and the type of window that the link
should follow in the Advertisement File and the Target property respectively.
The basic syntax of adding an AdRotator is as follows:

<asp:AdRotator runat = "server" AdvertisementFile = "adfile.xml" Target = "_blank" />

Before going into the details of the AdRotator control and its properties, let us look into the construction of the
advertisement file.

The Advertisement File

The advertisement file is an XML file, which contains the information about the advertisements to be
displayed.

Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-based markup
language that enables you to store data in a structured format by using meaningful tags. The term 'extensible'
implies that you can extend your ability to describe a document by defining meaningful tags for the
application.

XML is not a language in itself, like HTML, but a set of rules for creating new markup languages. It is a meta-
markup language. It allows developers to create custom tag sets for special uses. It structures, stores, and
transports the information.

Following is an example of XML file:

<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>

Like all XML files, the advertisement file needs to be a structured text file with well-defined tags delineating
the data. There are the following standard XML elements that are commonly used in the advertisement file:
Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

NavigateUrl The link that will be followed when the user clicks the ad.

The text that will be displayed instead of the picture if it cannot be


AlternateText
displayed.

Keyword Keyword identifying a group of advertisements. This is used for filtering.

Impressions The number indicating how often an advertisement will appear.

Height Height of the image to be displayed.

Width Width of the image to be displayed.

Apart from these tags, customs tags with custom attributes could also be included. The following code
illustrates an advertisement file ads.xml:

<Advertisements>
<Ad>
<ImageUrl>rose1.jpg</ImageUrl>
<NavigateUrl>http://www.1800flowers.com</NavigateUrl>
<AlternateText>
Order flowers, roses, gifts and more
</AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>
<Ad>
<ImageUrl>rose2.jpg</ImageUrl>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl>
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>

<Ad>
<ImageUrl>rose3.jpg</ImageUrl>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl>
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions>
<Keyword>russia</Keyword>
</Ad>

<Ad>
<ImageUrl>rose4.jpg</ImageUrl>
<NavigateUrl>http://www.edibleblooms.com</NavigateUrl>
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>

Properties and Events of the AdRotator Class

The AdRotator class is derived from the WebControl class and inherits its properties. Apart from those, the
AdRotator class has the following properties:
Properties Description

AdvertisementFile The path to the advertisement file.

The element name of the field where alternate text is provided. The default
AlternateTextFeild
value is AlternateText.

The name of the specific list of data to be bound when advertisement file is
DataMember
not used.

DataSource Control from where it would retrieve data.

DataSourceID Id of the control from where it would retrieve data.

Specifies the font properties associated with the advertisement banner


Font
control.

The element name of the field where the URL for the image is provided.
ImageUrlField
The default value is ImageUrl.

KeywordFilter For displaying the keyword based ads only.

The element name of the field where the URL to navigate to is provided.
NavigateUrlField
The default value is NavigateUrl.

Target The browser window or frame that displays the content of the page linked.

Obtains the unique, hierarchically qualified identifier for the AdRotator


UniqueID
control.

Following are the important events of the AdRotator class:


Events Description

It is raised once per round trip to the server after creation of the control, but
AdCreated
before the page is rendered

DataBinding Occurs when the server control binds to a data source.

DataBound Occurs after the server control binds to a data source.

Occurs when a server control is released from memory, which is the last
Disposed
stage of the server control lifecycle when an ASP.NET page is requested

Occurs when the server control is initialized, which is the first step in its
Init
lifecycle.

Load Occurs when the server control is loaded into the Page object.

PreRender Occurs after the Control object is loaded but prior to rendering.

Unload Occurs when the server control is unloaded from memory.

Working with AdRotator Control

Create a new web page and place an AdRotator control on it.

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


<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile ="~/ads.xml"
onadcreated="AdRotator1_AdCreated" />
</div>
</form>

You might also like