0% found this document useful (0 votes)
7 views

Asp.NET Unit-5

This document covers the essentials of working with XML, application configuration, and deployment in ASP.NET, including reading and writing XML, web services, and configuration settings. It explains the differences between XML and HTML, features of XML, and the role of XML parsers, along with methods for writing and reading datasets in XML format. Additionally, it introduces web services, their protocols, and how to create and consume them in ASP.NET applications.

Uploaded by

abhaychavda682
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)
7 views

Asp.NET Unit-5

This document covers the essentials of working with XML, application configuration, and deployment in ASP.NET, including reading and writing XML, web services, and configuration settings. It explains the differences between XML and HTML, features of XML, and the role of XML parsers, along with methods for writing and reading datasets in XML format. Additionally, it introduces web services, their protocols, and how to create and consume them in ASP.NET applications.

Uploaded by

abhaychavda682
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

Sub.: ASP.NET UNIT - 5 B.C.A.

Sem - 5

5 Working with XML, Application Configuration


&Deploymen
Topic Covered
1. Reading from XML
2. Writing to XML
3. Web Service Introduction [HTTP,XML,SOAP,WSDL,UDDI, creating aWeb services]
4. Introduction To Web.Config
5. Common Configuration
6. Appsettings
7. Tracing
8. Custom Error
9. Authentication & Authorization
10. Deployment of Application in web server

 Introduction
 XML stands for eXtensible Markup Language.
 A text file that contains information organized in a structure that meets XML standards.
 XML is a markup language much like HTML but both have many differences.

 Difference Between XML & HTML


 HTML is a markup language. View/ presentation is its main goal.
 So HTML always focuses on how your data will look.
 XML is also a markup language. Data is the main goal of XML.
 It is designed to store and transfer your data from one location to another via XML mainly
focuses on data part. You can specify your own rules to enter data as per your requirement in
XML.

 Features of XML
 Using XML you can create your own tags.
 So by creating your own tags you can specify your own set of rules to enter data between
tags.
 Consider following example ,
 <Age>35</Age>
 You can see here that <Age> tag have a data i.e. 35. Now while creating <Age>tag, you can
