Home > Articles > Web Services > XML

  • Print
  • + Share This
Like this article? We recommend

Broker Server

The broker server is divided into the following tasks:

  • Listening to orders

  • Accepting the client request

  • Reading the XML file into XML DOM

  • Selecting a command

  • Invoking the action

  • Sending the response to the client and cleaning up

Listening to Orders

The broker server listens to the client order through TCP. It utilizes the TcpListener class for listening and accepting connections from the client. The TcpListener class uses the Bind method to bind to an IP address and port.

string ipAddr = "127.0.0.1";
int port = 12345;
// TASK A: START LISTENING
TcpListener orderListener = new TcpListener(IPAddress.Parse(ipAddr),
                   port);

// start listening to the socket
orderListener.Start();

After creating the object of the TcpListener class, we start listening to the socket by calling the Start() method. The Start() method internally calls the socket's Bind() method to bind to the end point we provided in the constructor.

Accepting the Client Request

The Start() method continues to listen to the port until some client tries to connect. We can use the TcpClient's Pending() method to determine whether there are any pending client requests. If Pending() returns true, some client is trying to connect with the server. In that case, we call the AcceptTcpClient() method to accept a pending connection request; otherwise, we can skip this step and do other tasks instead of blocking the thread.

// accepting client connection
// we take socketAccepted as an instance of TcpClient,
// which is then used to communicate with the client
if (orderListener.Pending())
{
socketAccepted = orderListener.AcceptTcpClient();
.
.
.

Reading the XML File into XML DOM

The next step after establishing a connection with the client is to receive the order file. The order file is transferred as a stream; therefore, to read it back from the client we use the StreamReader's ReadLine() method:

// reading XML from client
StreamReader readerStream =
       new StreamReader(socketAccepted.GetStream());
String xmlFile = readerStream.ReadLine();

The complete XML file is now in the xmlFile string. The XmlDocument's LoadXML() method is then used to read the string into DOM:

// converting string to XML format
XmlDocument orderXml = new XmlDocument();
orderXml.LoadXML(xmlFile);

Selecting a Command

A factory is a common interface through which we can facilitate the creation of objects. It's a single place where the object instantiation services are provided, instead of spanning the system. Whenever you want to add a new type to the system, you just have to edit the code in the factory. This design pattern belongs to the Creational category, which involves the details of object creation, so the code isn't dependent on what types of objects there are and thus doesn't have to be changed if a new type is added to the system.

The key to making a factory method is to build an abstract base class and define a static factory method in it. This static method will serve as the method to create different objects.

The abstract base class used in the sample is as follows:

// the top level abstract class
abstract class Action
{
  public static string StatusMessage;

  public abstract void InvokeAction(XmlDocument xmlDoc);

  public XmlNode getXmlNode(XmlDocument xmlDoc, string strQuery)
  {
   return xmlDoc.SelectSingleNode(strQuery);
  }

  public static Action ActionFactory(string actiontype)
  {
   if (actiontype.Equals("saveinvoice"))
     return new SaveAction();
   else if (actiontype.Equals("mailinvoice"))
     return new MailAction();
   else
     return new SaveAction(); // default action

  }
}

Apart from the static factory method, the class consists of some other methods that are inherited by the child classes. The factory method ActionMethod() takes an argument that allows it to determine the type of the action object to create. Based on the argument, the method returns the appropriate object to the caller. If we want to add another type to the system, we make another class implementing the abstract Action class. The code inside the ActionFactory() method is changed to add another if check, to compare the new type to the argument and subsequently return the new type's object.

Following are the two classes implemented in this example:

// implementation of the SaveAction class
class SaveAction : Action
{

// implementation of the MailAction class
class MailAction : Action
{

Both of these classes implement the Action abstract class.

Invoking the Action

After getting our required object instance through the object factory, we call the InvokeAction() method of the appropriate object. We implemented two different actions in our XML file and in the server: MailAction and SaveAction. The following sections describe both.

MailAction

The MailAction class implements the procedure of sending an email with the order to the specified email address in the XML file. To implement this method, we get the required fields from the XML file, and then use the .NET System.Web.Mail classes to send the email.

The required fields from the XML file are fetched by using XPath. (See w3schools.com for a good XPath tutorial.) XPath allows the application to locate one or more nodes from an XML document. It provides the syntax for performing basic queries on the XML document.

We used the XmlDocument's SelectSingleNode() method to select the node from an XML document using the XPath query. For example, we use the following XPath query to find the to name in the XML file:

"/message/header/to/text()"

The location path can be absolute or relative. An absolute location starts with a slash (/).

The XPath also contains functions to retrieve an element node, text, or attribute. The text() is used to retrieve the node text of the node on which it's called. The path just described returns the text between the <to></to> tags. The code below retrieves the text inside the toName and toEmail text elements:

XmlNode toName = xmlDoc.SelectSingleNode ("/message/header/to/text()");
XmlNode toEmail = xmlDoc.SelectSingleNode ("/message/header/toemail/text()");

To retrieve an attribute, we use the "at" (@) character with the attribute name:

// get invoice number
XmlNode invoiceNumber =
xmlDoc.SelectSingleNode ("/message/body/saveinvoice/invoice/@number");

This code retrieves the number attribute from the invoice tag. The SelectSingleNode() method returns an XmlNode object. The Value property of the XmlNode class returns the value of the node.

After retrieving the required values from the XML document, we transform the XML document into HTML by using the XSL transformation. .NET provides the class XslTransform for transforming XML using an XSL file. (See www.w3schools.com for an XSL tutorial.) The XSL file is shown below:

<?xml version="1.0" encoding="ISO-8859-1"?>
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:template match="/">
<html>
<head>
<title>Order Page</title>
</head>
<body>
<b>To: </b><xsl:value-of select="message/header/to"/> &lt;
<xsl:value-of select="message/header/toemail" />&gt; <br/>
<b>From: </b><xsl:value-of select="message/header/from"/> &lt;
<xsl:value-of select="message/header/fromemail" />&gt; <br/>
<p><b>Invoice No.: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/@number" />
<br/><b>Date: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/@date" /></p>
<h5>Address:</h5>
<b>Name: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/address/name"/>
<br/>
<b>Street: </b> 
<xsl:value-of select="message/body/saveinvoice/invoice/address/street"/>
<br/>
<b>City: </b>
<xsl:value-of select="message/body/saveinvoice/invoice/address/city" />
<br/>
<b>Country: </b>
<xsl:value-of select="message/body/saveinvoice/invoice/address/@country"/>
<br/>
</body>
</html>
</xsl:template>

</xsl:stylesheet>

To transform an XML document using XSL, we first created an object of the XslTransform class and then called its Load method to load the XSL file into the object. The real transformation is performed in another function called Transform(), which takes the XML document and the output stream as parameters. Transform() reads the XML file from the XmlDocument object, applies the transformation, and stores the result in the output stream specified in the last parameter.

After executing the following piece of code, the StringWriter's object has the transformed HTML file:

// transforming the XML file
XslTransform orderXsl = new XslTransform();
orderXsl.Load("order.xsl");

// generating the transformed file and
// reading into TextWriter
StringWriter orderWriter = new StringWriter();
orderXsl.Transform(xmlDoc,null,orderWriter);

The last step in this action is to send the HTML through email to the recipient specified in the XML document. The recipient's name is retrieved using the SelectSingleNode() method of the XmlDocument class.

// Code to send invoice as email
MailMessage msg = new MailMessage();

// specifying the message body as HTML
msg.BodyFormat = MailFormat.Html;

// specifying the message recipient and sender
msg.To = toEmail.Value;
msg.From = fromEmail.Value;

msg.Subject = "Invoice No." + invoiceNumber.Value
        + " from " + toName.Value;
Console.WriteLine(msg.Subject);

string body = orderMessage;

msg.Body = body;

// sending email through SMTP Server
SmtpMail.SmtpServer = "smtp.abc.com";
SmtpMail.Send(msg);

The code above is applied to send email through the SMTP server. The message body and subject are constructed using the MailMessage class in the System.Web.Mail namespace. Because we're sending the email in HTML format, we set the BodyFormat property of the MailMessage class. Similarly, we set the appropriate fields for body, subject, sender, and recipient addresses. After completing the body of the message, the Send() method of the SmtpMail class is used to send the message to the SMTP server.

NOTE

Notice the SMTP server specified in the SMTPServer property, which is used to route email directly to the specified SMTP address. If we don't specify any SMTP address, the Windows SMTP Service is used for sending email.

SaveAction

The SaveAction class implements the saving mechanism. The method saves the XML file on the filesystem. First, the appropriate values required are retrieved from the XML document, using the XPath queries. After that, the Save() method of the XmlDocument class is used to save the document.

// encapsulate invoice into XML
XmlNode invoiceNode = 
    getXmlNode(xmlDoc,"/message/body/saveinvoice/invoice");

XmlNode invoiceNumber =
  getXmlNode(xmlDoc,"message/body/saveinvoice/invoice/@number");

// loading a sub portion of the XML file
XmlDocument invoiceDoc = new XmlDocument();
invoiceDoc.LoadXml(invoiceNode.OuterXml);

// saving the XML DOM to a file
invoiceDoc.Save(invoiceNumber.Value + ".xml");

The XmlDocument's OuterXml property gets the markup representing the current node and all its children. The invoice number is used as the filename.

Sending the Response to the Client and Cleaning Up

After processing the XML document, the last step that's required for the server is to send a response back to the client about the status of the order. The response is created dynamically using the XmlTextWriter class.

The XmlTextWriter class contains methods to create elements, attributes, nodes, and all the other parts in an XML document. The XmlTextWriter constructor requires a stream to which all the output is written. This stream is passed to the XmlTextWriter's object through the constructor. Next, the WriteStartDocument() method is called to create the basic XML tag in memory, and WriteStartElement() and WriteAttributeString() write an element and an attribute, respectively. To create a node with child nodes, we use WriteStartElement(). To define the last node in the tree, we use WriteElementString(). To close the tag, the WriteEndElement() method is called for each opened tag.

// stream XML output to StringWriter
StringWriter xmlResponse = new StringWriter();
// PREPARE RESPONSE XML THROUGH XMLWRITER
XmlTextWriter xWriter = new XmlTextWriter(xmlResponse);

// start the document
xWriter.WriteStartDocument();

// write the root element
xWriter.WriteStartElement("response");

// get the toAddress
XmlNode toName = xmlDoc.SelectSingleNode("/message/header/to/text()");
XmlNode toEmail =
   xmlDoc.SelectSingleNode("/message/header/toemail/text()");

// get the fromAddress
XmlNode fromName =
    xmlDoc.SelectSingleNode("/message/header/from/text()");
XmlNode fromEmail =
   xmlDoc.SelectSingleNode("/message/header/fromemail/text()");

// get the invoice number
XmlNode invoiceNumber =
xmlDoc.SelectSingleNode("/message/body/saveinvoice/invoice/@number");

xWriter.WriteStartElement("invoice");
xWriter.WriteAttributeString("number", invoiceNumber.Value);

xWriter.WriteElementString("toname", toName.Value);
xWriter.WriteElementString("toemail", toEmail.Value);

xWriter.WriteElementString("fromname", fromName.Value);
xWriter.WriteElementString("fromemail", fromEmail.Value);

xWriter.WriteElementString("message", Action.StatusMessage);

xWriter.WriteEndElement();

// close the root element
xWriter.WriteEndElement();

xWriter.Flush();
xWriter.Close();

The XmlTextWriter is flushed after constructing the body. The StringWriter is now ready to be transferred to the client side, using the NetworkStream's Write() method. The Write() method accepts a byte array; therefore, we first convert the string into bytes using the GetBytes() method:

// sending XML file to client
// assume that writerStream is an object of NetworkStream
byte [] dataWrite = Encoding.ASCII.GetBytes(xmlResponse.ToString());
writerStream.Write(dataWrite,0,dataWrite.Length);

After sending the response, the listener socket is stopped and the client socket is closed to finish the server's task and end the application.

  • + Share This
  • 🔖 Save To Your Account