Introduction To XML

What is XML?

  • XML stands for eXtensible Markup Language
  • All of you must have used HTML tags and elements. HTML provides a fixed set of elements and we are bound to use only those elements.
  • XML on the other hand allows us to create our own tags and elements
  • Since we create our own tags they can be descriptive making the document more readable
  • HTML is designed to display your data in a web browser
  • XML is designed to represent your data rather than its display. The display of data is taken care by other means like CSS or XSL or custom applications
  • HTML page or data can be displayed only on web browsers
  • XML data can be used by any application including web browser which understands how to interpret the data
  • Since the data is separated from display, any change in data can be easily incorporated without touching the display mechanism
  • XML originated from SGML – Standard Generalized Markup Language – which provides specifications to create markup languages
  • HTML is also an example of markup language
  • SGML and XML are controlled by World Wide Web Consortium(W3C)
  • XML made its first public appearance in 1996
  • The first official specification of XML was published in 1998

A Simple XML document

Consider following file named myfirstxml.xml which represents a simple XML document. Try to compare it with HTML. XML files are just plain text files having .xml extention

Myfirstxml.xml

<? Xml version=”1.0″ ?>

<!DOCTYPE mylibrary SYSTEM “mylibrary.dtd”>

<catalog>

<book book_no=”100″>

<author>Author 1</author>

<title>Title 1 </title>

<photo src=”photo1.gif” />

</book>

<book book_no=”200″>

<author>Author 2</author>

<title> Title 2</title>

<photo src=”photo2.gif” />

</book>

</catalog>

Common XML Terms

  • Processing instructions

<? Xml version=”1.0″ ?>

They are special instructions and enclosed in a pair of <? And ?>

<?xml version=”1.0″ encoding=”UTF-8″ standalone=”yes”?>

  • Version : specifies xml version used for the document. Currently it should be 1.0
  • Encoding : Optional argument. Specifies character code set used
  • Standalone : Optional argument. Specifies weather the document depends on any other external document or markup. If your document is based on any DTD then set it to “no” .
  • Document Type Declaration

<!DOCTYPE mylibrary SYSTEM “mylibrary.dtd”>

If your XML document is based on some DTD you must declare that DTD name here. The document name “mylibrary” is arbitery and need not be the same as the DTD file name

  • Tag

<author>

Tags are identifiers of a particular instance of data. They are enclosed between a pair of < and >. Generally a set of start tag (<—>) and end tag(<— />) form an element

  • Element

<author></author>

<photo src=”photo1.gif” />

An element is a set of tags. Element generally comprise of a set of start tag and end tag. However some times they can be represented in an alternative way like shown in the second example. Here instead of using a pair of <photo> and </photo> we have used a shortcut <photo — />

  • Attribute

Book_no

They provide some extra information about an element

  • Root

Catalog

Every XML document must have an element at the top of hierarchy called the root element

  • Tree

<catalog>

—-

</catalog>

An XML document can be viewed as an inverted tree with root element at the top and all other elements at various branch levels

  • Node

Catalog

Each point which starts a branch or is at a leaf level is called as a Node

  • Parent

Catalog

Parent elements are the elements having sub elements

  • Child

Book

Child elements are the elements beneath parent elements

Basic Rules of XML Grammar

  • XML is case sensitive. So, all the tag names – start and end – must appear in the same case
    e.g.
    <mytag> is not same as <MYTAG> or <MyTag>
  • All start tags must have corresponding end tags
    e.g
    <mytag>Some Data
    <my_other_tag>Some other data</my_other_tag>
    Above XML is wrong as <mytag> do not have corresponding end tag </mytag>
  • Empty elements must be written in abbreviated form
    e.g.
    <photo src=”mypicture.gif” />
  • All tags must be nested properly
    e.g.
    <mytag>some data
    <my_other_tag>Some other data
    </mytag>
    </my_other_data>
    Above XML is invalid because the nesting of tags is incorrect. The correct nesting would be
    <mytag>some data
    <my_other_tag>Some other data
    </my_other_data>
    </mytag>
  • All attribute values must be enclosed in quotation marks
    e.g.
    <book book_no=100> is invalid. Valid usage would be
    <book book_no=”100″>

What is a DTD ?

  • DTD stands for Document Type Declaration
  • It defines the structure or rules for an XML document which is based on the DTD
  • DTD is written in a special format called Extended Backus-Naur Form(EBNF)

  • Share/Bookmark

How To Change Target Web Service At Runtime

Introduction

While developing clients for web service, we typically add a web reference to the web service by specifying URL of the .asmx file. Adding a web service in VS.NET generates required proxy object. However, it may happen that after adding the web reference the web service is moved to some other location. In such cases the most easy way is to recreate the proxy object. But what if the same thing happens after you deploy your web service client. It would be nice to allow configurable URL so that even if original web service is moved your clients need not be recompiled. In this article we will see how to do just that.

Creating the web service

For our example we will develop a simple web service that has only one method. Following steps will show you how to proceed.

  • Create a new C# web service project in VS.NET.
  • Open the default .asmx file and add following code to it.