specify rules for age, so that these tags wont allow you to enter invalid <Age> value.
 XML can have a file called DTD (Document Type Definition or XSD (XML Schema
Definition- Both of these files are used to specify rules for XML data. Out of these two,
XSD gives, much more facilities then DTD.
 For example, in above example we discussed, about <Age> tag (Element) which should
accept AGE only between 1 to 100.
 In which file you will write these rules? That is XSD File.
 XML is platform independent. So today it is used widely across web applications to transfer
data.
 XML can separate Data from HTML. The reason behind this is that HTML is mainly used
for presentation purpose where as XML focuses on data part.
 In XML, you can create DTD (Data Type Definition) and XSD (XML Schema Definition)
files to specify your own set of rules for user defined tags.

Page 1 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 In XML, you can create XSLT (XML StyleSheet Transformation) files to show your XML
data in particular format.
 XML is called eXtensible Markup Language because you can create your own tags. Further
more you can again create new tags with already created tags.
 Which means you can extend your previously created tags.

 What is XML Parser ?


 We have already discussed that in XML, you can create your own set of tags and for each of
your tags you can define your own set of rules. Now, think as if we have defined our own set
of rules in XML. But who will check those rules. Who checks whether your XML file is in
proper format or not?
 That is XML Parser. XML Parser is a small software tool that reads XML file for two
purpose. XML Parser can check whether XML file is Well-Formed and Verified or not.
 An XML parser parses (converts) XML documents and sends data to display in a browser.
 MSXML is most popular XML Parser as it comes along with all IE. Versions- today.
 There are plenty of other parsers available under XML. They are REXML, AElfred, Electric
XML, eXML, FastXML, libxml, Xerces etc.

 Rules for creating XML file


 Every XML document can have only one root element.
 Every start tag must have end tag.
 End tag cannot contain any information.
 All attributes value must be written in double quotes (“ )
 All elements must be nested properly.
 Elements (Tags) in XML are case-sensitive.
<?xml version=“1.0” encoding=“UTF-8”?>
<!--This is example of XML file which has student data- >
<students>
<student id=“101”>
<name>kruti purohit</name>
<city>junagadh</city>
</student>
</students>
 First part shows processing instruction line. It shows XML version and encoding standard
which will be used by XML.
 Second part shows comment line. XML can have comments similar to HTML.
 Third part is the data part. You can see that there is only one root element. All other nodes
are inside root node i.e. <students> and </students>.
 All tags are properly nested. All attribute values are written in double quotes (“----”).
 All tag, are written in case-sensitive manner.

 WRITING DATASETS TO XML & READING DATASETSWITH XML


 .NET has got a special namespace for XML which gives you all classes to access XML
features from top to bottom.
 The namespace is
 “System.xml" namespace
 This namespace provides you no. of classes to manipulate XML file.
 Writing DataSet to XML
 This is the procedure to write data to the XML file from DataSet.

Page 2 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 WriteXML( ) method :
This method is used to read data from DataSet and write data as XML data.
DataSetName is Treated as Root Element
All Tables of DataSets are treated as Main Elements.
All the Column of the particular Table are treated as Sub element
All Rows data is the actual data of the xml file
 WriteXMLSchema( ) method :
We have discussed a small bit of Xml Schema Defination file in XML Basics part.
XMLSchema is a file which contains rules for Xml Elements and their data. You may
also have some Schema information along with you DataSet.
If you use only WriteXml() method, only data. is written as XML. But along with data if
you want to write schema information, you can use WriteXmlSchema() method.
 Reading DataSets with XML
 This is the procedure to store the XML file data into a particular DataSet.
 ReadXml ( ) method :
This method is used to read Xml data from any Xml file to DataSet.
It treats all main Elements under root element as different tables, if you are using
DataSet to read the data.
It automatically stores data in Xml way, because you are already reading a file which is
in Xml format.
 Reading XmlSchema( ) method :
XmlSchema is a file which contains rules for Xml Element and their data. You may also
have some Schema information along with your DataSet.
If you use only ReiadXmlQ method. It just reads entire d.ata from Xml and stores it into
DataSet or DataTable.
But before reading Xml data into DataSet, if you want to specify some schema rules
(data rules) before writing xml data to DataSet/DataTable, you can use
ReadXmlSchema() which allows you to specify, XSD file and it restricts the data being
copied into Dataset / DataTable.

 Web services
 Introduction
o Web services are one of the strongest feature that is exposed by Microsoft since
ASP.NET launched.
o As you are new to Web Services, you might have first question that what are web
services??
o Web Services are group of web methods where each web method gives you some
particular functionality. Web methods are just same as those methods, but all web
methods are combined under a single Web Service and Web Service is uploaded / kept
on Web Server so that you can use its functionality through various Web methods.
o You can use this web services method for your windows application as well as in web
application.
o Web services can be used by different applications regardless of the programming
language, Operating System and Hardware platform.
o The net result is reduced complexity and more time for a developer to concentrate on
business logic rather than plumbing.
o A web service is a distributed computing technology that enables the exposure and reuse
of logical business entities over the Internet.
o Web services provide a platform-independent means of exposing business logic over the
Internet.

Page 3 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

o Creating ASP.NET web services is easy and abstracts much of the complexity associated
with Internet communications. This allows developers to concentrate on business logic.
o web services has no. of web methods that provide different functionality which can be
accessed by different types of application.
o An application which uses Web Service is called as Web Service client as it is used
particular web service.
o today there are so many clients, each of them don’t use similar configuration. Some
client use different hardware, some use different operating system and programming
languages.
o Now question is how to share something among all of them. Web services are the
components which are shareable among all types of hardware, OS and programming
language.
o The reason behind these are web services are
o Platform independent.
o Web services can be shared among any platform. Now the question arises is how it is
possible.
o The answer is various standard and protocols work behind web services.
o Standard / Protocols for Web Services
XML (eXtensible Markup Language)
SOAP(Simple Object Access Protocol)
WSDL (Web Services Description Language)
UDDI(Universal Description Discovery Integration)

 XML (eXtensible Markup Language)


o XML File has a standard data representation format and standard rules. This protocol is
responsible for handle different machine independency.
o XML File is a platform independent. So that the content of the XML File can be
understood by any machine without care of Hardware platform, operating system and
programming language.
o Web methods are developed in any language method name, arguments (parameters) and
return value is converting in XML File format so it can be understood by every machine.
 SOAP(Simple Object Access Protocol)
o The Simple Object Access Protocol (SOAP) is a communications protocol that
enablesvclients to interact with UDDI directories and web services.
o XML is the base of Web Services. Web Service argument and return values are written
in a form of XML.
o But how they are passed over the web or in other words how web service arguments or
return values are transferred over HTTP.
o SOAP is XML based protocol that allows different applications to share information
over HTTP.
o In short using SOAP XML data can be transferred over HTTP from one location to
another location.
o This protocol is responsible for share methods information (method name, parameter and
return value) which is stored in XML File. This protocol transfers the method
information on web through HTTP.
o SOAP is a standard communication protocol for interchanging information in a
structured format distributed environment.
o For transfer the information on internet SOAP creates a package for method name and
arguments and passed to web server in XML format
o When the SOAP packet arrives at the Web server on which the web service is placed, the
web method name and its parameters are extracted from the SOAP packet.

Page 4 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

o After this appropriate web method is invoked, execute and again answer value is
returned back using SOAP packet in reverse.

 WSDL (Web Services Description Language)


o As we have already discussed that Web Services are platform independent. So,
explanation of Web Method i.e. Its parameters, return values and body, everything
should also be in standard format so that it can be shared among all platform
o This is achieved by using XML based description language called WSDL (Web Services
Description Language). WSDL is a language which is used to describe Web Service and
its Web Methods.
o The Web Services Description Language (WSDL) is an XML-based format for
describing a web service.
o It describes what the web service is, its parameters, and how to use it.
o WSDL contains following information about particular web services and its web
methods :
At which website the all web services are located
Web Services used for what
The type of parameter and return value for each method of particular Web
Service
Format of web service method
From where this web method is access .

 UDDI (universal Description Discovery and integration)


o UDDI is a directory service where different companies can register and search for their
web services.
o You can say that UDDI provides standard mechanism to register and discover a Web
Service.
o If we talk in easy words, UDDI is a place (directory) for storing information about Web
Services.
o These directories manage WSDL documents and provide a means for clients to find and
use web services.
o The client who wants to access some web service, need to first of all find the particular
web service and then need to use it.
o The place where you can find all the registered web services, is UDDI.
o When you register Web Service under UDDI, its registered and the URL of Web Service
is stored under UDDI, which can be accessed by client after searching it. UDDI
communicates via SOAP.
o The fact is that it was never widely adopted and practically no one uses it. Instead, most
web service implementations use other forms of documentation to publish their web
services.
o For example, Amazon.com has web services that anyone can use; you just visit its site
and read its documentation, which includes all the information you need for finding and
using its web services.

Page 5 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 Namespaces used for Web Services :


o There are two important namespaces which are used for creating and consuming web
services. They are as follows
System.Web.Services
System.Web.Services.protocol
 Web services related files
o There are two types of files that work along with web services.
.asmx file(web service class)
This file is the entry point of any web service
.cs/.vb (web service code behind file)
This file contains web methods which will have some code.

o Application for writing Dataset to XML


o - At Design time:-
Database Design:-

Design view:-

using System.Data;
using System.Data.SqlClient;
using System.Web.Configuration;
public partial class _Default : System.Web.UI.Page
{
static string str = WebConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;

Page 6 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

SqlConnection con = new SqlConnection(str);


SqlDataAdapter da;
DataSet ds = new DataSet();

protected void Page_Load(object sender, EventArgs e)


{
}
protected void btnWritexml_Click(object sender, EventArgs e)
{
da = new SqlDataAdapter("Select * From Std", con);
ds.DataSetName="StudentData";
da.Fill(ds, "student");
string path = MapPath("Student.xml");
ds.WriteXml(path);
path = MapPath("StudentWithSchema.xml");
ds.WriteXmlSchema(path);
Response.Write("Data Written Successfully");
}
protected void btnReadxml_Click(object sender, EventArgs e)
{
ds.Clear();
ds.ReadXmlSchema(MapPath("StudentWithSchema.xml"));
ds.ReadXml(MapPath("Student.xml"));
Response.Write(ds.Tables.Count + "<br/>");
Response.Write(ds.Tables[0].TableName + "<br/>");
Response.Write(ds.Tables[0].Columns[0].ColumnName);
GridView1.DataSource=ds;
GridView1.DataBind();
}
}
 Application for Web Service
 Create new ASP.NET website
 Add new Database as follows

 Add some data in it.


 Again open another VS and create new Website -> ASP.NET Webservice
 Add following web method in App_Code -> Service.cs
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment
the following line.

Page 7 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

// [System.Web.Script.Services.ScriptService]
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components
//InitializeComponent();
}

[WebMethod]
public bool login(String username, string password)
{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=E:\ASP_NET\webServiceDemo\App_Data\Lo
gin.mdf;Integrated Security=True;User Instance=True");
con.Open();
SqlCommand cmd = new SqlCommand("select * from login", con);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
if (dr[0].ToString() == username && dr[1].ToString() == password)
{
return true;
}
}
con.Close();
return false;
}
}
 Run .asmx file and invoke your web method to test the service
 Make one “dll” folder in your folder
 If successfully runs now write click on your application and select option “Publish Web
