Вы находитесь на странице: 1из 112

Web application development

The DOT NET (.NET) created by Microsoft is a software development platform focused on rapid application development (RAD), platform
independence and network transparency. DOT NET (.NET) is Microsoft's strategic initiative for server and desktop development for the
next decade. According to Microsoft, DOT NET (.NET) includes many technologies designed to facilitate rapid development of Internet and
intranet applications.
DOT NET (.NET) has brought new functionalities and tools to the application programming interface (API). These innovations allow
development of applications for both Windows and the web as well as components and services (web services). .NET provides a new
reflective, object-oriented API. .NET is designed to be sufficiently generic so that many different high-level languages can be
compiled.

Shrigen Technologies has Expertise in .NET


Shrigen provides design, development and integration business solutions based on the DOT NET (.NET) platform. Our team of
experienced Microsoft certified DOT NET (.NET) architects, analysts and developers delivers a wide range of comprehensive solutions in
the following key areas.

DOT NET (.NET) Desktop Application Development


ASP.NET (Web) Application Development
DOT NET (.NET) Software Product Development
Migration of Web and Desktop Applications to DOT NET (.NET)
Web Services Based DOT NET (.NET) Application Development
Mobile applications based on DOT NET (.NET) Compact Framework

ASP.NET Web Forms


ASP.NET is a development framework for building web pages and web sites with HTML,
CSS, JavaScript and server scripting.
ASP.NET supports three different development models:
Web Pages, MVC (Model View Controller), and Web Forms.

What is Web Forms?


Web Forms is one of the 3 programming models for creating ASP.NET web sites and web
applications.
The other two programming models are Web Pages and MVC (Model, View, Controller).
Web Forms is the oldest ASP.NET programming model, with event driven web pages written as a
combination of HTML, server controls, and server code.
Web Forms are compiled and executed on the server, which generates the HTML that displays
the web pages.
Web Forms comes with hundreds of different web controls and web components to build userdriven web sites with data access.

CS6001 C# AND .NET


PROGRAMMING

Unit
IV

Visual Studio Express 2012/2010


Visual Studio Express is a free version of Microsoft Visual Studio.
Visual Studio Express is a development tool tailor made for Web Forms (and MVC).
Visual Studio Express contains:

MVC and Web Forms


Drag-and-drop web controls and web components
A web server language (Razor using VB or C#)
A web server (IIS Express)
A database server (SQL Server Compact)
A full web development framework (ASP.NET)

CS6001 C# AND .NET


PROGRAMMING

Unit
IV

Working With XML File in ASP.NET


Introduction
Extensible Markup Language (XML) strores and transports data. If we use a XML file to store
the data then we can do operations with the XML file directly without using the database.
The XML format is supported for all applications. It is independent of all software
applications and it is accessible by all applications. Here is an example that shows how to
insert the data into the XML file and how to retrieve the data from the XML file; also how to
bind the data into tha DataList using ASP.NET. For this the following procedure can be used.
Step 1: First start Visual Studio 2010 by clicking "File" -> "New" -> "Web Site..." then click
on "ASP.NET Web Site". Now write the following inline code that will design your web page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 40%;
border-style: solid;
border-width: 1px;
background-color:Silver;
height: 152px;
}
.style2
{
width: 295px;
}
.style3
{
width: 754px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style2">
&nbsp;</td>
<td class="style3">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Employee_Inf
o rmation</td>
</tr>

CS6001 C# AND .NET


PROGRAMMING

Unit
IV

<tr>
<td class="style2">
Name:</td>
<td class="style3">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Emp_Id:</td>
<td class="style3">
<asp:TextBox ID="TextBox2"runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Qualification:</td>
<td class="style3">
<asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width
="132px">
<asp:ListItem>--SELECT--</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>BCA</asp:ListItem>
<asp:ListItem>MBA</asp:ListItem>
<asp:ListItem>BBA</asp:ListItem>
<asp:ListItem>BTech</asp:ListItem>
<asp:ListItem>MTech</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style2">
&nbsp;</td>
<td class="style3">
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Cl
ick"/>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Sho
w"/>
</td>
</tr>
</table>
<asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84"
BorderColor="#D EBA84"
BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"
GridLines="Both" RepeatDirection="Horizontal"
style="margin-right: 32px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510"/>
<HeaderStyle BackColor="#A55129" Font-Bold="True"ForeColor="White"/>
<ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510"/>
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"/>
<ItemTemplate>
<hrsize=0 />

CS6001 C# AND .NET


PROGRAMMING

Unit
IV

Name:<%#DataBinder.Eval(Container.DataItem,"name")%><br/>
Emp_id:<%#DataBinder.Eval(Container.DataItem,"Emp_id")%></a><br/>
Qualification:<%#DataBinder.Eval(Container.DataItem,"Qualification")
%><br/>
</ItemTemplate>
</asp:DataList>
<br />
</div>
</form>
</body>
</html>
The design will look as in the following image:

Step 2: Add a XML file by clicking "File" -> "Add new item" then click on "XML file". Name
this XML file Sample.xml. Put the following code in the XML file:
<?xml version="1.0"encoding="utf-8"?>
<EmployeeInformation>
</EmployeeInformation>
Step 3: After that add the following namespaces in the code behind:
using System.Data;
using System.Xml;

Step 4: Now write the following code in the code behind file:
public partial classDefault2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)

{
//Bind xml data to datalist
BindDatalist();

}
}
private void BindDatalist()
{
XmlTextReader xmlreader =new
XmlTextReader(Server.MapPath("Employee.xml")); DataSet ds = newDataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
DataList1.DataSource = ds;
DataList1.DataBind();
}
else
{
DataList1.DataSource = null;
DataList1.DataBind();
}
}

Step 5: Write the following code in the click event of the submit button, so that the
data that is entered is stored in the XML File:
protected void Button1_Click(object sender, EventArgs e)
{
XmlDocument xmldoc =new XmlDocument();
xmldoc.Load(Server.MapPath("Employee.xml"));
BindDatalist();
}
Step 6: Write the following code in the click event of the show button. Now the data
stored in the XML file can be shown.
protected void Button2_Click(object sender, EventArgs e)
{
XmlDocument xmldoc =new XmlDocument();
xmldoc.Load(Server.MapPath("Employee.xml"));
XmlElement parentelement = xmldoc.CreateElement("Details");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = TextBox1.Text;
XmlElement Emp_id = xmldoc.CreateElement("Emp_id");
Emp_id.InnerText = TextBox2.Text;
XmlElement Qualification =
xmldoc.CreateElement("Qualification"); Qualification.InnerText =
DropDownList1.SelectedItem.Text;
parentelement.AppendChild(name);
parentelement.AppendChild(Emp_id);
parentelement.AppendChild(Qualification);

xmldoc.DocumentElement.AppendChild(parentelement)
; xmldoc.Save(Server.MapPath("Employee.xml"));
BindDatalist();

Step 7: Run your application by pressing F5. The output is:

Step 8 : See your sample.xml file, it will include the data that I entered at the run time like
this:
<?xmlversion="1.0"encoding="utf-8"?>
<EmployeeInformation>
<Details>
<Name>Richa</Name>
<Emp_id>1</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</EmployeeInformation>
Summary: In this article I use a XML file so that the data is stored and retrieved in XML
using the Datalist in ASP.NET.

Parsing XML Files in .NET Using C#


Parsing XML files is an unglamorous task that can be time consuming and tricky. In the days
before .NET, programmers were forced to read XML as a text file line by line and then use string
functions and possibly regular expressions. This is a time-consuming and error-prone process,
and just not very much fun.
While I was writing .NET test automation that had test case data stored in XML files, I discovered
that the .NET Framework provides powerful new ways of parsing XML. But in conversations with
colleagues, I also discovered that there are a variety of opinions on which way of parsing XML
files is the best.
I set out to determine how many different ways there are to parse XML using .NET and to
understand the pros and cons of each technique. After some experimentation, I learned that
there are five fundamentally different ways to parse XML, and that the "best" method depends
both on the particular development situation you are in and on the style of programming you
prefer.
In the sections that follow, I will demonstrate how to parse a testCases.xml file using five
different techniques. Each technique is based on a different .NET Framework class and its
associated methods:

XmlTextReader
XmlDocument
XPathDocument
XmlSerializer
DataSet
After I explain each technique so you can modify my examples to suit your needs, I will give you
guidance on which technique should be used in which situation. Knowing these five methods for
parsing XML files will be a valuable addition to your .NET skill set. I'm assuming that you're
familiar with C#, VS.NET, the creation and use of class libraries, and have a working knowledge
of XML files.
The XML File to Parse and the Goal
Let's examine the testCases.xml file that we will use for all five parsing examples. The
file contents are shown in Listing One.
Listing One: XML file to parse

?
1

<?xml version="1.0" encoding="utf-8" ?>

<suite>

3
4
5

<testcase id="001" kind="bvt">


<inputs>

<arg1>4</arg1>

<arg2>7</arg2>

</inputs>

<expected>11.00</expected>
</testcase>

10
11

<testcase id="002" kind="drt">

12

<inputs>

13
14

<arg1>9</arg1>

15

<arg2>6</arg2>

16

</inputs>

17

<expected>15.00</expected>
</testcase>

18
19

<testcase id="003" kind="bvt">

20

<inputs>

21

<arg1>5</arg1>

22

<arg2>8</arg2>

23

</inputs>

24

<expected>13.00</expected>

25

</testcase>

26
27
28

<
/suite>

Note that each of the three test cases has five data items: id, kind, arg1,
arg2, andexpected. Some of the data is stored as XML attributes (id and kind),
and arg1 and arg2are stored as XML elements two levels deep relative to the root
node
(suite). Extracting attribute data and dealing with nested elements are key tasks regardless of
which parsing strategy we use.

The goal is to parse our XML test cases file and extract the data into memory in a form that we
can use easily. The memory structure we will use for four of the five parsing methods is shown in
Listing Two. (The method that employs an XmlSerializer object requires a slightly
different memory structure and will be presented later.)
Listing Two: CommonLib.dll definitions

?
1
2

using System;
using System.Collections;

3
4
5

namespace CommonLib
{

6
7

public class
TestCase
{

public string id;

public string kind;

10

public string arg1;

11

public string arg2;

12
13

public string expected;


}

14
15
16

public class Suite


{

17

public ArrayList items = new ArrayList();

18

public void Display()

19

20

foreach (TestCase tc in items)

21

22
23

Console.Write(tc.id + " " + tc.kind + " " + tc.arg1 +


" ");

24

Console.WriteLine(tc.arg2 + " " + tc.expected);

25

26

}
}

27

// class Suite

// ns

Because four of the five techniques will use these definitions, for convenience we can put the
code in a .NET class library named "CommonLib." A TestCase object will hold the five
data parts of each test case, and a Suite object will hold a collection of TestCase
objects and provide a way to display it.
Once the XML data is parsed and stored, the result can be represented as shown in >Figure 1.
The data can now be easily accessed and manipulated.
Figure 1 XML data stored in memory

Parsing XML with XmlTextReader


Of the five ways to parse an XML file, the most traditional technique is to use
theXmlTextReader class. The example code is shown in Listing Three.
Listing Three: Parsing XML using XmlTextReader

?
1

using System;

using System.Xml;

using CommonLib;

namespace Run

class Class1

[STAThread]

10

static void Main(string[] args)

11

{
CommonLib.Suite s = new CommonLib.Suite();

12
13
14
15
16

XmlTextReader xtr = new


XmlTextReader("..\\..\\..\\..\\testCases.xml");
xtr.WhitespaceHandling = WhitespaceHandling.None;
xtr.Read(); // read the XML declaration node, advance to <suite> tag

17
18
19
20

while (!xtr.EOF) //load loop


{
if (xtr.Name == "suite" && !xtr.IsStartElement()) break;

21
22
23

while (xtr.Name != "testcase" || !xtr.IsStartElement() )


xtr.Read(); // advance to <testcase> tag

24
25
26
27
28
29
30

tag
31

tag

CommonLib.TestCase tc = new CommonLib.TestCase();


tc.id = xtr.GetAttribute("id");
tc.kind = xtr.GetAttribute("kind");
xtr.Read(); // advance to <inputs> tag
xtr.Read(); // advance to <arg1> tag
tc.arg1 = xtr.ReadElementString("arg1"); // consumes the </arg1>
tc.arg2 = xtr.ReadElementString("arg2"); // consumes the </arg2>

32

xtr.Read(); // advance to <expected> tag

33

tc.expected = xtr.ReadElementString("expected"); // consumes

the
34

</expected> tag
// we are now at an </testcase> tag

35

s.items.Add(tc);

36

xtr.Read(); // and now either at <testcase> tag or </suite> tag


37

} // load loop
38
39

xtr.Close();

40

s.Display(); // show the suite of TestCases

41
42
43
44

} // Main()
} // class Class1
} // ns Run