using System;
using System.Web.Services;

namespace HelloWorldWS
{
public class CHelloWorld :
System.Web.Services.WebService
{
	[WebMethod]
	public string GetHelloWorld()
	{
		return "Hello World From CHelloWorld";
	}
}
}
  • As shown above this web service class (CHelloWorld) contains a single method called GetHelloWorld() that returns a string.
  • Add another .asmx file to the project.
  • Open the file and modify it as shown below.
using System;
using System.Web.Services;

namespace HelloWorldWS
{
public class CHelloWorldBackup :
System.Web.Services.WebService
{
	[WebMethod]
	public string GetHelloWorld()
	{
		return "Hello World From CHelloWorldBackup";
	}
}
}
  • This class is similar to previous one but its name is CHelloWorldBackup. Also, it returns different string from GetHelloWorld() method so that you can identify the method call
  • Now, that we have both the web services ready compile the project.

creating web service client

Let us build a simple web client for our web service.

  • Create a new ASP.NET web application in VS.NET.
  • The application will have a default web form. Before writing any code we need to add a web reference to our web service. Right click on the references node and select Add web reference. Follow the same procedure as you would have while developing normal web services. Adding  a web reference will generate code for proxy web service object.
  • Place a button on the web form and add following code in the Click event of the button:
private void Button1_Click
(object sender, System.EventArgs e)
{
localhost.CHelloWorld proxy=new localhost.CHelloWorld;
Response.Write(proxy.GetHelloWorld());
}
  • Above code shows how you will normally call a web service. The web reference contains information about the location of the web service.
  • If you move the .asmx file after you deploy this client, it is bound to get an error. To avoid such situation, modify above code as shown below:
private void Button1_Click
(object sender, System.EventArgs e)
{
localhost.CHelloWorld proxy=new localhost.CHelloWorld;
proxy.Url="http://localhost/webserviceurlandtimeout
/HelloWorld.asmx";
Response.Write(proxy.GetHelloWorld());
}
  • In above code we have explicitly set Url property of the proxy class to the required .asmx file. You can easily store this URL in <appSettings> section of web.config file and retrieve it at run time. Now, even if you move your web service, all you need to do is change its URL in the web.config.
  • Following code shows this:
private void Button1_Click(object sender, System.EventArgs e)
{
localhost.CHelloWorld proxy=new localhost.CHelloWorld;
proxy.Url=GetURL();
Response.Write(proxy.GetHelloWorld());
}
public string GetURL()
{
   return ConfigurationSettings.AppSettings["webserviceurl"];
}
  • The web.config looks like this:
<appSettings>
<add
key="webserviceurl"
value="http://localhost/webserviceurlandtimeout
/HelloWorldBackup.asmx" />
</appSettings>    

Note that in order to work above code correctly, both the web service should have exactly same web method signatures.

I hope you must have got some idea about how to change target web service at run time.

Keep Coding!

  • Share/Bookmark

How To Handle Timeouts in Web Services

Introduction

While developing web applications you should also consider factors like network downtime and server crashes. The same applies to developing web services. When you call a method from your client by default it waits infinitely for the response. This means if server hosting the web service is down then you are bound to get error after a long wait. In this article we will how to deal with such timeouts in web services.

Web Service Proxy

Before consuming a web service from .NET clients you will typically create a web service proxy for the web service. The proxy class so generated has a property called Timeout that can be used to set the timeout value for the web service. Following code in C# shows how to set the property:

localhost.Service1 proxy=new localhost.Service1();
proxy.Timeout=2000;

Note that

  • localhost is the namespace of the proxy class.
  • Service1 is the web service under consideration
  • The Timeout property is set to number of milliseconds for which the client will wait for response from the web service. If the web service is unable to respond in that much time an exception will be thrown.
  • If you set the Timeout property to -1 then the web service proxy will wait infinitely for the response to come.

Connecting with a backup web service in case of failure

You can also trap the timeouts and connect with some backup server where the same web service is hosted. Following code shows how:

localhost.Service1 proxy=new localhost.Service1();
proxy.Timeout=2000;
try
{
	proxy.SomeMethod();
}
catch
{
	proxy.Url="http://www.anotherserver.com/service2.asmx";
	proxy.SomeMethod();
}

Here

  • We have created instance of web service proxy as usual
  • We then set time out value to 2000
  • We then put the call to the web method (SomeMethod) in try..catch block
  • If the web method call times out we point the proxy to the backup web service and call the same method

Note that both the web service must be identical.

I hope you must have found the article useful.

  • Share/Bookmark

Introduction to XML Namespaces & Schema

Introduction

Traditionally XML document structures are defined using DTD – Document Type Definition. However DTDs suffer for many limitations like :

  • They are written using a markup called Extended Backus-Naur Form(EBNF) which differs from normal XML. Hence, you must spend some time in learning the new syntax

  • DTDs provide very limited data types

  • DTDs are not extensible

  • DTDs do not provide support for namespaces