Site”

 Now again work in your Website which you have added database

Page 8 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 From website menu-> Add References -> and select Browse tab form dialog box and
browse your App_code.dll from you’re “ dll” folder -> bin

 Design your web form as follow

 Now write code in btnLogin ‘s click event


using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
Service s = new Service();
if (s.login(txtUsername.Text, txtPassword.Text))
{
Response.Redirect("~/welcome.aspx");
}
else
{
Response.Write("invalid username or password...");
}
}
}

Page 9 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 Overview of ASP .NET Configuration


 ASP.NET Configuration system is used to describe the properties and behaviors of various
aspects of ASP.NET applications. ASP.NET uses XML-based configuration system that is
more accessible and easier to use.
 You can configure features, such as Connection Strings, Authentication Modes, Caching,
Debug and Tracing, Custom Errors and many more.
 ASP.NET configuration is done in XML file format because XML is platform independent.
so that it can applied on any type of machine, platform, etc.
 ASP.NET Configuration allows you to define configuration settings at the time of creating
your Web Application for the first time. You can also add configuration even after your
Application is created..
 Benefits of XML-based Configuration files
 ASP.NET Configuration system is extensible and application specific information can be
stored and retrieved easily. It is human readable.
 You need not restart the web server when the settings are changed in configuration file.