After creating a new C# Console Application Project in Visual Studio .NET, we add a Project
Reference to the CommonLib.dll file that contains definitions
for TestCase and Suite classes. We start by creating a Suite object to hold the XML
data and an XmlTextReader object to parse the XML file.
The key to understanding this technique is to understand
the Read() andReadElementString() methods of XmlTextReader.
To an XmlTextReader object, an XML file is a sequence of nodes. For example,

?
1

<?xml version="1.0" ?>

<foo>

3
4

<bar>99</bar>
</foo>

has 6 nodes: the XML declaration, <foo>, <bar>, 99, </bar>, and </foo>.
The Read() method advances one node at a time. Unlike many Read() methods in
other classes, the System.XmlTextReader.Read() does not return significant
data.

TheReadElementString() method, on the other hand, returns the data between the
begin and end tags of its argument, and advances to the next node after the end tag. Because
XML attributes are not nodes, we have to extract attribute data using
the GetAttribute()method.
Figure 2 shows the output of running this program. You can see that we have successfully parsed
the data from testCases.xml into memory.
Figure 2 Output from the XmlTextReader technique

The statement xtr.WhitespaceHandling


is important because without it you would have to
blank lines.

= WhitespaceHandling.None;
Read() over newline characters and

The main loop control structure that I used is not elegant but is more readable than the
alternatives:

?
1
2
3

while (!xtr.EOF)

//load loop

