Showing posts with label XML. Show all posts
Showing posts with label XML. Show all posts

XML Documentation in .Net

Posted by Techie Cocktail | 1:09 AM | , | 0 comments »

Introduction

Code documentation is important to be followed as the standard practise. Obviously its not an interesting job to the code developers, for many reasons and also because of laziness issues. It again depends on the importance of documentation. Lets forget these documentation talks. But bottomline, it is really important for future reference purpose. You will believe one day and some of you already believe that.

Most of the devlepers follow the basic comenting. But if you really want to follow the authentic professional method, .net has it all. The line or block of code is generally commented using //(double forward slash - single line), or /* */ (within slash, asterik block - multiple lines).

But if you want to distribute your code or class libraries to your clients, its very helpful if you submit thorough documentation file along with it for reference purpose.

XML comment tags used for documentation

Lets get into the actuals now. If you type /// (3 slashes) in the source code unit, you will see an XML block that gets auto-generated for you. This is the comment block in xml format. The basic comment tags that show up depends upon where you have put the slashes. If it is above the function block, you will see the below segment,

Sample with default tags


/// <summary>
///
/// </summary>
/// <param name="number1"></param>
/// <param name="number2"></param>
/// <returns></returns>
static int addTwoNumbers(int number1, int number2)
{
}

As seen above, we have <summary>, <param>, <returns> tags added automatically. The <summary> tag is used to provide the summary details on what the method does. The <param> tags are included, to write details on the parameters being passed to the method. And the <returns> is included for details on the return type and/or value from the method.

Note, these xml tags must conform the xml rules otherwise you will get warnings and also you final xml documentation file would not contain the errorneous tags until you fix them.

Lets see other commonly used xml tags available for comments as below:

1. <remarks> - Used to provide detailed information about a type or member.
2. <paramref> - Used to create a reference to a parameter.
3. <see cref="" /> - Used to create a reference to any type or a memeber.
4. <exception cref="" /> - Used to create details on exceptions.
5. <c> or <code> - <c> is Used to demonstrate a
small code segment whereas <code> tag is used to demonstrate multi-lines code segment.
6. <example> - used to demonstrate code examples. Usually the <c> and <code> tags are contained withing <example> tag.

Once these tags are in place in the code, follow these 2 steps and C# compiler will generate the XML Documentation file at the specified location.

a. Check the XML Documentation file checkbox and specify the file location, in the Build tab of the project's properties.
b. Build the application.



Lets see a complete code source example with some of the comments tags as mentioned above. After the source code is the XML Documentation file generated.

Source Code with XML Comments as Code documentation

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace xmlDocumentation
{
class Program
{
/// <summary>
/// This is the entry point method of this project.
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
int number1 = 1;
int number2 = 2;
addTwoNumbers(number1, number2);
}

/// <summary>
///
/// </summary>
/// <param name="number1"></param>
/// <param name="number2"></param>
/// <returns><see cref="int" /></returns>
/// <paramref name="number1">Number 1 is the big number</paramref>
/// <remarks></remarks>
/// <example>
/// <c>Result = number1+number2;</c>
/// </example>
static int addTwoNumbers(int number1, int number2)
{
return number1 + number2;
}
}
}

XMLDocumentation.xml file

<?xml version="1.0"?>
<doc>
<assembly>
<name>xmlDocumentation</name>
</assembly>
<members>
<member name="M:xmlDocumentation.Program.Main(System.String[])">
<summary>
This is the entry point method of this project.
</summary>
<param name="args"></param>
</member>
<member name="M:xmlDocumentation.Program.addTwoNumbers(System.Int32,System.Int32)">
<summary>

</summary>
<param name="number1"></param>
<param name="number2"></param>
<returns><see cref="T:System.Int32"/></returns>
<paramref name="number1">Number 1 is the big number</paramref>
<remarks>This method will add the two numbers being passed as the parameters and returuns the sum of two numbers as the result.</remarks>
<example>
<c>Result = number1+number2;</c>
</example>
</member>
</members>
</doc>

Representation

This article is mainly focussed on getting you familiarized with the available xml tags that can be used to document your code and generate xml documentation file.

Once your xml documentation .xml file is ready, you need to present it in a common man readable format. Some of the available tools that can be used to convert the xml document are stated below. We suggest you to explore them and use based on your liking and requirements.

a. XSL -
You can develop your own XSL stylesheet to decorate the above .xml comment file.

b. NDoc -
This is an extensible code documentation generation tool for .NET Developers. It is completely free to download and use. It converts the .xml file as above and coverts it into .chm file. It is very easy to use. You can find the download link at: http://sourceforge.net/projects/ndoc/