ASP.NET automatically detects the changes and applies them to the running ASP.NET
application.
 You can edit Configuration file using simple text editor. It can be easily exchanged.
 ASP.NET uses a hierarchical system of configuration.
 When an ASP.NET application starts, this hierarchy of configuration files is merged and
cached in memory.
 If you make a change to any of the configuration files in the hierarchy, the new
configuration settings are loaded into memory automatically.
 Furthermore, when you make a change to a configuration setting, you don’t need to stop and
restart an application manually for the new setting to take effect.
 The ASP.NET Framework reloads the cached configuration settings automatically when the
configuration settings are changed on the file system.
 There are two types of configuration files which are used to configure either all web
applications stored in your machine or to configure individual web application. They are
o Machine.Config
o Web.Config

 Server Configuration file (Machine.config)


 Every ASP.NET server installation includes a configuration file named machine.config, and
this file is installed as a part of .NET Framework installation. You can find machine.config
in
 C:\<Windows>\Microsoft.NET\Framework\<version>\Config\
 ASP.NET 3.5 provides another two files machine.config.default and
machine.config.comments. The machine.config.default acts as a backup for the
machine.config file. The machine.config.comments file contains a description for each
configuration section and explicit settings for the most commonly used values.
 If you are using Visual Web Developer (or Visual Studio .NET), then you can modify
certain configuration settings with the Web Site Administration Tool. This tool provides you
with a form interface for making configuration changes.
 You open the Web Site Administration Tool by selecting the menu option Website,
ASP.NET Configuration. Selecting this option opens a browser window that contains the
tool.
 Application Configuration file (Web.config)

Page 10 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 Each and Every ASP.NET application has its own copy of configuration settings stored in a
file called Web.config. This file is generated from Machine.Config file. Web Config file is
Stored in
 C:\<Windows>\Microsoft.NET\Framework\<version>\Config\
 If the web application spans multiple folders, each sub folder has its own Web.config file
that inherits or overrides the parent's file settings.
 Configuration File Format
 Both Machine.config and Web.config share the same XML schema. Configuration files are
divided into multiple sections, with each section being a top-level XML element. The root
level element in a configuration file is always <configuration>. Configuration file is
organized as hierarchy of section handlers, with each section provides a unique
functionality.
<?xml version=“1.0” ?>
<configuration>
<!-- All other Configuration sections are place here inside configuration
section -->
</configuration>

 <Configuration> Sections
 <configSection> : This allows you to configure different sections of web application like
javaScript, Web Services, Resources etc.
 <appSetting> :Configures custom settings for an application. The settings in this section
can be compared to application variables.
 <connectionString> : Specifies a collection of database connection strings, as name/value
pairs, for ASP.NET applications and features.
 <System.web> :This is important element used to configure your web application.
<compilation> <authentication>
<caching> <customErrors>
<deployment> <roleManager>
<trace> <sessionState>
<webServices>
 https://www.youtube.com/watch?v=l3Sqdk88gH4<system.codedom> : This section
stores compiler specific information used for your web application under <compilers>
element.
 <system.webServer> : This section stores information and configuration setting for web
servers which will be used for your deploying and running your web application
 <runtime> : This section is used to specify some runtime settings for your web application.
Run Time setting can include no .of setting like connection string, tracing, data provider etc.

Application Settings
The application settings allow storing application-wide name-value pairs for read-only access.
For example, you can define a custom application setting as:

<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>

Page 11 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

For example, you can also store the name of a book and its ISBN number:

<configuration>
<appSettings>
<add key="appISBN" value="0-273-68726-3" />
<add key="appBook" value="Corporate Finance" />
</appSettings>
</configuration>

 Common Configuration Setting


 Tracing Web Application
 Customizing Errors
 Authentication and Authorization
 Enabling Role Manager
 Session Configuration
 Trust Levels
 Web Service Configuration
 Caching

Tracing Web Site


 Tracing is a very important thing in the web site. It is useful to find the bug or logical error
in the particular web page or whole application.
 It display the values of the all the variables, session variable, Cookie, Application Variable
and control properties etc.
 By tracing you can also maintain a log file. In this log file all the information about the
errors and exception in the web site or particular web page.
Customizing Errors (Redirecting Errors to Customized Pages)
 Sometimes you are not aware of a some types of errors or errors which is based on user
input.
 At that time error will occur in the browser or display unexpected output to the user. So it
will generate bad effect on the user.
 So you have facilities to handle this type of errors. Errors like Bad Request, Page Not