{
if (xtr.Name == "suite" && !xtr.IsStartElement())
break;

It exits when we are at EOF or an

</suite>

tag.

When marching through the XML file, you can either Read() your way one node at a time
or get a bit more sophisticated with code like the following:

?
1

while (xtr.Name != "testcase" || !xtr.IsStartElement() )


xtr.Read();

// advance to <testcase> tag

The choice of technique you use is purely a matter of style.


Parsing an XML file with XmlTextReader has a traditional, pre-.NET feel. You
walk sequentially through the file using Read(), and extract data
with ReadElementString() andGetAttribute(). Using XmlTextReader is
straightforward and effective and is appropriate when the structure of your XML file is relatively
simple and consistent. Compared to other techniques we will see in this
article, XmlTextReader operates at a lower level of abstraction, meaning it is up to you as
a programmer to keep track of where you are in the XML file andRead() correctly.

Parsing XML with XmlDocument


The second of five ways to parse an XML file is to use the
class. The example code is shown in Listing Four.
Listing Four: Parsing XML using XmlDocument

?
1

using System;

using System.Xml;

using CommonLib;

4
5

namespace Run

class Class1

[STAThread]

10

static void Main(string[] args)

11

12
13

CommonLib.Suite s = new CommonLib.Suite();

XmlDocument

14

XmlDocument xd = new XmlDocument();

15

xd.Load("..\\..\\..\\..\\testCases.xml");

16

XmlNodeList nodelist = xd.SelectNodes("/suite/testcase");

17

// get all <testcase>

nodes

18
19

foreach (XmlNode node in nodelist)

20

// for each <testcase> node

CommonLib.TestCase tc = new CommonLib.TestCase();

21
22
23

tc.id = node.Attributes.GetNamedItem("id").Value;

24

tc.kind = node.Attributes.GetNamedItem("kind").Value;

25
26

XmlNode n = node.SelectSingleNode("inputs");

27

tc.arg1 = n.ChildNodes.Item(0).InnerText;

28

tc.arg2 = n.ChildNodes.Item(1).InnerText;

// get the one <input> node

29

tc.expected = node.ChildNodes.Item(1).InnerText;

30
31

s.items.Add(tc);

32

33

// foreach <testcase> node

34

s.Display();

35
36

37

38

// class Class1

39
40

// Main()

// ns Run

XmlDocument

objects are based on the notion of XML nodes and child


nodes. Instead of sequentially navigating through a file, we select sets of nodes
with
the SelectNodes()method or individual nodes with
the SelectSingleNode() method. Notice that because XML attributes
are not nodes, we must get their data with
an Attributes.GetNamedItem()method applied to a node.
After loading the

XmlDocument, we fetch all the test case nodes at once with:

?
1

XmlNodeList nodelist = xd.SelectNodes("/suite/testcase");

Then we iterate through this list of nodes and fetch each

<input>

node with:

?
1

XmlNode n = node.SelectSingleNode("inputs");

and then extract the

arg1

(and similarly

arg2) value using:

?
1

tc.arg1 = n.ChildNodes.Item(0).InnerText;

In this statement, n is the <inputs> node; ChildNodes.Item(0) is the


first element of<inputs>, i.e., <arg1> and InnerText is the value
between <arg1> and </arg1>.
The output from running this program is shown in Figure 3. Notice it is identical to
the output from running the XmlTextReader technique and, in fact, all the
other techniques presented in this article.
Figure 3 Output from the XmlDocument technique

The XmlDocument class is modeled on the W3C XML Document Object Model
and has a different feel to it than many .NET Framework classes that you are
familiar with. Using theXmlDocument class is appropriate if you need to
extract data in a nonsequential manner, or if you are already
using XmlDocument objects and want to maintain a consistent look and feel
to your application's code.
Let me note that in discussions with my colleagues, there was often some confusion
about the role of the XmlDataDocument class. It is derived from
the XmlDocument class and is intended for use in conjunction
with DataSet objects. So, in this example, you could use
theXmlDataDocument class but would not gain
anything.
Parsing XML with XPathDocument
The third technique to parse an XML file is to use the
class. The example code is shown in Listing Five.
Listing Five: Parsing XML using XPathDocument
1

using System;

using System.Xml.XPath;

using CommonLib;

4
5

namespace Run

XPathDocument

class Class1

[STAThread]

10

static void Main(string[] args)

11

CommonLib.Suite s = new CommonLib.Suite();


12
13
14
15
16
17

XPathDocument xpd = new


XPathDocument("..\\..\\..\\..\\testCases.xml"); XPathNavigator xpn =
xpd.CreateNavigator();
XPathNodeIterator xpi = xpn.Select("/suite/testcase");

18
19
20
21
22

while (xpi.MoveNext())

// each testcase node

{
CommonLib.TestCase tc = new CommonLib.TestCase();
tc.id = xpi.Current.GetAttribute("id", xpn.NamespaceURI);
tc.kind = xpi.Current.GetAttribute("kind", xpn.NamespaceURI);

23
24
25
26
27
28
29
30

XPathNodeIterator tcChild =
xpi.Current.SelectChildren(XPathNodeType.Element);
while (tcChild.MoveNext())

// each part (<inputs> and <expected>) of <testcase>

{
if (tcChild.Current.Name == "inputs")
{
XPathNodeIterator tcSubChild =
tcChild.Current.SelectChildren(XPathNodeType.Element);

31

while (tcSubChild.MoveNext())

32

33

// each part (<arg1>, <arg2>) of <inputs>

if (tcSubChild.Current.Name == "arg1")

34

tc.arg1 = tcSubChild.Current.Value;

35

else if (tcSubChild.Current.Name

36

== "arg2")

tc.arg2 = tcSubChild.Current.Value;

37

38

39

else if (tcChild.Current.Name == "expected")

40

tc.expected = tcChild.Current.Value;

41

s.items.Add(tc);

42
43

44

// each testcase node

45

s.Display();

46
47

48

49

// Main()

// class Class1

50

// ns Run

Using an XPathDocument object to parse XML has a hybrid feel that is part
procedural (as inXmlTextReader) and part functional (as in XmlDocument).
You can select parts of the document using the Select() method of
an XPathNavigator object and also move through the document
using the MoveNext() method of an XPathNodeIterator object.
After loading the XPathDocument object, we get what is in essence a
reference to the first <testcase> node into an XPathNodeIterator object
with:

?
1

XPathNavigator xpn = xpd.CreateNavigator();

XPathNodeIterator xpi = xpn.Select("/suite/testcase");

Because XPathDocument does not maintain "node identity," we must


iterate through each<testcase> node with this loop:

?
1

while (xpi.MoveNext())

Similarly, we have to iterate through the children with:

?
1

while (tcChild.MoveNext())

The XPathDocument class is optimized for XPath data model queries. So using
it is particularly appropriate when the XML file to parse is deeply nested or has a
complex structure. You might also consider using XPathDocument if other
parts of your application code use that class so that you maintain a consistent
coding look and feel.
Parsing XML with XmlSerializer
The fourth technique we will use to parse an XML file is
the XmlSerializer object. The example code is shown in Listing Six.
Listing Six: Parsing XML using XmlSerializer

?
1

using System;

using System.Xml.Serialization;

using System.IO;

using SerializerLib;

5
6

namespace Run

class Class1

// defines a Suite class compatible with testCases.xml

9
10

[STAThread]

11

static void Main(string[] args)

12

{
XmlSerializer xs = new XmlSerializer(typeof(Suite));

13
14

StreamReader sr = new
StreamReader("..\\..\\..\\..\\testCases.xml");

15

SerializerLib.Suite s =
(SerializerLib.Suite)xs.Deserialize(sr);

16
17

sr.Close();

18

s.Display();
}

19

20

// class Class1

// ns Run

Using the XmlSerializer class is significantly different from using any of


the other classes because the in-memory data store is different from the
CommonLib.Suite we used for all other examples. In fact, observe that pulling the
XML data into memory is accomplished in a single statement:

?
1

SerializerLib.Suite s =
(SerializerLib.Suite)xs.Deserialize(sr);

I created a class library named "SerializerLib" to hold the definition for


a Suite class that corresponds to the testCases.xml file so that
the XmlSerializer object can store the XML data into it. The trick, of course,
is to set up this

Suite

class.

Creating the Suite class is done with the help of the xsd.exe command-line
tool. You will find it in your Program Files\Microsoft Visual Studio
.NET\FrameworkSDK\bin folder. I used xsd.exe to generate a Suite class
and then modified it slightly by changing some names and adding
aDisplay() method.

The screen shot in Figure 4 shows how I generated the file testCases.cs, which
contains aSuite definition that you can use directly or modify as I did. Listings
Seven and Eight show the classes generated by XSD and my modified classes in the
SerializerLib library.
Figure 4 Generating testCases.cs definitions using XSD

Listing Seven: XSD-generated suite definition

?
// This source code was auto-generated by xsd, Version=1.0.3705.288.

1
2
3

//

using System.Xml.Serialization;

4
5
6

[System.Xml.Serialization.XmlRootAttribute("suite", Namespace="",
IsNullable=false)]
public class suite {

[System.Xml.Serialization.XmlElementAttribute("testcase")]

public suiteTestcase[] Items;

10
11
12

public class suiteTestcase {


public string expected;

13

[System.Xml.Serialization.XmlElementAttribute("inputs")]

14

public suiteTestcaseInputs[] inputs;

15

[System.Xml.Serialization.XmlAttributeAttribute()]

16

public string id;

17

[System.Xml.Serialization.XmlAttributeAttribute()]

18

public string kind;

19

20
21

public class suiteTestcaseInputs {

22

public string arg1;

23

public string arg2;

24

Listing Eight: Modified suite definition

?
1

using System;

using System.Xml.Serialization;

3
4

namespace SerializerLib

[XmlRootAttribute("suite")]

public class Suite

[XmlElementAttribute("testcase")]

10

public TestCase[] items;

11

public void Display()

// changed name from xsd-generated code

// added to xsd-generated code

12

foreach (TestCase tc in items)


13

14
15
16

+ " ");

Console.Write(tc.id + " " + tc.kind + " " + tc.inputs.arg1


Console.WriteLine(tc.inputs.arg2 + " " + tc.expected);

17

18

19

}
20
21

public class TestCase

// changed name from xsd-generated code

22

{
23

[XmlAttributeAttribute()]

24

public string id;

25

[XmlAttributeAttribute()]

26

public string kind;

27

[XmlElementAttribute("inputs")]

28

public Inputs inputs;

29

// change from xsd-generated code: no array

public string expected;

30

31
32

public class Inputs

33

34

public string arg1;

35

public string arg2;

36
37

// changed name from xsd-generated code

}
}

Using the XmlSerializer class gives a very elegant solution to the problem
of parsing an XML file. Compared with the other four techniques in this
article, XmlSerializer operates at the highest level of abstraction, meaning

that the algorithmic details are largely hidden from you. But this gives you less
control over the parsing and lends an air of magic to the process.
Most of the code I write is test automation, and using XmlSerializer is
my default technique for parsing XML. XmlSerializer is most appropriate
for situations not covered by the other four techniques in this article: finegrained control is not required, the application program does not use
other XmlDocument objects, the XML file is not deeply nested, and the
application is not primarily an ADO .NET application (as we will see in our next
example).

How To Create a Virtual Directory in


Internet Information Services (IIS)
Create Virtual Directories in IIS 5.0
1. Click Start, point to Programs, click to select Administrative Tools, and then click Internet
Services Manager.
2. Expand the server name.
3. In the left pane, right-click Default Web Site, point to New, and then click Virtual Directory.
4. In the frst screen of the Virtual Directory Creation Wizard, type an alias, or name, for the virtual
directory (such as MyWebData), and then click Next.
5. In the second screen, click Browse. Locate the content folder that you created to hold the
content. Click Next.
6. In the third screen, click to select Read and Run scripts (such as ASP). Make sure that the
other check boxes are cleared. Click Finish to complete the wizard.
7. For ASP content, you may want to confrm that an application was created. To do this, right-click
the new virtual
directory, and then click Properties.
8. On the Virtual Directory tab, make sure that the virtual directory name is listed in the
Application Name box under Application Settings. If it is not, click Create. Note that the
application name does not have to match
the virtual directory alias.
9. Close the Properties dialog box.

Creating virtual directories and application pools


in IIS 7.5 and 7.0
To create a virtual directory:
1. Open IIS Manager

On Windows 7: Open Start -> Control Panel -> System and Security category -> Administrative

Tools -> Internet Information Services (IIS) Manager.


On Windows Server 2008 or W indows Vista: Open Start -> Control Panel -> System and
Maintenance category -> Administrative Tools ->Internet Information Services (IIS) Manager.
2. Expand local computer -> Sites -> right-click on Default Web Site (or other website if you're
running multiple websites on the same computer) and choose Add Virtual Directory...

An Add Virtual Directory dialog appears.


3. Enter the Virtual Directory Alias. If you want the website to run
as http://localhost/KenticoCMSDemo, enter alias KenticoCMSDemo.
4. Type a path or browse to the physical directory that contains the chosen directory.

5. Click OK.

The system creates a new virtual directory.


6. Right-click the virtual directory and choose Convert to Application.

An Add Application dialog appears.


7.Click Select... and choose the ASP.NET v4.0 application pool from the drop-down menu.

8. Click OK.
The system converts the virtual directory to an application.
Alternatively, you can create an application in one step by right-clicking a web site and
choosing Add Application... and filling the required information in the Add Application dialog as
mentioned above.

Configuring application pools in IIS 7 and IIS 7.5


Application Pools provide you with additional level of website management. They are supported only
by Windows Server 2003/2008/Vista/7. You can configure them in the Internet Information
Services (IIS) Manager under local computer -> Application Pools.

You can check and change the assigned application pool by right-clicking an application under local
computer -> Sites -> Default Web Site (or other web site) and selecting Manage Application ->
Advanced Settings...

You can set the Recycling and other options by right-clicking on an application pool under local
computer -> Application Pools and selecting Advanced Settings....

Recommended Application Pool Configuration

It's highly recommended that you run Kentico in a separate application pool. If you share the pool
with other websites, the system may behave unpredictably.
We do not recommend to run multiple websites in a single pool.
It's recommended that you specify some value in the Recycle worker processes on
the Recycling tab. This value shouldn't be too short (less than60 minutes) or too long (more
than 1440 minutes/1 day). Setting this value ensures that the memory is recycled and the
application is automatically recovered from failures by regular restart. If your website
freezes time to time, you can temporarily set the value to 30 minutes to ensure that the website is
restarted automatically. Short intervals may lead to high server load and slow response since after
each recycling, the application needs to be restarted and data reloaded to the cache.

It's recommended that you do not limit the maximum virtual or used memory. If you need to use
some value, use at least 100 MB. If your website is being restarted too often, it may be caused by
low maximum memory limit. You can check the frequency of application restarts in KenticoEvent log.
The Maximum number of worker processes on the Performance tab must be set to 1. If you set a
higher value, the worker processes will not be synchronized and Kentico website will not work
correctly. This may lead to unexpected caching of content and system objects.
You can configure the user account under which the application runs on the Identity tab. This
information is useful if you need to troubleshoot issues with permissions, such as disk write
permissions.
Kentico does not support Web garden. Therefore, the Maximum number of worker
processes has to be set to 1.

Understanding Session Management


Techniques in ASP.NET

Introduction
In this article we will try to see what are the different ways we can
manage sessions in an ASP.NET application. When should we use
which techniques and what are the pros and cons of using each
technique.

Background
The basic stateless nature of web sites and web applications are
rather very confusing to anyone who is starting with web
development. ASP.NET provides various ways of handling the
states. The basic overview of all the state management techniques
can be found here.
In this article we will specifcally be discussing the Session management
techniques. Session are the server side method of managing the state
of an application i.e. all the web applications' state related info will be
stored on server side if we use this technique. The beneft of having
this technique is that since we are keeping all the state related
information on server, the request and response becomes lightweight.
Also, the chances of someone intercepting or changing this data is also
reduced. But this technique does involve more resource usage on the
server.
The advantages of using Session State are

Better security
Reduced bandwidth
The disadvantages of using Session state are

More resource consumption of server.


Extra code/care if a Web farm is used(we will discuss this shortly)

Let us start looking into how we can use the Session state in our
application and
see how we can confgure it to use various techniques.

Getting to know the Players


Using Session State
ASP.NET allows us to save values using Session state. It is a global
storage mechanism that is accessible from all pages in the Web
application. Session state is stored in the Session key/value dictionary. This
information will be user
specifc i.e. for each user separate dictionary will be created and
no one can access other session information. below is the
Example usage of sessions.
Hide Copy Code
//global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["number"] = 0;
}
// Web forms
Session["number"] = Convert.ToInt32(Session["number"]) + 1;
Label6.Text = Session["number"].ToString();s

Enumerating Session Management Techniques


Before we proceed, let us see what all session management
techniques are present in the ASP.NET framework.

In-Proc.
SQLServer.
StateServer.

How to confgure Sessions


To confgure the session management we need to specify the

settings in the web.confg fle. Typical settings inweb.config looks


like:

Hide Copy Code


<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data
Source=.\SQLEXPRESS;Trusted_Connection=Yes;" cookieless="false"
timeout="100"/>

Let us see what each of these attributes mean.


mod
e

This specifes the type of session management we


want
to use. it could be

InProc,SQLServer,

and

StateServer

If we use StateServer as session management


technique
stateConnectionStringthen this specifies the location of the
server that is handling the session data.
If we use SQLServer as session management
sqlConnectionStr technique
ing
then this specifies the databaseconnectionstring
that will store the session data.

cookiele
ss

This specifes whether we will be using


identify

to

sessions or we want session info appended in


URL. It could be

timeou
t

cookies

true

or

false.

This specifes the time for which the session should


be
active. after this much time of inactivity the
session will expire.

Single server vs Web Farm


Website require a hosting server. If we have a high traffic website then
to improve the performance we might choose to have multiple web
servers. In case we want multiple web servers(Web Farm), We need to
have all the requests handled at a single point i.e. a Load Balancer. The

Load Balancer will accept all the requests and forward it to appropriate

server(based on load on server and some other criteria)

Single server

Setup with a Load Balancer

Note: Why is this relevant will become clear in


some time.

Configuring
Modes
Using
Mode

In-Proc

the

Session

Session

If we are using In-Proc session handling then all the session


information will be stored in the server memory. This is the default
session state in ASP.NET.
This approach works fne as long as we are keeping small session
information. Since the memory location was handled by the ASP.NET

worker thread only it involves a considerable overhead for the


worker thread to manage these. Also, since this is in the memory of
server, chances are that large session information would lead to
more memory usage and thus lowering the performance.

Let us try to visualize this session management technique.

To confgure the In-Proc session management we need to specify


the sessionState element in theweb.confg fle. let us see how to
confgure the in-proc sessions
Hide Copy Code
<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data
Source=.\SQLEXPRESS;Trusted_Connection=Yes;" cookieless="false"
timeout="100"/>

The only relevant options for In_proc session mode in this confguration
elements
are the mode(which specifies that we are using In_proc sessions), the
cookieless(if true, will use to manage sessions otherwise append
session management data in the URL) and timeout(the time after which
the session should expire.
It is advisable to use the In-Proc sessions when we want very small
amount of information in the sessions. Since the session data is
stored in the memory of computer which is directly accessible by
ASP.NET worker thread nothing extra needs to be done.

The problem with In-Proc mode session mode is that if the size of session
data
becomes large then it effects performance. Also, since the session
data is in memory of server the application restart(ASP.NET) will
effectively flush all the data.

In-Proc sessions in Web Farm scenario


As we have discussed above the web farm will have a load balancer
accepting all the requests. It will then forward the request to any
server based on some criteria. Lets try to see a scenario which could
create problems for us if we are using In- Proc sessions.

Problem Scenario

1. The request from Computer1 reaches the load balancer and load balancer
forwards
it to server1.
2. The In-Proc session led the session data created in the server1's
memory.
3. The next request comes from Computer1 and this time load
balancer pushes it to Server2.
4. Since the server1 had this user specific data in its memory server2 will not
be able
to recognize this request leading to failure of our application logic.
So what should we do to tackle this situation. The whole problem was
because each server in our web form was keeping the session data in
their own memory. If we could somehow move this data from each
server memory to a centralized location then we will not face this
problem. And that is where
the SQLServer and stateServercomes to rescue. using these two
approaches we can easily confgure a central repository to store
session data.
Note: There could still be some reasons(explained below) which will
force you to use In-Proc sessions in a Web farm scenario. If this is the
case then the load balancer should be confgured to maintain connection
affnity or sticky sessions so that the requests coming from a particular
client will always be forwarded to the same server so that the session
information can always be found.

Using SQLServer Session Mode


If we use the SqlServer mode of session management then the session
data will be stored in the SqlServer. The beneft of having this scenario
is that the data is stored in a centralized database rather than the
server memory. Let us see how this can be confgured from web.config
Hide Copy Code
<sessionState mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data
Source=.\SQLEXPRESS;Trusted_Connection=Yes;" cookieless="false"
timeout="100"/>

Apart from this the SQLServer also needs to be confgured to store the

session
data. To do that simply typeaspnet_regsql on Visual studio command
prompt and

a confguration wizard will open. Here we can confgure the SqlServer to


cater
the session data. The demo project has sqlexpress in local machine
confgured for this. To run the application, you will have to confgure
the sqlserver on local machine and perhaps change the web.confg of
the website.
Note: I have given cursory step by step guide to configure SqlServer
because I
want to keep this article at conceptual level rather than becoming a
"How
To" guide.
This way the server memory is not affected by the size of session
data. Also, if we have a web farm then we can don't fnd any problem
in using session data as the session data is in a central location. lets
try to visualize this scenario

Using this mode will only involve the overhead of additional database
access to retrieve the session data. But there is one important aspect

to remember when we are planning to use this technique. We need


to send and receive the data to a SqlServer database, which will be a
separate server. To successfully send and

receive the data toSqlServer all the data that is being kept in the Session
has to
be serializable. This sometimes becomes a very big issue when an
application is being ported to web farm from a single server. That is
where the load balancer's connection affnity will come in picture with InProc sessions.

Using StateServer Session Mode


If we use the StateServer mode of session management then the session
data
will be stored in a separate computer(server) and the session data will
be handled by a windows service. The beneft of having this scenario is
that the data is stored in a centralized location i.e. a state server
rather than the individual server memory. Let us see how this can be
configured from web.config
Hide Copy Code
<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>

Apart from this the Server that will be used as state server also needs
to be
confgured to store the session data. To do that simply run the service
named ASP.NET state service to enable the desired Server to cater the
session data. The demo project does the same on local machine
confgured for this. To run the application, you will have to run the
service on local machine and perhaps change the web.config of the
website.
Note: I have given cursory step by step guide to configure state
server on local machine because I want to keep this article at
conceptual level rather than becoming a "How To" guide.
This way the server memory is not affected by the size of session
data. Also, if we have a web farm then we can don't fnd any problem
in using session data as the session data is in a central location. lets
try to visualize this scenario

Using this mode will only involve the overhead of network latency to
retrieve the
session data. But there is one important aspect to remember when we
are planning to use this technique. We need to send and receive the
data to a state server. To successfully send and receive the data to the
state server all the data that is being kept in the Session has to be
serializable. This sometimes becomes a very big issue when an
application is being ported to web farm from a single server. That is
where the load balancer's connection affnity will come in picture with InProc sessions.

Using the code


The test application contains 3 web sites with single page each.
functionality wise all the web sites are doing the same thing but each
of then is using a different session management technique.

To run all three websites the Sqlserver on local machine has to be


confgured to
store session specifc data(details above in the respective category)
and the
ASP.NET state service should be running on local machine. Also,
the connectionstring will have to be modifed accordingly to use the
database on the running computer.
Note: Please refer the web.confg of each website to get the subtle
difference. The application while running will look like:

WHAT IS A WEB.CONFIG FILE?


A web.config file lets you customize the way your site or a specific
directory on your site behaves. For example, if you place a web.config
file in your root directory, it will affect your entire site
(www.coolexample.com). If you place it in a /content directory, it will
only affect that directory (www.coolexample.com/content). However, in
order for a web.config file to register in a specific directory, there must
be a web.config file in the root directory.
web.config files work on our Windows servers.
Using a web.config file, you can control:

Database connection strings.

Error behavior.

Security.

ASP.NET - Configuration
The behavior of an ASP.NET application is affected by different settings in
the configuration files:

machine.config

web.config

The machine.config file contains default and the machine-specific value for
all supported settings. The machine settings are controlled by the system
administrator and applications are generally not given access to this file.

An application however, can override the default values by creating


web.config files in its roots folder. The web.config file is a subset of the
machine.config file.
If the application contains child directories, it can define a web.config file for
each folder. Scope of each configuration file is determined in a hierarchical
top-down manner.
Any web.config file can locally extend, restrict, or override any settings
defined on the upper level.
Visual Studio generates a default web.config file for each project. An
application can execute without a web.config file, however, you cannot
debug an application without a web.config file.
The following figure shows the Solution Explorer for the sample example
used in the web services tutorial:

In this application, there are two web.config files for two projects i.e., the
web service and the web site calling the web service.
The web.config file has the configuration element as the root node.
Information inside this element is grouped into two main areas: the
configuration section-handler declaration area, and the configuration section
settings area.
The following code snippet shows the basic syntax of a configuration file:
<configuration>

<!-- Configuration section-handler declaration area. -->


<configSections>
<section name="section1" type="section1Handler" />

<section name="section2" type="section2Handler" />


</configSections>
<!-- Configuration section settings area. -->

<section1>
<s1Setting1 attribute1="attr1" />
</section1>

<section2>
<s2Setting1 attribute1="attr1" />
</section2>

<system.web>
<authentication mode="Windows" />
</system.web>

</configuration>

Configuration Section Handler declarations


The

configuration

section

handlers

are

contained

within

the

<configSections> tags. Each configuration handler specifies name of a


configuration section, contained within the file, which provides some
configuration data. It has the following basic syntax:
<configSections>
<section />
<sectionGroup />

<remove />
<clear/>
</configSections>

It has the following elements:

Clear - It removes all references to inherited sections and


section groups.

Remove - It removes a reference to an inherited section and


section group.

Section - It defines an association between a configuration


section handler and a configuration element.

Section

group -

It

defines

an

association

between

configuration section handler and a configuration section.

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>

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>

Connection Strings
The connection strings show which database connection strings are
available to the website. For example:
<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=E:\\projects\datacaching\ /
datacaching\App_Data\ASPDotNetStepByStep.mdb"
providerName="System.Data.OleDb" />

<add name="booksConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\ \databinding\App_Data\books.mdb"
providerName="System.Data.OleDb" />
</connectionStrings>

System.Web
Element
The system.web element specifies the root element for the ASP.NET
configuration section and contains configuration elements that configure
ASP.NET Web applications and control how the applications behave.

It holds most of the configuration elements needed to be adjusted in


common applications. The basic syntax for the element is as given:
<system.web>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>

<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</system.web>

The following table provides brief description of some of common sub


elements of the system.web element:

AnonymousIdentification
This is required to identify users who are not authenticated when
authorization is required.

Authentication
It configures the authentication support. The basic syntax is as given:
<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>

Authorization
It configures the authorization support. The basic syntax is as given:
<authorization>
<allow .../>
<deny .../>
</authorization>

Caching
It Configures the cache settings. The basic syntax is as given:
<caching>
<cache>...</cache>
<outputCache>...</outputCache>
<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>
</caching>

CustomErrors
It defines custom error messages. The basic syntax is as given:
<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">
<error. . ./>
</customErrors>

Deployment
It defines configuration settings used for deployment. The basic syntax is as
follows:
<deployment retail="true|false" />

HostingEnvironment
It defines configuration settings for hosting environment. The basic syntax
is as follows:
<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity
It configures the identity of the application. The basic syntax is as given:
<identity impersonate="true|false" userName="domain\username"
password="<secure password>"/>

MachineKey
It configures keys to use for encryption and decryption of Forms
authentication cookie data.
It also allows configuring

a validation key

that performs message

authentication checks on view-state data and forms authentication tickets.


The basic syntax is:
<machineKey validationKey="AutoGenerate,IsolateApps" [String]
decryptionKey="AutoGenerate,IsolateApps" [String]
validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 |
HMACSHA384 | HMACSHA512 | alg:algorithm_name]
decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
/>

Membership
This configures parameters of managing and authenticating user accounts.
The basic syntax is:
<membership defaultProvider="provider name"
userIsOnlineTimeWindow="number of minutes" hashAlgorithmType="SHA1">
<providers>...</providers>
</membership>

Pages
It provides page-specific configurations. The basic syntax is:
<pages asyncTimeout="number" autoEventWireup="[True|False]"
buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]"
compilationMode="[Always|Auto|Never]"
controlRenderingCompatibilityVersion="[3.5|4.0]"
enableEventValidation="[True|False]"
enableSessionState="[True|False|ReadOnly]"
enableViewState="[True|False]"
enableViewStateMac="[True|False]"
maintainScrollPositionOnPostBack="[True|False]"
masterPageFile="file path"
maxPageStateFieldLength="number"
pageBaseType="typename, assembly"
pageParserFilterType="string"
smartNavigation="[True|False]"
styleSheetTheme="string"
theme="string"

userControlBaseType="typename"
validateRequest="[True|False]"
viewStateEncryptionMode="[Always|Auto|Never]" >

<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>

Profile
It configures user profile parameters. The basic syntax is:
<profile enabled="true|false" inherits="fully qualified type reference"
automaticSaveEnabled="true|false" defaultProvider="provider name">

<properties>...</properties>
<providers>...</providers>

</profile>

RoleManager
It configures settings for user roles. The basic syntax is:
<roleManager cacheRolesInCookie="true|false" cookieName="name"
cookiePath="/" cookieProtection="All|Encryption|Validation|None"
cookieRequireSSL="true|false " cookieSlidingExpiration="true|false "
cookieTimeout="number of minutes" createPersistentCookie="true|false"
defaultProvider="provider name" domain="cookie domain">

enabled="true|false"
maxCachedResults="maximum number of role names cached"

<providers>...</providers>
</roleManager>

SecurityPolicy
It configures the security policy. The basic syntax is:
<securityPolicy>
<trustLevel />
</securityPolicy>

UrlMappings
It defines mappings to hide the original URL and provide a more user
friendly URL. The basic syntax is:
<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
</urlMappings>

WebControls
It provides the name of shared location for client scripts. The basic syntax
is:
<webControls clientScriptsLocation="String" />

WebServices
This configures the web services.

Web Services
Tutorial
Web services are open standard (XML, SOAP, HTTP etc.) based Web
applications that interact with other web applications for the purpose of
exchanging data.
Web Services can convert your existing applications into Web-applications.
In this tutorial you will learn what exactly Web Services are and Why and
How to use them.

Audienc
e
This tutorial will be useful for all those readers inclined to learn the basics of
web services and implement them in practice.

Prerequisite
s
This is an elementary tutorial that introduces the concepts of web services.
It does not require the readers to have a prior knowledge of any technology
in particular, however it would certainly make you comfortable if you have a
basic understanding of XML, HTTP, TCP/IP concepts.

What are Web


Services?
Different books and different organizations provide different definitions to
Web Services. Some of them are listed here.

A web service is any piece of software that makes itself available

over the internet and uses a standardized XML messaging


system. XML is used to encode all communications to a web
service. For example, a client invokes a web service by sending
an XML message, then waits for a corresponding XML response.
As all communication is in XML, web services are not tied to any

one operating system or programming language--Java can talk


with Perl; Windows applications can talk with Unix applications.

Web services are self-contained, modular, distributed, dynamic


applications that can be described, published, located, or
invoked over the network to create products, processes, and
supply chains. These applications can be local, distributed, or
web-based. Web services are built on top of open standards
such as TCP/IP, HTTP, Java, HTML, and XML.

Web services are XML-based information exchange systems that


use the Internet for direct application-to-application interaction.
These systems can include programs, objects, messages, or
documents.

A web service is a collection of open protocols and standards


used for exchanging data between applications or systems.
Software applications written in various programming languages
and running on various platforms can use web services to
exchange data over computer networks like the Internet in a
manner similar to inter-process communication on a single
computer. This interoperability (e.g., between Java and Python,
or Windows and Linux applications) is due to the use of open
standards.

To summarize, a complete web service is, therefore, any service that:

Is available over the Internet or private (intranet) networks

Uses a standardized XML messaging system

Is not tied to any one operating system or programming


language

Is self-describing via a common XML grammar

Is discoverable via a simple find mechanism

Components
Services

of

Web

The basic web services platform is XML + HTTP. All the standard web
services work using the following components

SOAP (Simple Object Access Protocol)

UDDI (Universal Description, Discovery and Integration)

WSDL (Web Services Description Language)

All
these
Services

components

have

been

discussed

in

the

Web

Architecturechapter.

How Does
Work?

Web

Service

A web service enables communication among various applications by using


open standards such as HTML, XML, WSDL, and SOAP. A web service takes
the help of:

XML to tag the data

SOAP to transfer a message

WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from
your Visual Basic program that runs on Windows.
You can also use C# to build new web services on Windows that can be

invoked from your web application that is based on JavaServer Pages (JSP)
and runs on Linux.

Exampl
e
Consider a simple account-management and order processing system. The
accounting personnel use a client application built with Visual Basic or JSP
to create new accounts and enter new customer orders.
The processing logic for this system is written in Java and resides on a
Solaris machine, which also interacts with a database to store information.
The steps to perform this operation are as follows:

The client program bundles the account registration information


into a SOAP message.

This SOAP message is sent to the web service as the body of an


HTTP POST request.

The web service unpacks the SOAP request and converts it into a
command that the application can understand.

The application processes the information as required and


responds with a new unique account number for that customer.

Next, the web service packages the response into another SOAP
message, which it sends back to the client program in response
to its HTTP request.

The client program unpacks the SOAP message to obtain the


results of the account registration process.

Why Web
Services?
Here are the benefits of using Web Services:

Exposing the Existing Function on the


network
A web service is a unit of managed code that can be remotely invoked using
HTTP, that is, it can be activated using HTTP requests. Web services allows
you to expose the functionality of your existing code over the network.
Once it is exposed on the network, other application can use the
functionality of your program.

Interoperabilit
y
Web services allow various applications to talk to each other and share data
and services among themselves. Other applications can also use the web
services. For example, a VB or .NET application can talk to Java web
services and vice versa. Web services are used to make the application
platform and technology independent.

Standardized
Protocol
Web services use standardized industry standard protocol for the
communication. All the four layers (Service Transport, XML Messaging,
Service Description, and Service Discovery layers) use well-defined
protocols in the web services protocol stack. This standardization of protocol
stack gives the business many advantages such as a wide range of choices,
reduction in the cost due to competition, and increase in the quality.

Low
Cost
Communication

of

Web services use SOAP over HTTP protocol, so you can use your existing
low-cost internet for implementing web services. This solution is much less
costly compared to proprietary solutions like EDI/B2B. Besides SOAP over
HTTP, web services can also be implemented on other reliable transport
mechanisms like FTP.

Web Services - Characteristics

Web services have the following special behavioral characteristics:

XMLBased
Web Services uses XML at data representation and data transportation
layers. Using XML eliminates any networking, operating system, or platform
binding. Web Services based applications are highly interoperable
application at their core level.

Loosely
Coupled
A consumer of a web service is not tied to that web service directly. The
web service interface can change over time without compromising the
client's ability to interact with the service. A tightly coupled system implies
that the client and server logic are closely tied to one another, implying that
if one interface changes, the other must be updated. Adopting a loosely
coupled architecture tends to make software systems more manageable and
allows simpler integration between different systems.

CoarseGrained
Object-oriented technologies such as Java expose their services through
individual methods. An individual method is too fine an operation to provide
any useful capability at a corporate level. Building a Java program from
scratch requires the creation of several fine-grained methods that are then
composed into a coarse-grained service that is consumed by either a client
or another service.
Businesses and the interfaces that they expose should be coarse-grained.
Web services technology provides a natural way of defining coarse-grained
services that access the right amount of business logic.

Ability to be Synchronous or Asynchronous


Synchronicity refers to the binding of the client to the execution of the
service. In synchronous invocations, the client blocks and waits for the
service to complete its operation before continuing. Asynchronous
operations allow a client to invoke a service and then execute other

functions.

Asynchronous clients retrieve their result at a later point in time, while


synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.

Supports
Calls(RPCs)

Remote

Procedure

Web services allow clients to invoke procedures, functions, and methods on


remote objects using an XML-based protocol. Remote procedures expose
input and output parameters that a web service must support.
Component development through Enterprise JavaBeans (EJBs) and .NET
Components has increasingly become a part of architectures and enterprise
deployments over the past couple of years. Both technologies are
distributed and accessible through a variety of RPC mechanisms.
A web service supports RPC by providing services of its own, equivalent to
those of a traditional component, or by translating incoming invocations
into an invocation of an EJB or a .NET component.

Supports
Exchange

Document

One of the key advantages of XML is its generic way of representing not
only data, but also complex documents. These documents can be as simple
as representing a current address, or they can be as complex as
representing an entire book or Request for Quotation (RFQ). Web services
support the transparent exchange of documents to facilitate business
integration.

Web Services - Architecture


There are two ways to view the web service architecture:

The first is to examine the individual roles of each web service


actor.

The second is to examine the emerging web service protocol

stack.

Web
Roles

Service

There are three major roles within the web service architecture:

Service Provider
This is the provider of the web service. The service provider implements the
service and makes it available on the Internet.

Service Requestor
This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML request.

Service Registry
This is a logically centralized directory of services. The registry provides a
central place where developers can publish new services or find existing
ones. It therefore serves as a centralized clearing house for companies and
their services.

Web
Service
Stack

Protocol

A second option for viewing the web service architecture is to examine the
emerging web service protocol stack. The stack is still evolving, but
currently has four main layers.

Service Transport
This layer is responsible for transporting messages between applications.
Currently, this layer includes Hyper Text Transport Protocol (HTTP), Simple
Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and newer
protocols such as Blocks Extensible Exchange Protocol (BEEP).

XML Messaging
This layer is responsible for encoding messages in a common XML format so
that messages can be understood at either end. Currently, this layer
includes XML-RPC and SOAP.

Service Description
This layer is responsible for describing the public interface to a specific web
service. Currently, service description is handled via the Web Service
Description Language (WSDL).

Service Discovery
This layer is responsible for centralizing services into a common registry
and providing easy publish/find functionality. Currently, service discovery is
handled via Universal Description, Discovery, and Integration (UDDI).
As web services evolve, additional layers may be added and additional
technologies may be added to each layer.
The next chapter explains the components of web services.

Few
Words
Transport

about

Service

The bottom of the web service protocol stack is service transport. This layer
is responsible for actually transporting XML messages between two
computers.

Hyper Text Transfer Protocol (HTTP)


Currently, HTTP is the most popular option for service transport. HTTP is
simple, stable, and widely deployed. Furthermore, most firewalls allow HTTP
traffic. This allows XML-RPC or SOAP messages to masquerade as HTTP
messages. This is good if you want to integrate remote applications, but it
does raise a number of security concerns.

Blocks Extensible Exchange Protocol (BEEP)


This is a promising alternative to HTTP. BEEP is a new Internet Engineering
Task Force (IETF) framework for building new protocols. BEEP is layered
directly on TCP and includes a number of built-in features, including an
initial handshake protocol, authentication, security, and error handling.
Using BEEP, one can create new protocols for a variety of applications,
including instant messaging, file transfer, content syndication, and network
management.
SOAP is not tied to any specific transport protocol. In fact, you can use
SOAP via HTTP, SMTP, or FTP. One promising idea is therefore to use SOAP
over BEEP.

Web Services Components


Over the past few years, three primary technologies have emerged as
worldwide standards that make up the core of today's web services
technology. These technologies are discussed below.

XML-RPC
This is the simplest XML-based protocol for exchanging information between
computers.

XML-RPC is a simple protocol that uses XML messages to perform


RPCs.

Requests are encoded in XML and sent via HTTP POST.

XML responses are embedded in the body of the HTTP response.

XML-RPC is platform-independent.

XML-RPC allows diverse applications to communicate.

A Java client can speak XML-RPC to a Perl server.

XML-RPC is the easiest way to get started with web services.

To learn more about XML-RPC, visit our XML-RPC Tutorial .

SOAP
SOAP is an XML-based protocol for exchanging information between
computers.

SOAP is a communication protocol.

SOAP is for communication between applications.

SOAP is a format for sending messages.

SOAP is designed to communicate via Internet.

SOAP is platform independent.

SOAP is language independent.

SOAP is simple and extensible.

SOAP allows you to get around firewalls.

SOAP will be developed as a W3C standard.

To learn more about SOAP, visit our SOAP Tutorial.

WSDL
WSDL is an XML-based language for describing web services and how to
access them.

WSDL stands for Web Services Description Language.

WSDL was developed jointly by Microsoft and IBM.

WSDL is an XML based protocol for information exchange in


decentralized and distributed environments.

WSDL is the standard format for describing a web service.

WSDL definition describes how to access a web service and what


operations it will perform.

WSDL is a language for describing how to interface with XMLbased services.

WSDL is an integral part of UDDI, an XML-based worldwide


business registry.

WSDL is the language that UDDI uses.

WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

To learn more about WSDL, visit our WSDL Tutorial.

UDDI
UDDI is an XML-based standard for describing, publishing, and finding web
services.

UDDI

stands

for

Universal

Description,

Discovery,

and

Integration.

UDDI is a specification for a distributed registry of web services.

UDDI is platform independent, open framework.

UDDI can communicate via SOAP, CORBA, and Java RMI


Protocol.

UDDI uses WSDL to describe interfaces to web services.

UDDI is seen with SOAP and WSDL as one of the three


foundation standards of web services.

UDDI is an open industry initiative enabling businesses to


discover each other and define how they interact over the
Internet.

Web Services Examples


Based on the web service architecture, we create the following two
components as a part of web services implementation:

Service
Publisher

Provider

or

This is the provider of the web service. The service provider implements the
service and makes it available on the Internet or intranet.
We will write and publish a simple web service using .NET SDK.

Service
Consumer

Requestor

or

This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML request.
We will also write two web service requestors: one web-based consumer
(ASP.NET application) and another Windows application-based consumer.
Given below is our first web service example which works as a service
provider and exposes two methods (add and SayHello) as the web services
to be used by applications. This is a standard template for a web service.
.NET web services use the .asmx extension. Note that a method exposed as
a

web

service

has

the

WebMethod

attribute.

Save

this

file

as

FirstService.asmx in the IIS virtual directory (as explained in configuring


IIS; for example, c:\MyWebSerces).

FirstService.asmx
<%@ WebService language = "C" class = "FirstService" %>

using System;
using System.Web.Services;
using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")]
public class FirstService : WebService
{
[WebMethod]
public int Add(int a, int b)
{
return a + b;
}

[WebMethod]
public String SayHello()
{
return "Hello World";
}
}

To test a web service, it must be published. A web service can be published


either on an intranet or the Internet. We will publish this web service on IIS
running on a local machine. Let us start with configuring the IIS.

Open Start Settings Control Panel Administrative tools


Internet Services Manager.

Expand and right-click on the default web site; select New


Virtual Directory. The Virtual Directory Creation Wizard opens.
Click Next.

The "Virtual Directory Alias" screen opens. Type the virtual


directory name. For example, MyWebServices. and click Next.

The "Web Site Content Directory" screen opens.

Enter the directory path name for the virtual directory. For
example, c:\MyWebServices Click Next.

The "Access Permission" screen opens. Change the settings as


per your requirements. Let us keep the default settings for this
exercise.

Click the Next button. It completes the IIS configuration.

Click Finish to complete the configuration.

To test whether the IIS has been configured properly, copy an HTML file
(For example, x.html) in the virtual directory (C:\MyWebServices) created
above.

Now,

open

Internet

Explorer

and

type

http://localhost/MyWebServices/x.html. It should open the x.html file.


Note: If it does not work, try replacing the localhost with the IP address of
your machine. If it still does not work, check whether IIS is running; you
may need to reconfigure the IIS and the Virtual Directory.
To test this web service, copy FirstService.asmx in the IIS virtual directory
created above (C:\MyWebServices). Open the web service in Internet
Explorer

(http://localhost/MyWebServices/FirstService.asmx).

It

should

open your web service page. The page should have links to two methods

exposed as web services by our application. Congratulations! You have


written your first web service!

Testing
Service

the

Web

As we have just seen, writing web services is easy in the .NET Framework.
Writing web service consumers is also easy in the .NET framework;
however, it is a bit more involved. As said earlier, we will write two types of
service consumers, one web-based and another Windows application-based
consumer. Let us write our first web service consumer.

Web-Based Service Consumer


Write a web-based consumer as given below. Call it WebApp.aspx. Note
that it is an ASP.NET application. Save this in the virtual directory of the
web service (c:\MyWebServices\WebApp.axpx).
This application has two text fields that are used to get numbers from the
user to be added. It has one button, Execute, that when clicked gets the
Add and SayHello web services.
WebApp.axpx
<%@ Page Language="C#" %>
<script runat="server">
void runSrvice_Click(Object sender, EventArgs e){
FirstService mySvc = new FirstService();
Label1.Text = mySvc.SayHello();
Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
Int32.Parse(txtNum2.Text)).ToString();
}
</script>

<html>
<head> </head>

<body>
<form runat="server">
<p>
<em>First Number to Add </em>:
<asp:TextBox id="txtNum1" runat="server" Width="43px">4<
/asp:TextBox>
</p>

<p>
<em>Second Number To Add </em>:
<asp:TextBox id="txtNum2" runat="server"
Width="44px">5</asp:TextBox>
</p>

<p>
<strong><u>Web Service Result -</u></strong>
</p>

<p>
<em>Hello world Service</em> :
<asp:Label id="Label1" runat="server" FontUnderline="True">Label< /asp:Label>
</p>

<p>
<em>Add Service</em> :
& <asp:Label id="Label2" runat="server" FontUnderline="True">Label</asp:Label>
</p>

<p align="left">
<asp:Button id="runSrvice" onclick="runSrvice_Click"
runat="server" Text="Execute"></asp:Button>
</p>

</form>

</body>
</html>

After the consumer is created, we need to create a proxy for the web
service to be consumed. This work is done automatically by Visual Studio
.NET for us when referencing a web service that has been added. Here are
the steps to be followed:

Create a proxy for the Web Service to be consumed. The proxy is


created using the WSDL utility supplied with the .NET SDK. This
utility extracts information from the Web Service and creates a
proxy. The proxy is valid only for a particular Web Service. If
you need to consume other Web Services, you need to create a
proxy for this service as well. Visual Studio .NET creates a proxy
automatically for you when the Web Service reference is added.
Create a proxy for the Web Service using the WSDL utility

supplied with the .NET SDK. It will create FirstSevice.cs file in


the current directory. We need to

compile it

to create

FirstService.dll (proxy) for the Web Service.

c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL

c:> csc /t:library FirstService.cs

Put the compiled proxy in the bin directory of the virtual directory
of the Web Service (c:\MyWebServices\bin). Internet Information
Services IIS looks for the proxy in this directory.

Create the service consumer, in the same way we already did.


Note that an object of the Web Service proxy is instantiated in
the consumer. This proxy takes care of interacting with the
service.

Type the URL of the consumer in IE to test it (for example,


http://localhost/MyWebServices/WebApp.aspx).

Windows Application-Based Web Service Consumer


Writing a Windows application-based web service consumer is the same as
writing any other Windows application. You only need to create the proxy
(which we have already done) and reference this proxy when compiling the
application. Following is our Windows application that uses the web service.
This application creates a web service object (of course, proxy) and calls
the SayHello, and Add methods on it.

WinApp.cs
using System;
using System.IO;

namespace SvcConsumer {

91

class SvcEater {

public static void Main(String[] args) {


FirstService mySvc = new FirstService();
Console.WriteLine("Calling Hello World Service: " +
mySvc.SayHello());
Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2,
3).ToString());
}
}
}

Compile

it

using c:\>csc

/r:FirstService.dll

WinApp.cs.

It

will

create

WinApp.exe. Run it to test the application and the web service.


Now, the question arises: How can you be sure that this application is
actually calling the web service?
It is simple to test. Stop your Web server so that the Web Service cannot
be contacted. Now, run the WinApp application. It will fire a run-time
exception. Now, start the web server again. It should work.

92

12) Explain briefly XML Web Sevices.