c. Sandcastle -
Sandcastle is provided by Microsoft. It produces accurate, MSDN Style, comprehensive documentation and is also easy to use. This tool is available for download at: http://www.microsoft.com/downloads/details.aspx?FamilyId=E82EA71D-DA89-42EE-A715-696E3A4873B2&displaylang=en

d. DOxygen -
Another souce code documentation generator tool. It is developed under Linux and Mac OS x but highly portable. It supports many output format but the popular one is HTML that is widely accepted. This tool is also easy and available for free at: http://www.stack.nl/~dimitri/doxygen/download.html#latestsrc

These are some of the common available options. There may be other tools available or may come in future.

Hope you start documenting your code after knowing the available easy and neat options to generate professional documentation. Keep patience and have fun.

Add/Remove nodes or elements to an XML Document

Posted by Techie Cocktail | 11:12 PM | , | 4 comments »

In the article, Update nodes and attributes in Xml document, we saw how to update an element or an attribute value in an Xml Document. It requires you to have a pointer to the node or attribute to update before you can update its value.

Lets say you want to add a new node section to an existing Xml document. For example lets take the same Xml file as used in the earlier article. It contains list of books, each having its name, author and price values. Say you want to add a new book & its details to the existing list of books.

Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
</books>

To add a new node, you don't require to have any pointer using XPath. XMLDocument, XMLElement and its properties and method does it all. We will first see how to add a new book section. After that we will remove the first one using C#.

Add a new node


static void Main(string[] args)
{
string fileName = @"d:\books.xml";

XmlTextReader _xmlTextReader = new XmlTextReader(fileName);
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);

//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();

addNode(fileName, _xmlDocument);
}

static void addNode(string fileName, XmlDocument xmlDoc)
{
XmlElement bookElement = xmlDoc.CreateElement("book");
bookElement.SetAttribute("name", "DotNet Made Easy");

XmlElement authorElement = xmlDoc.CreateElement("author");
authorElement.InnerText = "microsoft";
bookElement.AppendChild(authorElement);

XmlElement priceElement = xmlDoc.CreateElement("price");
priceElement.InnerText = "50";
bookElement.AppendChild(priceElement);

xmlDoc.DocumentElement.AppendChild(bookElement);
xmlDoc.Save(fileName);
}

Your Xml file should have new book added and should look like below.

Xml File: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>35</price>
</book>
<book name="DotNet Made Easy">
<author>microsoft</author>
<price>50</price>
</book>
</books>

Remove a node
Now lets remove the book - 'asp.net' from the list. The deleteNode() method below will remove the book node whose name="asp.net". Using XPath query we create a pointer to the node that needs to be removed. As book is the child node of the books (root element), RemoveChild() helps to remove the book (child node) from the books (root element).

static void deleteNode(string fileName, XmlDocument xmlDoc)
{
XmlElement _xmlElement = xmlDoc.DocumentElement;

XmlNode _xmlNode = _xmlElement.SelectSingleNode("book[@name='asp']");
_xmlElement.RemoveChild(_xmlNode);
xmlDoc.Save(fileName);
}


As seen from these examples it has become easy to perform almost every Xml task with the use of XML classes in .Net. Happy Coding!

Update nodes and attributes in a Xml document

Posted by Techie Cocktail | 11:09 PM | , | 5 comments »

Introduction
Xml is widely used in application systems to store and receive data, feeds or for some configuration details. There may be times when you need to update some node or element value or update an attribute value. In this article how you can update node or attributes values in an Xml document.

Approach
To update the value of a node or an attribute, you need to first create a pointer or a reference to that node containing the element or attribute that requires an update using XPath query. And once you get the pointer to that node, you can access the node or the attribute and set its value to the new value.

Example
Lets take a sample Xml file and try to update one of the elements and attributes value using C#.

Xml file: books.xml
<?xml version="1.0"?>
<books>
<book name="asp.net">
<author>John</author>
<price>40</price>
</book>
</books>

Lets see how to update an element and an attribute value as in the below sections. In C# the XML Classes can be found in System.Xml namespace.

Updating an element's value
Lets say you need to update the price of the book named asp.net, as in the above Xml document, to a promotional rate from 40 to 35. The below example shows it.


static void Main(string[] args)
{
string fileName = @"d:\books.xml";

//read the Xml file
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);

//load the Xml file into the XmlDocument object
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);

//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();

//update the element (price of the book - asp.net)
updateElement(fileName, _xmlDocument);
}

static void updateElement(string fileName, XmlDocument xmlDoc)
{
//get the root element of the document
XmlElement rootElement = xmlDoc.DocumentElement;

//create a pointer/reference to the price node for the book named 'asp.net'
XmlNode priceNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']/price");
priceNode.InnerText = "35";

//save the Xml
xmlDoc.Save(fileName);
}

In the above example, as in the UpdateElement() method, first the pointer is created to the price node of the book named 'asp.net'. Using that pointer its value is updated by accessing its InnerText (get/set) property.