Found, Server down etc.
 You can redirect your web site on particular error page which is made for display error or
handling error.
 So that page displays some specific message according to the error. You can redirect to
particular error page by particular error code for different errors.

Authentication and Authorization


 This setting is useful for the security purpose of the website.
 Now a day there are many possibilities to hack the web site. And main thing you have to
protect your web site from virus.
 So you have facilities to can’t access this web site by the unauthorized user. So this can be
done by Authentication and Authorization

Enabling Role Manager


 This is one of the important part of the web site. In the web site basically two part admin
side and client side.

Page 12 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 In the Admin side pages are generally made for useful web site related information or
setting. So that pages cannot be accessed by the common user otherwise it can be harmful to
your website.
 So to those pages you have to give some specific rights or security. This thing can be
handling by Role Manager.
.
Session Configuration :
 You can configure session related settings under this. Under Session configuration, you can
specify session settings like, Timeout Period, Session Mode, Cookie based Session or
Cookieless session, SqlCommandTimeout,NetworkTimeout, etc.
 Many of these sessions based configurations can be done at different levels of session
handling.

Trust Levels
 This thing is useful at the time of web developing. Web site can be developed by many
person so different person have different rights.
 Web master (Project Leader) can access all the pages of the web site. Web developer
(Designer, Programmer or Tester) have some limited access in the web site. Administrator
(DBA) has access for only back end pages. So this facility is provided by Trust Levels.

Web Services Configuration


 You can make the web services in the ASP .NET but by default it is accessed globally.
 So You can configure web services to lock some resources from being accessed by some
specific users.

Caching
 Sometimes caching is a very important thing for the web site. In your web server many
website or many web pages are available.
 So when you request for that page web server has to find the page or data. So at that time
page or data which is used recently that you can store in the cache memory. So it can not be
search each and every time for that you can increase the speed of your web server.
 Tracing
 To trace means to monitor.
 Tracing is a process of finding the problem from the application. When you executes the
web site or particular page within the web sites you cannot detect the value of variable,
property or methods or any code.
 Sometimes, you can’t find the actual problem at that time by the using of the trace
functionality you can know the flow of the program and find the bug or error by the help of
the value of source code without affect the actual output.
 Tracing is important to test your website in order to give perfect output as per developer’s
requirement which fulfills user’s need.
 Tracing can be done at two levels. They are
 Page Level Tracing
 Application Level Tracing

o Page Level Tracing


 Page level tracing is useful when you want to trace only selected web pages from
your website.
 Page level tracing allows you to trace a particular selected page.

Page 13 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 Explains how to enable tracing for a page, as well as how to include trace
statements in page output and how to interpret trace messages for a page.
 The page level tracing can be enabled using page directive called Trace.
 <%@ Page Language="vb" AutoEventWireup="False" Trace="True"
Codebehind="TraceTest.aspx.vb" Inherits="TracingExample.Test"%>
 Also, we have inbuilt Trace object to enable and disable the tracing dynamically.
In the page, on Load event if you write the below line, the tracing will be
enabled.
 Trace.IsEnabled = True;
 Trace :-
o This is the attribute of the page directive. It has a boolean value. Default
value is false. If you want
o to trace a particular page you can set the value true of Trace attribute.
 Trace Mode :-
o You can also use the TraceMode attribute of the <%@Page ...%>
directive to specify how you want
o your trace messages to be sorted when they are displayed on the page.
You can set this attribute to
o either SortByTime, which is the default, or SortByCategory.
o SortByTime displays trace messages in the order that they were
processed on the page.
o SortByCategory displays messages alphabetically by the category that
you assigned them when you wrote the code.
 You can write trace information by using Trace.Write() method or by using
Trace.Warn() method.
 so, if you have specified “SortByCategory”, all warned traced messages and
written traced messages are displayed.

o Application Level Tracing


 You can enable tracing for an entire application in that application's
configuration system the Web.config file in the application's root directory.
 When you are working with page level Tracing, you need to know probable page
that is to be traced.
 If your application is complex and if you want to trace you might not be aware
exact page that is to be traced.
 To avoid this problem , .NET platform, provides a facility to enable the tracing at
application level.
 When you enable global tracing, you also enable page-level tracing for all the
pages in the application, unless you explicitly disable tracing in a page using the
<%@Page...%> directive with a Trace = "false" attribute and value.
 As we know that web.config is a file that manages the application level settings.
In the same file we can mention setting of the Trace.
<configuration>
<system.web>
<trace enabled="true" pageOutput="true" requestLimit="10"
traceMode="SortByTime" localOnly="true" />
</system.web>
</configuration>

 Attributes of Trace Tag


 Enabled :- Enable or Disable tracing for entire application.

Page 14 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 PageOutput :- If this attribute value is set to true then the trace output will be displayed on
the page. If value of this attribute is set to false trace, then the trace output can be retrieved
using browser.
 RequestLimit :- This attribute is active only when the PageOutput attribute value is set to