XML Web Services provide a relatively simple technique for accessing a method
on an object that is running on a local or remote computer. Web Services are
based on standardized technologies such as HTTP and XML that are designed to
promote seamless interoperability among different operating systems.

13) Define HTTP and SOAP.

HTTP and SOAPa protocol that codifies how XML is used to package the request and
response data that comprise a Web Service operationare the two cornerstones of Web
Services. Other protocols such as GET and POST are available, but the Simple Object Access
Protocol (SOAP) has fewer limitations and is used in the majority of real-world applications.
14) Explain the Architecture of Web Services and its constituent parts.
The Web Service architecture is a service-oriented architecture that enables applications to be distributed
across a network or the Internet to clients using any language or operating system. As shown in Figure 18-1,
Web Service communications are implemented using existing technology and standards that require no
proprietary vendor support.
11) Defne the terms a) TCP/P, b) HTTP, C) XML, d) SOAP.

TCP/IP (Transmission Control Protocol/Internet Protocol). A communications protocol suite


that forms the basis of the Internet. It's an open system that governs the flow of data between
computers by breaking data into chunks that are easily routed over a network. A Web Service user or
developer rarely has direct contact with this layer.

HTTP (Hypertext Transfer Protocol). Technically, this text-based protocol is a Remote Procedure
Call (RPC) protocol that supports request/response communications. The .NET Framework as well
as most production Web Services use it because it has wide support and generally allows
information to sail unimpeded through firewalls. Both the HTTP POST and HTTP GET methods are
supported in .NET as a way to call a Web Service.