Updating an attribute's value
Lets say the book name has been changed from 'asp.net' to 'Asp.Net Made Easy'. Lets see how to update the name attribute to the new name in the above Xml.

static void Main(string[] args)
{
string fileName = @"d:\books.xml";

//read the Xml file
XmlTextReader _xmlTextReader = new XmlTextReader(fileName);

//load the Xml file into the XmlDocument object
XmlDocument _xmlDocument = new XmlDocument();
_xmlDocument.Load(_xmlTextReader);

//Note: Close the reader object to release the xml file. Else while saving you will get an error that it is
//being used by another process.
_xmlTextReader.Close();

//update the element (book name)
updateAttribute(fileName, _xmlDocument);
}

static void updateAttribute(string fileName, XmlDocument xmlDoc)
{
//get the root element of the document
XmlElement rootElement = xmlDoc.DocumentElement;

//Update the name attribute's value
XmlNode bookNode = rootElement.SelectSingleNode("/books/book[@name='asp.net']");
if (bookNode.Attributes["name"].Value.Equals("asp.net"))
{
bookNode.Attributes["name"].Value = "Asp.Net Made Easy";
}

//save the Xml
xmlDoc.Save(fileName);
}

Validate Xml using Xsd using C#.Net

Posted by Techie Cocktail | 9:54 PM | , | 1 comments »

Say you have an application architecture that reads data from xml file, processes it and further renders or input data to another system. The xml element values should have correct data types, the attributes associated to the elements must have the correct types and should not be empty and so on. There can definitely be inconsistencies in the data.

You must ensure that the xml data that you receive is consistent so as not to break your application or further process invalid data. This article shows how you can validate your xml data source using XSD validation type before further processing it.

The first step is to prepare a schema definition file that sets or define rules for your xml source and based on these rules you can further build your application architecture. This conforms that your application will always receive valid xml data.

Lets see an example,

XML File Source: sites.xml


<?xml version="1.0"?>
<refSites>
<site name="techiecocktail">
<url>http://techiecocktail.blogspot.com</url>
<articles>100</articles>
</site>
<site name="xyz">
<url>http:///xyz.com</url>
<articles>50</articles>
</site>
</refSites>

The schema rules file defined for this xml is as below. You can have your own rules defined as per the requirements.

Schema File: siteSchema.xsd

<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="generic" elementFormDefault="qualified" targetNamespace="generic">
<xsd:element name="refSites">
<xsd:complexType>
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="site">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="url" type="xsd:string">
</xsd:element>
<xsd:element name="articles" type="xsd:int">
</xsd:element>
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
</xsd:sequence>
</xsd:complexType>
</xsd:element>
</xsd:schema>




Now we have our xml source and its rules defined in the xsd file. Lets use this and build our xml validation logic in c# as below.

XML Valiation:

The required classes that you would require are XMLReaderSettings and XMLReader from System.Xml namespace.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Schema;

namespace ValidateXML
{
class Program
{
static void Main(string[] args)
{
string appDir = System.AppDomain.CurrentDomain.BaseDirectory;

try
{
//Read the xml and xsd files
XmlTextReader _xmlTextReader = new XmlTextReader(appDir + @"..\..\sites.xml");
StreamReader _streamReader = new StreamReader(appDir + @"..\..\siteSchema.xsd");

//create schema object by reading the streamReader required by XMLReaderSettings object
XmlSchema _xmlSchema = new XmlSchema();
_xmlSchema = XmlSchema.Read(_streamReader, new ValidationEventHandler(_xmlReaderSettings_ValidationEventHandler));

//create XMLReaderSettings object and define the validation type
XmlReaderSettings _xmlReaderSettings = new XmlReaderSettings();
_xmlReaderSettings.ValidationType = ValidationType.Schema;
_xmlReaderSettings.Schemas.Add(_xmlSchema);

//define the callback eventhandler that will be called when there are validation errors
_xmlReaderSettings.ValidationEventHandler += new ValidationEventHandler(_xmlReaderSettings_ValidationEventHandler);

//create the XMLReader object by passing the XMLTextReader and XMLReaderSettings objects
//and read the complete xml file and validating it using the defined schema.
XmlReader _xmlReader = XmlReader.Create(_xmlTextReader, _xmlReaderSettings);
while (_xmlReader.Read()) ;

}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}

//Callback EventHandler to display error message occured during validation.
static void _xmlReaderSettings_ValidationEventHandler(object sender, ValidationEventArgs e)
{
Console.Write(e.Message);
Console.Read();
}
}
}

Try to change any data in xml file that does not conform the schema rules. For example, in the xml file, if you change the 'articles' value to a string, the validation EventHandler will be called displaying the error details in the console window.

There are other available validation types such as DTD & XDR, schema validation being the most used one.