false. This attribute defines the number of page requests that are to be traced.
 TraceMode :- To manage the order of the trace output, this attribute is used. For Example
SortByTime, SortByCategory etc.
 localOnly :- Set this attribute to "false" if you want access the trace log from any client.
Otherwise the log will be displayed on local machine only.
 Key Points:
 If you have enabled Application Level Tracing, no need to go for Page Level Tracing.
 Tracing is not enabled automatically. You need to enable tracing whether its page level or
Application Level.
 Tracing does not affect your output. It just give some additional information along with your
code.

 Error Handling (Custom Error)


 Error Handling is a very useful part in the application. When you are developing a
Application you can handle all the compile time errors because that type of errors are static
so you can handle at the time of development.
 But What about Run Time Errors ? You can not solve it at development because it depends
on the user input.
 So that type of errors is user specific. It display the unexpected output to the user and user
cannot run the application in a proper way. It will be bad effect of your application on the
user.
 So one of solution is that to handle this run time errors you can use the Try / Catch and
Finally block. But in the large application this is not an easy to handle error with try / catch
block because you have to put this block in each and every methods of the application. So it
is very critical task.
 At that time in the ASP .NET have a special functionality to handle run time errors. This
way of error handling is very easy compare to the Try / Catch block. There are three ways to
handle runtime errors according the error scope.
 Cycle of Error Events

 Server.GetLastError() Method :

Page 15 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

This is the method is used to get the Exception or Error which is currently generated.
According that Exception or Error you can take proper decision to continue the
application.
 Server.ClearError Method :
This Error is used to clear the current error after give the proper output to the user. If you
will not clear error. Error is generated and execution of the program is not continuing.

 Error Handling at Page Level


 In the Page Level Error Handling you can solve Error in two ways:
1. Using ErrorPage attribute of <%@ Page …%> Page directive
You can set the URL of the Error Page in the ErrorPage attribute of the <%@ Page
…%>
Page directive.
 Example :-
<%@ Page Language="C#" AutoEventWireup="true"
CodeFile="Default.aspx.cs" Inherits="_Default" ErrorPage="~/Error.aspx" %>

2. Using Page_Error() Method


 You have to write the Page_Error Event in the code behind file or in the script tag in .aspx
file. In that event you can write the code according to the error handling. You can give the
specific output to the user or redirect to the particular error page.
 Example :-
public void Page_Error(object sender, EventArgs e)
{
Response.Redirect(“Error.aspx”);
}

 Error Handling Using Application_Error()


 event of Globle.asax file
o When you are not clear about the error that error occurred in which page or Sometimes
the possibilities is there error occurred in more than one pages at that time you have to
handle the error using Application_Error () event of the Globle.asax file. This event is
occurred when error is fire from any Page of the Application.
void Application_Error(object sender, EventArgs e)
{
Response.Redirect("Error.aspx");
}

 Error Handling Using <customError> tag of web.config file


o This is also used to handle the error at application level. When you are not clear about
the error that error occurred in which page or Sometimes the possibilities is there error
occurred in more than one pages at that time you can use the <customError> tag of the
web.config file.
Example :-
<configuration>
<system.web>
<customErrors mode="On” defaultRedirect="GeneralError.aspx">
<error statusCode="401" redirect="UnAthorizedError.aspx"/>
<error statusCode="404" redirect="PageNotFoundError.aspx"/>
<error statusCode="408" redirect="TimeOutError.aspx"/>
</customErrors>

Page 16 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

<system.web>
</configuration>
Status Code Error Message

401 Unauthorized Access


403 Forbidden (Request is rejected)
404 Page not found
408 Request timeout
500 Internal server error
503 Service unavailable (server down)
 The mode attribute specifies whether to show user-defined custom error pages or ASP.NET
error pages. Three values are supported for this attribute:
o On - Custom error pages are always shown, unless one is not specified. When a custom
error page is not defined, an ASP.NET error page will be displayed which describes how
to enable remote viewing of errors.
o Off - Custom error pages are not shown. Instead, ASP.NET error pages will be displayed
always, which will have rich error information.
o RemoteOnly - Custom error pages are shown for all remote users. ASP.NET error pages
with rich error information are displayed only for local users.

 Authentication & Authorization


 Authentication and Authorization are two interrelated security concepts. In short,
authentication is a process of identifying a user, while authorization is the process of
determining if an authenticated user has access to the resource(s) they requested.
 Typically, authentication is achieved by the user sharing credentials that somehow verify the
user's identity
o Authentication means to check Who are you?
o Authorization means What rights give to the user?
 Types Of Authentication
 None (No Authentication)
 Forms authentication
 Windows authentication
 Passport authentication

[1] None (No Authentication)


 This option is used when you do not want to use any authentication for the web site.