XML (Extended Markup Language). Web Services communication lends data to be serialized
into XML format for storage or transmission. The fact that it is text based makes it easy to work
with. Just about every programming environment supports tools for encoding and decoding XML
formatted data. Its inherent flexibility, extensibility, and validity checking make it attractive to Web
Services that must deal with simple data types such as strings, as well as more complex data
structures. There are currently two XML-based protocols used for delivering Web Services: XMLRPC and SOAP. Because .NET supports SOAP, this chapter focuses on it.

SOAP (Simple Object Access Protocol). SOAP is defined as "a lightweight protocol for exchange
of information in a decentralized, distributed environment." [1] It is not designed specifically for Web
Services, nor restricted to HTTP; but its RPC specifications define a model for invoking methods on
a specified target machine, passing parameters, handling faults, and receiving a method response. .It
is to be noted that XML and SOAP are typically handled transparently by .NET.
Figure 18-1. Web Service transport

93

15) How web service is discovered and used by the consumer?


Discovering and Using a Web Service
To use a Web Service, a client must have a description of how to access the service. This information is
provided by a Web Services Description Language (WSDL) document .
WSDL provides the name of the service, the signature of the method(s) that can be called, the address of
the service (usually a URL), and binding information that describes how the transport operation will
occur. In practical terms, the WSDL information contains the methods that actually call a Web Service.
15) What is UDDI?
Web sites are identified by a domain name and IP address that are maintained by a distributed network
service known as the Domain Name System (DNS). Servers in this network are responsible for controlling
e-mail delivery and translating domain names into IP addresses. The combination of DNS and Web
search engines enables users to quickly locate Web content. However, neither DNS servers nor search
engines provide a formal way of identifying Web Services.
To organize Web Services into a publicly searchable directory, a public consortium (www.uddi.com)
comprising hundreds of companies has defined a standard known as Universal Description Discovery and
Integration (UDDI). This standard defines a SOAP-based interface that can be used to publish a service
or inquire about services in a UDDI-compliant registry. The registry has a business-to-business flavor
about itcontaining information about a company, its services, and interface specifications for any Web
Services it offers. Importantly, there is no single UDDI registry. IBM, SAP, and Microsoft maintain the most
prominent registries.
Figure 18-2. Discovering and accessing a Web Service