These limitations called for a new flexible and extensible specifications. XML Schema is such a specification. It is used to define the structure of XML document. In other words it is a kind of metadata ( data about data). The Schema itself is XML document.

Following are the advantages of XML Schemas :

  • They are written in XML itself

  • They support namespaces i.e. your XML document can be based on one or more schemas

  • Being XML they are easy to write

  • They provide various data types which DTD lack

  • They can be inherited within your XML document

Currently, IE5+ is the only browser providing support to a subset of entire XML Schema specifications (called XML-DR which stands for XML Data Reduced). Note that this is Microsoft’s implementation and not a W3C standard. All the examples presented require IE5+ installed.

What are Namespaces?

Before going into the details of XML schema one should know the meaning of the term Namespace. Many XML books present this concept in rather abstract manner. Here will try to understand the concept using some analogous thing in real programming world.

Consider that you are developing an application which makes use of two third party components, say Component1 and Coponent2( Microsoft gang can assume that the components are VB ActiveX DLLs and Sun gang can assume them to be Java Class Packages . Both the components provide a class with name “MyClass”. Now, you declared a variable x like this :

Dim x as MyClass ———- in VB
MyClass x=new MyClass() ————- in Java

Got the problem? How the compiler  (VB or Java) will come to know that which MyClass instance to create since class with same name exist in both the components? To avoid the problem you will modify the declaration like this :

Dim x as Component1.MyClass ———- in VB
Component1.MyClass x=new Component1.MyClass() ————- in Java

Now the compiler will understand clearly which instance to create because you are using “fully qualified” class names to avoid “name collisions”.

The same thing applies go XML documents as well. What if your XML document is based on multiple schemas and same element name exists in them. How XML parser will come to know about your intention? This where XML Namespaces come into picture.

Namespace is a collection of names which are used in XML documents as element types and attribute names. The collection is uniquely identified by a URI (Uniform Resource Identifier).

Thus in our example Component1 represents one namespace which provides MyClass and Component2 represents another namespace providing its own MyClass.

Note : The analogy  shown above is just to help you understand the general concept of Namespaces.

Using Namespaces

Now, let us see how to use namespaces in our XML documents. To indicate that an element belongs to a namespace you write something like this :

<myelement xmlns=”my_namespace_uri”>

</myelement>

Above statements tell XML parser that the element and all its children belong to namespace my_namespace_uri. Note the use of xmlns attribute. As you might have noticed, assigning your namespace URI directly to xmlns attribute makes that URI default for all the child elements.

But what if I am using two namespaces? In such cases you modify the declaration as follows :

<myelement xmlns:prefix1=”my_namespace1_uri” xmlns:prefix2=”"my_namespace2_uri”>
<prefix1:child1>some data</prefix1:child1>
<prefix2:child2>some data</prefix2:child2>
<prefix2:child1>some data</prefix2:child1>
</myelement>

Now, you are identifying each child explicitly using its fully qualified tag name.

In many cases you will find that though you are using multiple namespaces, only one is being used most of the times. In such cases you can make that namespace default as follows :

<myelement xmlns=”my_namespace1_uri”   xmlns:prefix1=”"my_namespace2_uri”>
<child1>I am from default namespacesome data</child1>
<prefix1:child2>I am from other namespace</prefix1:child2>
</myelement>

Back to XML Schema

Let us consider following XML document :

<?xml version="1.0"?>

<books>
	<book isbn="100">
		<title>Visual Basic</title>
		<author>Author1</author>
	</book>
	<book isbn="101">
		<title>Java</title>
		<author>Author2</author>
	</book>
	<book isbn="102">
		<title>Linux</title>
		<author>Author3</author>
	</book>
</books>   

We want to enforce structural rules such that :

  • All the books element (which is also the root element) contains instances of book element only

  • All the book elements should contain attribute isbn

  • All the book elements should contain sub elements only (no text data)

  • The attribute data type must be integer

  • The child elements of book i.e. title and author must appear in the same sequence i.e. title first then author

Here is a schema which does that. The schema is stored as booksschema.xml

<?xml version="1.0" ?>

<Schema name="booksschema"
xmlns="urn:schemas-microsoft-com:xml-data"
xmlns:dt="urn:schemas-microsoft-com:datatypes" >

<AttributeType name="isbn" dt:type="int" required="yes"/>

<ElementType name="books">
	<element type="book" />
</ElementType>

<ElementType name="book" content="eltOnly" order="seq">
	<attribute type="isbn" />
	<element type="title" />
	<element type="author" />
</ElementType>

<ElementType name="title"></ElementType>
<ElementType name="author"></ElementType>

</Schema> 

Let us dissect it.

  • <Schema name=”booksschema”
    xmlns=”urn:schemas-microsoft-com:xml-data”
    xmlns:dt=”urn:schemas-microsoft-com:datatypes” >
    This line specifies the schema name and Namespaces used. Here, the default namespace is “urn:schemas-microsoft-com:xml-data”. Note that this namespace will work only in IE5+.Every scheme should start with element Schema and must have a name.

  • <AttributeType name=”isbn” dt:type=”int” required=”yes”/>
    This line declares an attribute isbn with data type of integer. The isbn attribute is specified to be mandatory by “required” attribute.

  • <ElementType name=”books”>
    <element type=”book” />
    </ElementType>
    Above block specifies that books element should contain one or more instances of book element

  • <ElementType name=”book” content=”eltOnly” order=”seq”>
    <attribute type=”isbn” />
    <element type=”title” />
    <element type=”author” />
    </ElementType>
    Above block states that book element should contain sub elements only and not PCDATA ( by content attribute). It also specifies that the book element should have isbn attribute and 2 sub elements – title and author. Further using order attribute we enforce that the sub elements should appear in the same sequence

  • <ElementType name=”title”></ElementType>
    <ElementType name=”author”></ElementType>
    Finally, declarations of title and author elements appear. Here, they do not contain sub elements but you can extend them as per your own requirement.

Now we will link this schema with our XML document.

<?xml version="1.0"?>

<books xmlns="x-schema:d:\bipin\xml\booksschema.xml"> 

We modified the definition of root element to include the namespace. The syntax should be as shown only the path will change as per your XML file.

You can test that the document is being validated as per schema by using IE validate XML context menu option. You should have latest MSXML parser installed to enable this feature.

  • Share/Bookmark

Introduction To XSL

XSL is a powerful way to transform XML documents into other formats. This article explains what XSL is and how to use it for common tasks. More emphasis is on transforming XML documents into XHTML documents

What is XSL?

  • XSL stands for eXtensible Style sheet  Language
  • XSL is used to transform XML documents into another formats.
  • For example, XSL can be used to convert one XML document into another XHTML document or even to another XML document
  • XSL style sheets are also XML documents and are stored generally with extension .xsl
  • The general principle behind XSL transformation is – search for a pattern in XML document and apply specified template to it
  • Many times when we say – XSL we are actually referring one of the following things :
    1. XSLT which is nothing but eXtensible Style sheet Language Transformations. These specifications deal with transforming XML to other formats
    2. XPath which is a standard for describing path or address of various XML elements like elements, attributes

How XSL works?

  • The work of transforming XML to other format is done by a piece of software called XSL processor
  • Note that XSL processor is not the same as XML parser.
  • IE 5+ comes with in-built XSL processor. So, you can test your work with IE 5+
  • XSL parser generates one tree from the XML document under consideration. This tree is called as Source Tree
  • It also generates second tree from the XSL style sheet file which you will write.
  • It then applies the rules from the XSL style sheet to the source tree and generates third tree called result tree

What are Patterns?

  • Patterns are nothing but the way various elements from the XML document are arranged.
  • For example pattern “books/book” means a book element who is child of books element
  • Your pattern can contain elements, attributes and some filtering criteria as well like book elements with subject as programming
  • Patterns are expressed using a specification called XPath

What are templates?

  • Templates are like a mould which gets applied to XML elements matching certain criteria.
  • Thus you can create a template which will be applied to book elements and display them in a HTML table

Let’s start !

Now that we know the general idea behind XSL, let us try to implement our knowledge. For working with the examples you will need a XML document called catalog.xml. The document is given below :

<?xml version="1.0"?>
<?xml-stylesheet href="catalog.xsl" type="text/xsl"?>
<catalog>
	<book isbn="100">
		<author>Author 1</author>
		<subject>Title 1</subject>
 	</book>
	<book isbn="200">
		<author>Author 2</author>
		<subject>Title 2</subject>
	</book>
	<book isbn="300">
		<author>Author 3</author>
		<subject>Title 3</subject>
	</book>
</catalog>

We will use this as Source document and see how it can be transformed into XHTML document.

Your First XSL style sheet

Our first example shows details of books from catalog.xml as plain HTML table

<?xml version='1.0'?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/TR/WD-xsl">

<xsl:template match="/">
    <HTML>
      <BODY>
      	<table border="1">
          <xsl:for-each select="catalog">
		<xsl:apply-templates select="book" />
          </xsl:for-each>
         </table>
      </BODY>
    </HTML>
</xsl:template>

<xsl:template match="book">
	<tr>
	<td><xsl:value-of select="author"/></td>
	<td><xsl:value-of select="subject"/></td>
	</tr>
</xsl:template>

Enter above text into your text editor and save the file as catalog.xsl. Before going further just look at the top of our XML document (catalog.xml) and note how our stylesheet ( catalog.xsl) is linked using processing instruction -  <?xml-stylesheet href=”catalog.xsl” type=”text/xsl”?>

Dissecting Our XSL style sheet

  • <?xml version=’1.0′?>
    Our XSL file starts with already familiar processing instruction. This indicates that XSL style sheet in also XML document
  • <xsl:stylesheet xmlns:xsl=”http://www.w3.org/TR/WD-xsl”>
    This line starts the root element of the stylesheet. The namespace used is http://www.w3.org/TR/WD-xsl. Note that in earlier versions of IE this namespace was http://www.w3.org/1999/XSL/Transform . So, check with your browser which one works !
  • <xsl:template match=”/”>
    This line shows the usage of template element of XSL namespace. In plain english this line means – “apply following instructions to element matching given criteria”. In our case the criteria is “/” meaning the template will be applied to root element of the XML document. Note that it is not same as “catalog” element
  • Next few lines are HTML opening tags for creating table
  • <xsl:for-each select=”catalog”>
    Our aim is to display details of all books available in the catalog.xml file. In plain English this line means – “select all the catalog nodes which are under the root element and perform following operations on them”
  • <xsl:apply-templates select=”book” />
    In side the “for-each” we are applying a template which actually displays the book details. This line would mean – “apply a template designed for the book node”
  • <xsl:template match=”book”>
    Finally comes the book template. All the displaying of book details happen inside this template. This template is same as one we saw previously but the only difference is instead of root node we are matching it against book node. This template will be applied to all the book nodes from the XML document.
  • <xsl:value-of select=”author”/>
    Inside the book template we output the values of the author and subject elements using “value-of” XSL element. This simply means – “output the value of author node”. What if my node has child nodes? In such case values of those will also be displayed. Similarly we output the value of subject node.

Accessing attributes

Our previous example is rather incomplete. We have not displayed the ISBN of each book. For doing that we need to access the isbn attribute of book element. Following style sheet adds this functionality:

........please refer previous example...........

<xsl:template match="book">
	<tr>
	<td><xsl:value-of select="@isbn"/></td>
	<td><xsl:value-of select="author"/></td>
	<td><xsl:value-of select="subject"/></td>
	</tr>
</xsl:template>

  • Share/Bookmark

Web Service Authentication Via SOAP Headers

Introduction

While working with web service one of the commonly faced question is – How do I secure my web service? One aspect of security is preventing anonymous access to the web service. This can be done in various ways such as passing user id and password with each web method call. One elegant alternative is to use SOAP headers to pass this authentication information. This code sample shows how to use SOAP headers to pass authentication information to the web service.

About SOAP Headers

Every SOAP message consists of SOAP body and optional header. SOAP header serve similar purpose as familiar HTTP headers such as passing some information. Note that SOAP headers are passed as plain text over the network. This means that if you need strong security measures you may not like to use them without some kind of encryption.

About Sample Source Code

A ZIP file is provided with this article for download. The ZIP contains two VS.NET projects – web service and web service client. The client passes user information such as User ID and Password in the SOAP headers to the web service. The web service then authenticates the user and sends back response accordingly.

  • Share/Bookmark

Windows Authentication with Web Services

Introduction

In the previous article in this series we saw how to use SOAP headers to authenticate a web service. In this article I will show you how you can use windows credentials to authenticate the consumer of your web service. Windows authentication is commonly used in intranet scenarios such as corporate portals.

How it works?

You can enable windows authentication for your web applications using web.config file. You need to set authentication mode to Windows in the <authentication> section. Additionally you need to set <authorization> section to deny anonymous access. Once you set these parameters in the web.config file the windows credentials of client machine (i.e. the machine which is accessing the web service) will be automatically passed to the web service. In side the web service you can then use Context.User.Identity.Name to get the user name of the user. In case client is not logged in to the domain, IE will pop up a dialog box to enter user id and password. Once user enters valid credentials he will be allowed to consume the web service.

Source Code

The sample source code provided contains two VS.NET projects. One is web service project that authenticates the user. The other is web application that consumes the web service.

  • Share/Bookmark

How To Read and Write XML Documents in .NET

Introduction

XML provides platform independent, self-descriptive and very flexible way to represent your data. .NET has harnessed the capabilities of XML in variety of ways. In addition to providing W3C compatible classes .NET also provides additional classes which make XML document  manipulation easy. In this article we will take a look at reading and writing XML documents using .NET specific classes.

XML Parsers

To access the content of an XML document you need to parse the document and reach to the specific parts of it. The software which allows you to do that is called as XML parser.

The parsers are of two types:

  • DOM parsers : These parsers built a tree of XML document in memory and allow navigation to various nodes and attributes.
  • SAX parsers : These parsers process XML document in sequential fashion. They have low memory footprint than DOM parsers.

In MSXML Ver.3, Microsoft has provided both of the parsers for our use. In .NET we have DOM parser matching closely with existing MSXML parser. The SAX parser has undergone some variation but provides similar functionality.

The pre-.NET parser i.e. MSXML provided classes and interfaces closely matching W3C recommendations. .NET also follows the same tradition but adds many easy to use and flexible ways to manipulate XML documents.

XML and .NET

XML related classes are available in System.XML namespace. In this article we will primarily discuss about .NET specific classes for reading and writing XML documents.

To read XML documents System.XML provides a class called XmlTextReader. This class is derived from XmlReader and provides easy access to various parts of XML document. This class can be thought as forward-only and read only cursor.

To write XML documents System.XML provides a class called XmlTextWriter. This class is derived from XmlWriter and allows quick writing of XML documents.

The methods provided by these classes are very easy to use and self explaining as compared to W3C DOM . This is mainly because these classes allow various methods to be called directly on themselves. They provide ‘current node’ for you to manipulate as opposed to W3C DOM classes where you have to track individual nodes. These classes do not require some thing like mydoc.ChildNodes(0).ChildNodes(1)…. to access various attributes or content of the node. (You will see examples of using XmlTextReader and XmlTextWriter in later sections)

Using XmlTextReader Class

Now, we will see how to use XmlTextReader class.

  • First import the System.XML namespace. If you are using Visual Studio.NET then Add Reference to System.Xml.dll

e.g. In VB.NET

Imports System.Xml
  • Create instance of XmlTextReader class and load the XML document.

e.g. In VB.NET

dim reader as XmlTextReader
reader = new XmlTextReader ("c:\xml\books.xml")
  • Start reading the XML document

e.g. In VB.NET

do while (reader.Read())
'do some action here
loop

The Read() method returns true if the node is successfully read else returns false. If node is successfully read, you can use properties and methods on the node to perform tasks like checking node type, access attributes, access content of node etc. You can call these methods directly on reader object.

Following table lists important properties of XmlTextReader class.

Property/Method Description
Read() method This method advances the ‘cursor’ to the next node. Returns true if node is read successfully. You can use this method in a While loop to process the document.
NodeType property This property returns the type of node i.e. Element, text node etc. The type is one from XmlNodeType enumeration.
Name property This property returns name of the current node
Value Property This property returns the content of the node.
ReadString(), Readxxxx()…. These Readxxxx() kind of properties return content of node as a specific data type as opposed to value property.
GetAttribute(“attb_name”) method This method returns string value of given attribute
HasAttributes property This boolean property indicates whether the node has any attributes.

Using XmlTextWriter Class

Now, let us see how to use XmlTextWriter Class.

  • As usual you need to import System.Xml namespace.
  • Specify the file to which XmlTextWriter should write its content

e.g. In VB.NET

dim writer as xmltextwriter
writer=new xmltextwriter("d:\newcatalog.xml",null)

The second argument of the constructor indicates the encoding to be used. The value of null indicates default encoding (ASCII)

Now we can write various parts of XML document into the file. You will be calling various methods on the instance of XmlTextWriter class directly. Following table lists important methods of XmlTextWriter Class.

Property/Method Description
WriteXmlDecl() This method writes XML processing instruction to the document i.e. <?xml version=”1.0″ ?>
WriteStartElement(“start_tag_name”) This method writes start tag of an element to the document
WriteEndElement() This method is called after calling WriteStartElement() and inserts corresponding end tag in the document
WriteAttribute(“attb_name”,”attb_value”) This method is nested with WriteStartElement() and WriteEndElement() methods and writes an attribute to the element
WriteElementString(“tag_name”,”text_in_tag”) This method creates a text only elements
Flush() This method flushes document buffer to disk. It is helpful if your document is too big.
Close() This method closes the XML document stream.

  • Share/Bookmark

How To Create Web Services in .NET

Introduction

Web services  are one of the building blocks of overall .NET architecture. This article explains the basics of ASP.NET web services along with examples.

What are Web Services?

To understand the meaning of term “Web Services” we will take analogous example form COM world. If you are programmer working with Microsoft Technologies, by this time you must have used third party components or at least components developed for your own applications. The COM components you developed provide “services” to your application. For example a component developed for a banking application might be providing services such as loan calculation, interest calculation etc. If you need same business logic at many places such component will be of great use. Components also isolate your business logic from the rest of the application. Web services offer similar functionality. Web services offer “services” over “web”. The communication between your application and web service is via HTTP protocol using SOAP standards (Simple Object Access Protocol).

How web services work?

In simple terms it works as follows :

  • Your application requests a service (or a method) from a Web Service
  • Your request is converted into SOAP format (which is nothing but XML) and routed to web service over web
  • The web service processes your request and sends back the result again in SOAP format

For routing your method calls to actual web service a special proxy (which is nothing  but a dll) is used. Following figure will make it clear :

Following points need to be noted about web services :

  • Web services are written as plain text files with extention .asmx
  • You generate a proxy source code for this .asmx file first into VB or C# source code using a utility provided with .NET (more on that later)
  • You then compile the source code into a DLL file (actual proxy dll) which makes the “Web Service” component
  • You can consume a web service from any type of application that supports HTTP e.g. Console, WinForms and WebForms or even plain old ASP.

Web Service Description Language

Web Service description language or WSDL is nothing but an XML document describing the web service. It is analogous to Interface Definition Language (IDL) or Type Libraries (TLB). It gives details like service method names, their parameter data types, return values etc.

Creating Your First Web Service

In this section we will create a simple web service called GreetingService. This web service will provide various greeting messages. You will need to pass an integer indicating the type of message you want e.g. Diwali Greetings, New Year Greetings etc. Following are the steps involved in creating a web service :

  • Create .asmx file containing source code for the service ( GreetingService.asmx in our case)
  • Convert .asmx file into VB or C# source code file
  • Compile VB or C# source code thus formed to obtain a proxy dll
  • Deploy the resulting DLL to the client applications bin folder

Create GreetingService.asmx file containing source code for the service

<%@ webservice language= "VB" class= "Greetings"%>Imports

System.Web.Services Public

Class Greetings <WebMethod()>Public
	Function GetMsg(id as integer) As String
		Select case id
		case 101
			GetMsg="Happy Diwali"
		case 102
			GetMsg="Happy New Year"
		case else
			GetMsg="Seasons Greetings"
		End Select
	End Function
End Class    

Let us dissect the code

  • Web service files have extention .asmx. In our case we created a file called GreetingService.asmx
  • <%@ webservice language=”VB”%>
    The webservice directive indicates that this is a web service. Language attribute specifies the language used to write the web service. We have used VB in our example. The class attribute specifies the class name which constitutes the web service. One .asmx file can have multiple class files (may be supporting classes). Out of available classes the class specified in the class attribute is considered for creating web service.
  • <WebMethod()>public function GetMsg(id as integer) as string
    This line marks GetMsg() method as “web callable” method using special attribute <WebMethod()>. This method returns the greeting message based on id we pass.

You can add as many web methods you want to the web service. You can also add normal methods i.e. methods without <WebMethod()> attribute. Such methods will not be exposed over web but can be used internal to the web service. You can also have more than one class per ASMX file. Typically, such classes will act as support class for the main class.

Convert .asmx file into VB or C# source code file

Now that we have our web service source code file ready, we need to convert it into VB source code. To do this .NET comes with a utility called WSDL.EXE. Type in the following command at the DOS prompt :

WSDL http://localhost/mywebapp/GreetingService.asmx?wsdl /l:VB /n:GreetingService

Here,

  • http://localhost/mywebapp/GreetingService.asmx?wsdl We need to supply the WSDL of the web service. This can be achieved by appending WSDL to the path of our .asmx file. You can even invoke this URL in browser and view the resulting XML code.
  • /l:VB Specifies that the resulting code should be generated in VB
  • /n:GreetingService Indicates that name for the resulting namespace should be GreetingService

After executing above command you will get a file called Greetings.vb and it contains the source code for the proxy dll. Do not bother much about the code contained in this file since you will not be generally modifying it manually.

Compile VB or C# source code to obtain proxy DLL

Now we will compile the VB source code to get the proxy DLL.

Type in following Command

vbc
/out:GreetingService.dll
/t:library Greetings.vb
/r:system.dll
/r:system.xml.dll
/r:system.web.services.dll

You will get GreetingService.DLL.

Deploy the resulting DLL

In order to use the DLL you created you must copy it in the \bin folder of your web application.
If such folder is already not there you need to create it

Note : Here, we are assuming that we want to consume our web service from a web client developed in ASP.NET

Creating proxy dll using visual studio.nET

VS.NET provides very easy way to create this proxy dll. It almost hides all the complexities of the process. In your project you can simply right click on references and select “Add a web  reference…” . Now select the web service and that’s it ! VS.NET will automatically create a proxy for you and place in your web application’s bin directory.

Testing our service

You can now test the web service you created by using it in an ASP.NET page. You might use following code :

<%@ language="VB"%>
<script runat=server>

public sub showmsg(s as Object,e as EventArgs)
	dim c as GreetingService.Greetings
	c=new GreetingService.Greetings()
	label1.text=c.GetMsg(101)
end sub

</script>

<form runat=server>
<asp:label id=label1 runat=server text="no msg set yet"/>
<asp:button id=btn1 runat=server onclick="showmsg" text="Click" />
</form>    

You can create instances of the web service component just like any other object.

Web services and session state

Just like any ASP.NET application web  services can hold session or application state. However, there are some special things to be done.

  • Your web service class must derive from WebService. Our class used above is not derived from WebService class and hence can not use session state.
  • You need to mark each method that wants to access session state with following attribute :
    <WebMethod(EnableSessionState=true)>
    The EnableSessionState parameter tells the web service that we want to access session state inside the method.

  • Share/Bookmark

How To Use Forms Authentication with Web Services

Introduction

ASP.NET Forms authentication is one of the most flexible way to authenticating users. Typically under such scheme you will have user ids and passwords in some database. You will then present a form to the user that accepts the credentials. Then at server side you check whether the credentials are valid or not. Based on this validation you will display some error or success message. Forms authentication works very well with web forms. Can you use it with web services? With some tricks – Yes. In fact in this article I am going to show how to do just that. Keep reading…

Problems while using Forms Authentication with Web Services

Before understanding the problem in implementing forms authentication with web services, let us first see how forms authentication works in a typical scenarios.

  • User is presented with a web form where he can enter user id and password
  • He enters user id and password and submits the form
  • At server side, you validate the values he entered against values stored in database
  • If the authentication fails you take him to the login page again and display some error message
  • If authentication succeeds you take him to the main page of your application
  • If user tries to access a page without logging in, Forms Authentication is clever enough to redirect him to the login page automatically

As you can see, Forms Authentication greatly depends on a physical login page to accept the user credentials. You can easily provide such page in a web application. But what if you want to use it with web service application? You certainly do not have any user interface for web services. Also, you must be knowing that forms authentication works based on an authentication cookie that is passed to and from with each request made to the application. Your web service is not a part of your web application and maintaining this authentication cookie across requests in a session is problem.

Developing the web service

Now, that we are clear with the problems let us see how to solve them. The first we need to do is to make appropriate changes to web.config to enable forms authentication. The following markup shows this in detail:

  <system.web>
	<authentication mode="Forms">
		<forms name="CookieName"
		loginUrl="service1.asmx"
		protection="All"
		timeout="60" path="/" />
	</authentication>
    <authorization>
        <deny users="?" />
    </authorization>
  </system.web>

Here, we set authentication mode to “Forms” and deny access to anonymous users. Next, we will write three web methods for the web service – Login, GetLoginStatus and Logout. The names are self explanatory and need no explanation. Following code from web service code-behind file shows how the web service looks:

Public Class Service1
    Inherits System.Web.Services.WebService

     _
    Public Function Login(ByVal UserName As String,
    ByVal Password As String) As Boolean
        If UserName.Length > 0 And Password.Length > 0 Then
            FormsAuthentication.SetAuthCookie(UserName, False)
            Return True
        Else
            Return False
        End If
    End Function

     _
    Public Function GetLoginStatus() As String
        If Context.User.Identity.IsAuthenticated = True Then
            Return "Logged In"
        Else
            Return "Not Logged In"
        End If
    End Function

     _
    Public Function Logout()
        If Context.User.Identity.IsAuthenticated = True Then
            FormsAuthentication.SignOut()
        End If
    End Function

Note that in each web method we set EnableSession to True. This allows us to access to the session object. In the Login method we simply call FormsAuthentication.SetAuthCookie() method passing supplied user name. Consumer of this web service must call Login() before calling any other method else he will not be allowed to consume the functionality. The GetLoginStatus() method simply returns whether user is logged into the system or not. If your web service has any other web methods then all such web methods should check Context.User.Identity.IsAuthenticated property before processing the request. The Logout() method calls FormsAuthentication.SignOut() and then onwards user will not be able to consume.

Developing the Web Service Consumer

If you are consuming the web service we developed above from a windows forms application, there are no much issues as there is no concern of ’state less’ programming. However, if you want to consume this web service via ASP.NET web forms then you need to do additional things. We will now develop a client web form that shows how to do that.

We will create a web form that has three buttons – Login, Check Login Status and Logout. The Click event handler of Login button contains following code:

Dim x As New localhost.Service1()
Dim cc As New CookieContainer()
Dim sessioncookie As Cookie
Dim cookiecoll As New CookieCollection()

x.CookieContainer = cc
x.Login("user1", "password1")
cookiecoll = x.CookieContainer.GetCookies
(New Uri("http://localhost"))
Session("sessioncookie") = cookiecoll("CookieName")

Note that you need to import System.Net namespace as classes such as CookieContainer reside within it. Let us see how the code works.

  • We first create an instance of web service proxy class (x)
  • The proxy class has a property called CookieContainer. This property represents the collection of cookies that are to be passed to the web service along with the request.
  • Then we call Login() method
  • Remember that Login() method sets an authentication cookie in the response. This cookie is trapped and stored in a session variable. Note that “CookieName” is the name we used in forms tag.

Once we are logged in, we can call any other web methods. Following is the code inside the Click event of ‘Check Login Status’ button.

Dim x As New localhost.Service1()
Dim cc As New System.Net.CookieContainer()
Dim sessioncookie As New System.Net.Cookie()
x.CookieContainer = cc
sessioncookie = CType(Session("sessioncookie"),
System.Net.Cookie)
If Not sessioncookie Is Nothing Then
	x.CookieContainer.Add(sessioncookie)
End If
Label1.Text = x.GetLoginStatus()

Since the web service decides whether a method call is authenticated or not based on the forms authentication cookie, we add the previously stored cookie with each method call. Then we call the actual web method. This is necessary because we are working in state less environment. The web service proxy class is created and destroyed each time the web form is processed. So, with each request you need to populate its CookieContainer again and again.

The LogOut() method works as follows:

Dim x As New localhost.Service1()
Dim cc As New System.Net.CookieContainer()
Dim sessioncookie As New System.Net.Cookie()
x.CookieContainer = cc
sessioncookie = CType(Session("sessioncookie"),
System.Net.Cookie)
If Not sessioncookie Is Nothing Then
	x.CookieContainer.Add(sessioncookie)
End If
x.Logout()
Session.Remove("sessioncookie")

Here, the code is almost identical to the previous code snippet. However, we call LogOut() method in the end. Once we call LogOut() we also remove the reference variable from the session that points to the authentication cookie. That’s it! You have just developed forms authentication mechanism for web services. I hope you must have enjoyed reading the article. See you soon with some more interesting stuff.

  • Share/Bookmark