This mode has not any type of the security in the web site.
 Example :-
<configuration>
<system.web>
<authentication mode=“None” />
</system.web>
</configuration>

[2] Forms Authentication


 This authentication mode is based on cookies where the user name and the password
are stored either in a text file or the database.

Page 17 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 After a user is authenticated, the user’s credentials are stored in a cookie for use in
that session. When the user has not logged in and requests for a page that is insecure,
he or she is redirected to the login page of the application. Forms authentication
supports both session and persistent cookies.
 Example :
<authentication mode="Forms">
<forms name="Login" loginUrl="Login.aspx">
<credentials passwordFormat="Clear">
<user name="prashant" password="doshi"/>
<user name="BBB" password="bbb"/>
</credentials>
</forms>
</authentication>
<authorization>
<allow users=”prashant,BBB"/>
<deny users="?"/>
</authorization>
 The statement <deny users="?"> indicates other users are not allowed. “?” indicates
all other users where as if you specify “*”, it indicates all the users.
 How to Check Username and Password ?
if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text))
{
FormsAuthentication.RedirectFromLoginPage (TextBox1.Text, false);
}
else
{
Response.Write("Invalid username or Password");
}

[3] Windows Authentication


 This is the default authentication mode in ASP.NET. Using this mode, a user is
authenticated based on his/her Windows account. Windows Authentication can be
used only in an intranet environment where the administrator has full control over
the users in the network. The following should be set in the web.config file to use
Windows Authentication.
 Example :
<authentication mode="Windows"/>
<authorization>
<allow users ="*" />
</authorization>

[4] Passport Authentication


 Passport authentication is concerned with Microsoft service authentication. This
method uses centralized authentication service provided directly by Microsoft
passport service developed by Microsoft.
 User login on the application by using his or her credentials details which are then
check by Microsoft’s website. If the user is authenticated then he or she would get
token. If he or she does not get a token that means the user is not authenticated by
Microsoft service.
 Example :

Page 18 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

<configuration>
<system.web>
<authenticationmode="Passport">
<passportredirectUrl="login.aspx" />
</authentication>
<authorization>
<deny users="?" />
</authorization>
</system.web>
</configuration>
 Type of Authorization :
o URL Authorization
o File Authorization
o Customized Authorization

URL Authorization
 We authorized you to particular URL. This authorization method is useful for
splitting Administrations and Normal Users. Where all the Administrative level Web
Pages are stored in different folder.
 Then only particular URL is authorized for administrative level users. So they can
access certain group of web pages for web site Administration.

File Authorization
 File Authorization is almost similar way to authorize you for particular file. This
method is also used to split admin pages and normal pages. If you have limited no. of
files to authorize, you can use this method, but for large number of users URL
authorization is best.

Customized Authorization
 You can also customize your Authorization. This can be done by using the location
element inside the configuration element of web.config file.
 Example :
<configuration>
<location path="OnlyAdmin.aspx" >
<system.web>
<authorization>
<allow users="Admin"/>
<deny users="*"/>
</authorization>
</system.web>
</location>
</configuration>

 Reading Setting From Configuration API

 As we have learn we done many settings in the web.config file like set the application
variable, connection strings, custom errors etc. So you need to get the value of that setting.
Most important thing how to read that value from the web.config or machine.config file and
that value you can use in your web site.

Page 19 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

 So reading that setting from the configuration file you need to use namespace
System.Web.Configuration. By using this namespace you can read the setting of the
web.config or machine.config file.

 Properties to read the value from the configuration file


(1) AppSetting :- Give the value of the variable which is set in <appSetting> tag of
web.config file.
Example :-
string user= WebConfigurationManager.appSetting[“user”];

(2) ConnectionStrings :- Gives the connection string which set in the


<connectionString> tag in web.config file
Example :-
string ConStr= WebConfigurationManager.
ConnectionStrings[“ConStr”].ConnectionString;

 Methods :
(1) GetSection() :- This method return the particular section according to path you have
given from the web.config file.
(2) OpenMachineConfiguration() :- This method is used to read the setting of the
machine.config file.
(3) OpenWebConfiguration() :- This method is used to read the setting from the
web.config file.
(4) GetWebApplicationSection() :- This method is used to read the section from the
Current web sites root folder web.config file.

Develop an ASP.NET application for Error Handling:-


- At Design Time:-
 For this we have to create on Folder in application root directory named ErrorPages.
 Take Aspx pages named PageNotFound.Aspx, DefaultError.Aspx and
RequestTimeOut.Aspx.
 Now in your web.config file put this code in <system.web> tags.
<system.web>
<customErrors mode="Off"
defaultRedirect="~/ErrorPages/DefaultError.aspx">
<error statusCode="404"
redirect="~/ErrorPages/PageNotFound.aspx"/>
<error statusCode="408"
redirect="~/ErrorPages/RequestTimeOut.aspx"/>
</customErrors>
</system.web>