The dialog between the client and UDDI registry server is conducted using SOAP messages. Overall, UDDI
defines approximately 40 SOAP messages for inquiry and publishing.
16) List the steps in UDDI Discovery example.
UDDI Discovery Example

94
To demonstrate how to use UDDI, w'e'll look at the SOAP messages sent between client and server as we
seek to discover a Web Service that can provide a stock quote. A Web-based UDDI browser sends and
receives the messages.
Step 1: Send Discovery Request

For our example, we'll search the UDDI registry provided by Microsoft:

http://uddi.microsoft.com/inquire

An inquiry may request business information or tModel information. The former contains information
about a business, including a description of services. The following message requests a list of tModel
keys for companies whose service includes providing a stock quote.

<Envelope>

<Body>

<find_tModel generic="1.0" maxRows="100">

<findQualifiers/>

<name>stock quote</name>

</find_tModel>

</Body>

</Envelope>

Step 2: Registry Service Responds with List of Services Matching Request

A list of tModel keys is returned. These keys are used for the subsequent query:

Step 3: Retrieve Overview Document Containing WSDL

95

The response message includes the OverviewURL element that points to a WSDL document. This
document contains the information needed to create an application to access the service.
17) Explain the steps required for building the web services by hand. Give a
suitable example with code and diagrams.

Building an XML Web Service


Creating a Web Service by Hand
Step-I :The first step is to select or create a virtual directory under IIS that will hold the Web Service
source code file(s). Then, assign it an alias that will be used in its URL. In our example, we will place the
service in the \ws subdirectory.
Step-II :After the directory has been set up, the next step is to use a text editor to create a file in this
directory with the .asmx extension to contain the Web Service code. An example webService which
exposes a method GetdayBorn that accepts three integer parameters that represent the month, day, and
year for birth date. A string value containing the day of the week (Monday, Tuesday, and so on) for this date
is returned.
18) Explain salient features of example web service code.
The code consists of a single class and a method that is invoked by a client to return the day-of-week value.
WebService Directive

The WebService directive identifies the file as defining a Web Service:

<%@ WebService Language="C#" Class="BirthDayWS.BirthDay" %>

The directive specifies the class implementing the XML Web Service and the programming language used
in the implementation. In this example, the directive and the code for the class are present in the
BirthDayWS.asmx file.

This statement would be the only line needed in the .asmx file.
WebMethod Attribute

The WebMethod attribute identifies a method as being accessible to clients making HTTP requests that
is, as an XML Web Service.

[System.Web.Services.WebMethod

96

(Description="Return day of week for a date")]

Testing the Web Service

A quick way to test the newly developed Web Service is to point a browser to its location. For this example,
we enter the address:

http://localhost/ws/BirthDayWS.asmx

19) Explain the steps in building an XML Web Service client.

Building an XML Web Service Client


This section describes how to create a client application that consumes a Web Service. The objective is to
make the client's call to the remote Web method as simple as calling a method in its own code.
Before delving into details, let's first take a high-level view of how a .NET Web Services client interacts
with a Web Service.
The most important thing to observe in Figure 18-6 is that the client does not directly invoke the Web
Service method. Instead, it calls a proxy object that performs this task. The proxy class is created from the
WSDL information provided by the Web Service. The messages exchanged between the proxy and server
are bundled within an HTTP request and transmitted using either the HTTP or the SOAP wire protocol .
Figure 18-6. Overview of how a client accesses a Web Service