ASPX Page:-

Page 20 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

ASPX.CS page:-
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Diagnostics;

public partial class _Default : System.Web.UI.Page


{
protected void btnPageNot_Click(object sender, EventArgs e)
{
Response.Redirect("ABC.aspx");
}
protected void btnDivideZero_Click(object sender, EventArgs e)
{
int a = 10;
int b = 0;
int c = a / b;
}
}
 In DefaultError.aspx just print <h1>Default Error </h1>
 In PageNotFound.aspx just print <h1>Page Not Found</h1>
 In RequestTimeOut.aspx just print <h1>Request Time Out</h1>

Develop an ASP.NET application for Authentication & Authorization


 Do change in <system.web> tag of configuration file.
<authentication mode="Forms">
<forms name="Login" loginUrl="Login.aspx">
<credentials passwordFormat="Clear">
<user name="prashant" password="doshi"/>
<user name="aaa" password="bbb"/>
<user name="admin" password="admin"/>
</credentials>
</forms>
</authentication>
<authorization>
<allow users="prashant,aaa,admin"/>
<deny users="?"/></authorization>
- At Design Time:-

Page 21 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string target = Request.QueryString["ReturnUrl"];

if (target == "/AuthenticationAndAuthorizationDemo/AdminPage.aspx")
{
Response.Write("<font color='red'>");
Response.Write("You must log in as 'Admin' in order to use AdminPage.aspx page");
Response.Write("</font> <hr>");
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text))
{
FormsAuthentication.RedirectFromLoginPage(TextBox1.Text, false);
}
else
{
Response.Write("Invalid username or Password");
}
}
}
Add AdminPage.aspx page and design as follows.

Add SuccessfullyLogin.aspx page and design as follows.

Page 22 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

Develop an ASP.NET application for Reading Settings from Configuration


API(web.config).

Add following settings in web.config file


<appSettings/>
<connectionStrings>
<add name="ConnectionString" connectionString="Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated
Security=True;User Instance=True"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<authentication mode="Forms">
<forms name="Login" loginUrl="Login.aspx">
<credentials passwordFormat="Clear">
<user name="prashant" password="doshi"/>
<user name="aaa" password="bbb"/>
<user name="admin" password="admin"/>
</credentials>
</forms>
</authentication>
<authorization>
<allow users="prashant,aaa,admin"/>
<deny users="?"/>
</authorization>
<customErrors mode="Off" defaultRedirect="~/ErrorPages/DefaultError.aspx">
<error statusCode="404" redirect="~/ErrorPages/PageNotFound.aspx"/>
<error statusCode="408" redirect="~/ErrorPages/RequestTimeout.aspx"/>
</customErrors>
</system.web>

- At Design Time:-
ASPX Page:-

using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Configuration;
using System.Web.Configuration;
public partial class GetSettings : System.Web.UI.Page
{
protected void btnConStr_Click(object sender, EventArgs e)
{ string x =
WebConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

Page 23 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

Response.Write("<p>Connection String: " + x);


Response.Write("<hr>");
}
protected void btnAutInfo_Click(object sender, EventArgs e) {
AuthenticationSection auth =
(AuthenticationSection)WebConfigurationManager.GetWebApplicationSection("system.web/
authentication");
Response.Write("<p> Authentication Mode :" +auth.Mode.ToString());
if (auth.Mode.ToString() == "Forms")
{
Response.Write("<p> Login URL :" +auth.Forms.LoginUrl.ToString());
Response.Write("<p> Time Out: " +auth.Forms.Timeout.ToString());
Response.Write("<p> Form Name: " + auth.Forms.Name);
} }
protected void btnReadErr_Click(object sender, EventArgs e)
{
CustomErrorsSection cust
=(CustomErrorsSection)WebConfigurationManager.GetWebApplicationSection
("system.web/customErrors");
Response.Write("<p> Error Mode: " + cust.Mode.ToString());
Response.Write("<p> Default Error Redirection URL: " +cust.DefaultRedirect);
CustomErrorCollection errs = cust.Errors;
foreach (CustomError ce in errs)
{
Response.Write("<hr>");
Response.Write("<br> Status Code: " +ce.StatusCode.ToString());
Response.Write("<br> Redirect URL: " + ce.Redirect);
}
Response.Write("<hr>"); } }

 Deployment of Application in web server


Deploying your application means putting it on a Web server so that it can be used either
through the Internet or an intranet. ... To deploy your application onto a production Web
server, you need to check: Server Web share paths and application URLs.

here 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
Page 24 of 25
Sub.: ASP.NET UNIT - 5 B.C.A. Sem - 5

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. Unike 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 errtor checking for the files.
 The initial page load will be slow.

Creating a Setup Project


In this method, you use Windows Installer and package your web applications so it is ready to
deploy on the production server. Visual Studio allows you to build deployment packages.

Page 25 of 25

You might also like