20) Explain briefly WSDL.structure


Web Services Description Language (WSDL)
WSDL is broadly defined as "an XML format for describing network services as a set of endpoints
operating on messages containing either document-oriented or procedure-oriented information." [2] In our
case, the endpoints are the client and a Web Service, and WSDL defines how the client interacts with the
service.
The WSDL Structure

97
Specifications for the WSDL grammar define six major elements:
definitions,
types,
message,
port type,
binding,
and service.
Let's discuss these within the context of the WSDL file that describes the sample BirthDayWS Web
Service.
<Definitions>

This is the root element of the WSDL document. It declares multiple namespaces used throughout the
document, and contains all of the other elements:

<definitions xmlns:http="http://schemas.xmlsoap.org/wsdl/http/"
.
>

Namespaces are used to distinguish elements because it is possible that elements from different namespaces
could have the same name .
<Types>

This element contains an XSD (XML Schema Definition Language) schema that describes the data types
publicly exposed by the service: the parameters passed in the Web Service request, and the response:

<types>

<s:schema elementFormDefault="qualified"

</types>

98
<Message>

Defines the data that is exchanged between the Web Service provider and consumer.

<message name="GetDayBornSoapIn">

<part name="parameters" element="s0:GetDayBorn" />

</message>

<PortType>

The <portType> element contains <operation> elements that correspond to the methods in the Web
Service. The <input> and <output> elements define the messages associated with the operation.

<portType name="BirthDaySoap">

<operation name="GetDayBorn">
..
</operation>

</portType>

<Binding>

A set of rules that describe how the <portType> operation is transmitted over the wire. Wire protocols
available are HTTP GET , HTTP POST , and SOAP. This example demonstrates how SOAP is specified.

<binding name="BirthDaySoap" type="s0:BirthDaySoap">


..
<Service>

Identifies the location of the Web Service. Specifically, it lists the name of the Web Service class, the URL,
and references the binding for this endpoint.

99

<service name="BirthDay">

<port name="BirthDaySoap" binding="s0:BirthDaySoap">

<soap:address location=

"http://localhost/ws/BirthDayWs.asmx" />

</port>

</service>

21) Explain in detail SOAP.


Simple Object Access Protocol (SOAP)
SOAP is a platform-neutral protocol for exchanging information. Its cross-platform capabilities are
attributable to its use of XML to define the data being passed and support for HTTP as a communications
protocol. SOAP is the most popular and flexible protocol for the exchange of information between Web
Service consumers and providers. Its format allows it to define complex data structures not supported by the
competing HTTP GET and POST protocols.
A SOAP Request Message

The header for a SOAP request reveals that the SOAP request is packaged as an HTTP POST request to the
server designated by the Host field. The length field specifies the number of characters in the body of
the POST , and SOAPAction indicates the namespace and method to be contacted.

POST /ws/BirthDayWS.asmx HTTP/1.1

Host: localhost

Content-Type: text/xml; charset=utf-8

Content-Length: length

100

SOAPAction: "http://tempuri.org/GetDayBorn"

Listing 18-3 shows the XML template for the SOAP message that is sent to the server.
Listing 18-3. GetdayBorn SOAP Request Content

<?xml version="1.0" encoding="utf-8"?>

<soap:Envelope

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
----------

<soap:Body

soap:encodingStyle=

"http://schemas.xmlsoap.org/soap/encoding/">

<tns:GetDayBorn>
-----------

</soap:Body>

</soap:Envelope>

The overall structure of a SOAP message is not complex. It is an XML document that has a mandatory root
element, <Envelope> , an optional <Header> element, and a mandatory <Body> .

101
A SOAP envelope, as the name implies, is conceptually a container for the message. The SOAP header
represents a way to extend the basic message. The SOAP body contains what one would regard as the
actual data: the arguments sent to the service and the response. The contents of the <Body> element in this
example consist of the method name and its three parameters that correspond to the call made within the
client code:

string dayOfWeek = bd.GetDayBorn(12,20,1963);

A SOAP Response Message

The SOAP body of the response includes a <GetDayBornResult> element

<tns:GetDayBornResponse>

<GetDayBornResult

xsi:type="xsd:string">string</GetDayBornResult>

</tns:GetDayBornResponse>

</soap:Body>

</soap:Envelope>

22) What are the issues of building web services with complex data types.

Using Web Services with Complex Data Types


The BirthDayWS Web Service used throughout this chapter accepts integers as input and returns a string
value. This is useful for introducing Web Service principles because HTTP GET , HTTP POST , and SOAP
all support it. However, Web Services also have the capability of serving up more complex data types such
as data sets, hash tables, images, and custom objects.
Before data can be sent to or from a Web Service, it is serialized using XML serialization. Conversely, it is
deserialized on the receiving end so it can be restored to its original type. Not all data can be serialized.
Thus, when designing a Web Service, it is important to understand restrictions that apply to serialization:

102
23) What are the factors affecting performance of a web service?

Web Services Performance


The performance of a Web Service from both the client and server side is affected by a variety of factors.
Some are .NET related and others are inherent in the technology.
The Nagle Algorithm

One way to improve network efficiency is to reduce the number of small data packets sent across a network.
To accomplish this, the software layer controlling the underlying TCP (Transmission Control Protocol)
connection attempts to accumulate, or buffer, small messages into a larger TCP segment before they are
sent. The technique to do this is based on the Nagle algorithm . [4]
The crux of the algorithm is that small amounts of data should continue to be collected by TCP until it
receives acknowledgment to send the data. .NET institutes a delay of up to 200 milliseconds to collect
additional data for a packet. For a typically small Web Service request, there may be no reason to include
this delay. It's an option you can experiment with.
Working with Large Amounts of Data
Although the XML format offers a great deal of flexibility in representing data, it can place a potentially
large burden on a network because of the large files that can be generated. Moreover, processing XML data
can require extensive memory resources on the client and server.
For large amounts of data, consider these options:

Use FTP or a Web client as described in Section 17.6, "Creating a Web Client with WebRequest and
WebResponse."

Avoid calls as much as possible by caching data rather re-requesting it.

Look at compression techniques such as HTTP transport compression or the SOAP extensions that
can compress part of a Web Service message.

Passing datasets, returning


datasets from web services
Step 1 : Open Visual Studio then select "File" -> "New" -> "Project..." then provide a project
name.

103

I have provided the project name WebServicewithpassingliat.


After adding the project name we will just create a new web service.
Step 2 : Let us add a web service for sending a DataSet and DataTable.
For adding the web service right-click on the solution then select Add > Add New Item then
select Web Service then click the Add button.

104

Step 3 : After adding the web service you will see a WebMethod with the name Helloworld;
just remove it.
And create a new WebMethod of type DataSet and name it MobileDataset() and add another
Web Method of type DataTable and name it MobileDatatable().
For reference see the following image:

105

1. DataSet Code Snippet.

And this Webmethod will return a DataSet.


2. DataTable code snippet.

And this Webmethod will return a DataTable.


Just run your application now.
You will see the same screen that is given below.

106

Now just copy this URL.


http://localhost:2157/Service1.asmx
Step 4 : Let's create another project then it will consume this list.
Open Visual Studio then select "File" -> "New" -> "Project..." then provide a project name.
Here I am using the name WebApplication2.

107

After creating it you will see your solution like the following:

Step 5 : Then just right-click on the solution and select Add Web Reference.

108

After selecting Add Web Reference a new dialog will pop up asking for an address.

Step 6 : Just paste the preceding address that you copied.


http://localhost:2157/Service1.asmx

109

After adding the URL just click the Add Reference button.
Now your solution will look like this.

Now we have completed the adding of the service.


Step 7: Now we just want to use this service.
We have a default page that is created by default.

110

On the page load of that page I have created a couple of methods with the names:
1. GET_DATASET(); // For Getting the Dataset
2. GET_DATATABLE(); // for Getting the DataTable
Code of the default page:
1.

using System;

2.

using System.Collections.Generic;

3.

using System.Linq;

4.

using System.Web;

5.

using System.Web.UI;

6.

using System.Web.UI.WebControls;

7.

using System.Data;

8.

using WebApplication2.localhost;

9.

using System.Text;

10.
11. namespace WebApplication2
12. {
13.

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

14.

15.

protected void Page_Load(object sender, EventArgs e)

16.

17.

GET_DATASET();

18.

GET_DATATABLE();

19.
20.

21.
22.

public void GET_DATATABLE()

23.

24.

localhost.Service1 mo = new WebApplication2.localhost.Service1();

25.

DataTable dt = mo.MobileDatatable();

26.

GridView1.DataSource = dt;

27.

GridView1.DataBind();

28.

111
29.
30.

public void GET_DATASET()

31.

32.

localhost.Service1 mo = new WebApplication2.localhost.Service1();

33.

DataSet ds = mo.MobileDataset();

34.

GridView2.DataSource = ds;

35.

GridView2.DataBind();

36.

37.

38. }

Namespace
1.

using WebApplication2.localhost; // is the namespace for accessing service objects

In this code I have created an object of web service that we have added.
1.

localhost.Service1 mo = new WebApplication2.localhost.Service1();

After creating an object I have passed an object to the DataSet.


1.

localhost.Service1 mo = new WebApplication2.localhost.Service1();

2.

DataSet ds = mo.MobileDataset();

For the DataTable I have created an object. I have passed an object to the DataTable.
1.

localhost.Service1 mo = new WebApplication2.localhost.Service1();

2.

DataTable dt = mo.MobileDatatable();

Design of Default page


1.

<html xmlns="http://www.w3.org/1999/xhtml">

2.

<head runat="server">

3.

<title></title>

4.

</head>

5.

<body>

6.

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

7.

<div>

8.

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

9.

</asp:GridView>

10.

<br />

112
11.

<asp:GridView ID="GridView2" runat="server">

12.

</asp:GridView>

13.

</div>

14.

</form>

15. </body>
16. </html>

I have only added 2 GridViews for displaying data of both the DataTable and DataSet.
After doing that, just run the application and check it.
Here is the output:

Вам также может понравиться