Wednesday, August 27, 2008

Reading and Writing XML in C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language. First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.

Introduction to Microsoft .NET XML Namespaces and Classes

Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library. .NET provides five namespace - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes.

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes.

The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example.

The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.

In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList.

Next namespace in Xml series is System.Xml.Schema. It classes to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType.

The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams.

The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document.

The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.

Reading XML Documents

In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line:

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

Or you can use any XML file.

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor.

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on.

List 1 reads a document and displays a node information using these properties.

About Sample Example 1

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output.

Sample Example 1.



using System;

using System.Xml;

namespace ReadXml1

{

class Class1

{

static void Main(string[] args)

{

// Create an isntance of XmlTextReader and call Read method to read the file

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

textReader.Read();

// If the node has value

while (textReader.Read())

{

// Move to fist element

textReader.MoveToElement();

Console.WriteLine("XmlTextReader Properties Test");

Console.WriteLine("===================");

// Read this element's properties and display them on console

Console.WriteLine("Name:" + textReader.Name);

Console.WriteLine("Base URI:" + textReader.BaseURI);

Console.WriteLine("Local Name:" + textReader.LocalName);

Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());

Console.WriteLine("Depth:" + textReader.Depth.ToString());

Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());

Console.WriteLine("Node Type:" + textReader.NodeType.ToString());

Console.WriteLine("Attribute Count:" + textReader.Value.ToString());

}

}

}

}




The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.

List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has.

About Sample Example 2

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.

Sample Example 2.



using System;

using System.Xml;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

int ws = 0;

int pi = 0;

int dc = 0;

int cc = 0;

int ac = 0;

int et = 0;

int el = 0;

int xd = 0;

// Read a document

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

// Read until end of file

while (textReader.Read())

{

XmlNodeType nType = textReader.NodeType;

// If node type us a declaration

if (nType == XmlNodeType.XmlDeclaration)

{

Console.WriteLine("Declaration:" + textReader.Name.ToString());

xd = xd + 1;

}

// if node type is a comment

if (nType == XmlNodeType.Comment)

{

Console.WriteLine("Comment:" + textReader.Name.ToString());

cc = cc + 1;

}

// if node type us an attribute

if (nType == XmlNodeType.Attribute)

{

Console.WriteLine("Attribute:" + textReader.Name.ToString());

ac = ac + 1;

}

// if node type is an element

if (nType == XmlNodeType.Element)

{

Console.WriteLine("Element:" + textReader.Name.ToString());

el = el + 1;

}

// if node type is an entity\

if (nType == XmlNodeType.Entity)

{

Console.WriteLine("Entity:" + textReader.Name.ToString());

et = et + 1;

}

// if node type is a Process Instruction

if (nType == XmlNodeType.Entity)

{

Console.WriteLine("Entity:" + textReader.Name.ToString());

pi = pi + 1;

}

// if node type a document

if (nType == XmlNodeType.DocumentType)

{

Console.WriteLine("Document:" + textReader.Name.ToString());

dc = dc + 1;

}

// if node type is white space

if (nType == XmlNodeType.Whitespace)

{

Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());

ws = ws + 1;

}

}

// Write the summary

Console.WriteLine("Total Comments:" + cc.ToString());

Console.WriteLine("Total Attributes:" + ac.ToString());

Console.WriteLine("Total Elements:" + el.ToString());

Console.WriteLine("Total Entity:" + et.ToString());

Console.WriteLine("Total Process Instructions:" + pi.ToString());

Console.WriteLine("Total Declaration:" + xd.ToString());

Console.WriteLine("Total DocumentType:" + dc.ToString());

Console.WriteLine("Total WhiteSpaces:" + ws.ToString());

}

}

}

Writing XML Documents

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class.

Although, it's not possible to describe all the Writexxx methods here, let's see some of them.

First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.

In my sample example, I create a file myXmlFile.xml in C:\\ root directory.

// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;

After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.


textWriter.WriteStartDocument();
textWriter.WriteEndDocument();
textWriter.Close();

The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it. WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.

WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document.

//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "");

The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter:

After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.

About Sample Example 3

In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items.

Sample Example 3.

using System;

using System.Xml;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// Create a new file in C:\\ dir

XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);

// Opens the document

textWriter.WriteStartDocument();

// Write comments

textWriter.WriteComment("First Comment XmlTextWriter Sample Example");

textWriter.WriteComment("myXmlFile.xml in root dir");

// Write first element

textWriter.WriteStartElement("Student");

textWriter.WriteStartElement("r", "RECORD", "urn:record");

// Write next element

textWriter.WriteStartElement("Name", "");

textWriter.WriteString("Student");

textWriter.WriteEndElement();

// Write one more element

textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");

textWriter.WriteEndElement();

// WriteChars

char[] ch = new char[3];

ch[0] = 'a';

ch[1] = 'r';

ch[2] = 'c';

textWriter.WriteStartElement("Char");

textWriter.WriteChars(ch, 0, ch.Length);

textWriter.WriteEndElement();

// Ends the document.

textWriter.WriteEndDocument();

// close writer

textWriter.Close();

}

}

}




Using XmlDocument

The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article.

Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.

About Sample Example 4

This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file.

Sample Example 4.

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("Tommy
ex
"));
//Save the document to a file.
doc.Save("C:\\std.xml");
You can also use Save method to display contents on console if you pass Console.Out as a
arameter. For example:
doc.Save(Console.Out);

About Sample Example 5

Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console

Sample Example 5.

XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read();
// load reader
doc.Load(reader);
// Display contents on the console
doc.Save(Console.Out);

Writing Data from a database to an XML Document

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document.

The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query.

About Sample Example 6

In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter.

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir.

Sample Example 6.

using System;

using System.Xml;

using System.Data;

using System.Data.OleDb;

namespace ReadingXML2

{

class Class1

{

static void Main(string[] args)

{

// create a connection

OleDbConnection con = new OleDbConnection();

con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";

// create a data adapter

OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);

// create a new dataset

DataSet ds = new DataSet();

// fill dataset

da.Fill(ds, "Customers");

// write dataset contents to an xml file by calling WriteXml method

ds.WriteXml("C:\\OutputXML.xml");

}

}

}


Summary

.NET Framework Library provides a good support to work with XML documents. The XmlReader, XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.

Monday, August 25, 2008

Legal and Logical Explained

After having failed his exam in "Logistics and Organization", a student goes and confronts his lecturer about it.

Student: "Sir, do you really understand anything about the subject?"

Professor: "Surely I must. Otherwise I would not be a professor!"

Student: "Great, well then I would like to ask you a question.

If you can give me the correct answer, I will accept my mark as is and go. If you however do not know the answer, I want you give me an "A" for the exam. "

Professor: "Okay, it's a deal. So what is the question?"

Student: "What is legal, but not logical, logical, but not legal, and neither logical, nor legal?"

Even after some long and hard consideration, the professor cannot give the student an answer, and therefore changes his exam mark into an "A", as agreed.

Afterwards, the professor calls on his best student and asks him the same question.

He immediately answers: "Sir, you are 63 years old and married to a 35 year old woman, which is legal, but not logical. Your wife has a 25 year old lover, which is logical, but not legal. The fact that you have given your wife's lover an "A", although he really should have failed, is neither legal, nor logical."

A very beautiful poem on today's fast life

' WAQT NAHI '

Har khushi Hai Logon Ke Daman Mein,
Par Ek Hansi Ke Liye Waqt Nahi.
Din Raat Daudti Duniya Mein,
Zindagi Ke Liye Hi Waqt Nahi.

Maa Ki Loree Ka Ehsaas To Hai,
Par Maa Ko Maa Kehne Ka Waqt Nahi.
Saare Rishton Ko To Hum Maar Chuke,
Ab Unhe Dafnane Ka Bhi Waqt Nahi.

Saare Naam Mobile Mein Hain,
Par Dosti Ke Lye Waqt Nahi.
Gairon Ki Kya Baat Karen,
Jab Apno Ke Liye Hi Waqt Nahi.

Aankhon Me Hai Neend Badee,
Par Sone Ka Waqt Nahi.
Dil Hai Ghamon Se Bhara Hua,
Par Rone Ka Bhi Waqt Nahi.

Paison ki Daud Me Aise Daude,
Ki Thakne ka Bhi Waqt Nahi.
Paraye Ehsason Ki Kya Kadr Karein,
Jab Apane Sapno Ke Liye Hi Waqt Nahi.

Tu Hi Bata E Zindagi,
Iss Zindagi Ka Kya Hoga,
Ki Har Pal Marne Walon Ko,
Jeene Ke Liye Bhi Waqt Nahi.......

Excerpts from AOL Sermons

What Enhances Your Beauty?



When your mind is not complaining, responsible, courageous, confident and hollow and empty you are inexplicably beautiful. A person who cannot correct or act has no right to complain. And when a person can correct or act, he will never complain. Complaining is a sign of weakness. Complaining is the nature of utter ignorance where one does not know the Self. Complaint takes away the Beauty that is inborn in you. And it shows up more on the one who is on this path.

Worldly mind is a complaining mind; Divine mind is a dancing mind. Just complaining without indicating the solution is irresponsibility. When the solutions are not workable, finding alternative solutions is Courage.
For external beauty, you put on things; for real Beauty, you have to drop all the things. For external beauty you have to have Make-up; for your real Beauty you only have to realize that you are MADE-UP!






The World Belongs to You


Pleasure or pain is an intense sensation in the four to six and half foot body. When we are not caught up in this then we are truly and sincerely able to say, "I belong to you." That is when all the cravings and aversions, desires and doubts fall off—and in a moment the world belongs to you. All your miseries surround the "I, I, I, . . . ", "I want this, I like that, I don't like this . . ." Just let go. The sun rises and sets, the grass grows, the river flows, the moon shines and I am here forever!

How do you feel if someone praises you?
Answer: "Shy, happy, great, embarrassed . . . "

It does something to you, doesn't it? It doesn't do anything to me! When you praise the moon, the mountains, Lake Lucerne, the Black Forest . . .it doesn't do anything to them. They remain the same.
Just like that I am part of nature. If you enjoy praising me, you may do so. In fact, you have no choice! (Laughter)

You can do with me whatever you like. I am there for you. I am your toy! (Laughter)






Dedication and Commitment


Just like you run out of fuel in the car and you have to refill it again and again, in the same way your dedication and commitment runs out in the course of time and it needs constant renewal!
You have to dedicate and rededicate again and again.

Often people take their dedication for granted and then the mind starts demanding or complaining. When dedication is not complete, it leads to grumbling and complaints.

Total dedication brings enormous enthusiasm, zeal, trust, and challenge, and does not leave any room for ego.






The Way Out of Sorrow


If your are unhappy you better check if one or all of these are lacking: Tapa (penance), Vairagya (dispassion), Sharanagati (surrender).
• Tapas is agreeing with the moment, total acceptance of pleasant or unpleasant situations.
• Vairagya means I want nothing and I am nothing.
• Sharanagati is "I am here for You, for Your joy."

If you are grumbling then these are lacking, because when you accept the situation you cannot grumble; when you take it as Tapa you will not grumble; when you come from a state dispassion ("I don't want anything") you don't grumble; and if you are surrendered you will have no complaints.

All these three (Tapas, Vairagya and Sharanagati) purify your mind and uplift you in joy.

If you don't do it willingly you will do it in desperation. First you say, "Nothing can be done." Then in anger and desperation you say, "I give up, I want nothing, I have no choice, to hell with it!"





Every Stone is Precious


A sculptor in a temple uses all types of stones. Certain stones he uses for the foundations. These never appear outside.

From certain stones which are good to carve, the sculptor makes the walls and pillars of the Temple. From other stones he makes the steps. Certain stones become the tower of the Temple.

Only those stones which are extremely suitable for carving will become the Deity and be installed in the Temple. When the stone become a part of the Temple, it no longer remains a stone, it becomes a sculpture, a piece of art, it becomes the Living Deity.

In the same way many people come to the Master. According to the degree of their surrender they are installed by the Master. All are essential.

If there were no steps, how could a person reach the Temple?

If there were no foundation, how could the Temple be there at all?

What can a tower do without pillars?

For a sculptor, each stone is precious and valuable.






Sensitivity and Strength


Those who are sensitive are often weak. Those who feel themselves strong are often insensitive.
There are some who are sensitive to themselves but insensitive to others. There are some who are sensitive to others but not to themselves.

Those who are sensitive to others often end up feeling "Poor me . . ." Those who are sensitive to themselves often feel, "The others are the bad guys." Some conclude it's better not to be sensitive and they shut off, because sensitivity brings pain. But mind you, if you are not sensitive you will lose all the finer things in life too—intuition, love, joy.

This path and this knowledge make you both strong and sensitive. Often people who are insensitive do not recognize their insensitivity. And those are sensitive often do not recognize their strength. Their sensitivity is their strength.

Sensitivity is intuition; sensitivity is compassion; sensitivity is love.

Sensitivity is strength.

Strength is calmness, endurance, silence, nonreactiveness, confidence, faith—and a smile.
Be both sensitive and strong.






The Golden Veil


Craving comes from encouraging the thought of pleasure. The actual experience of pleasure may not be as pleasurable as the memory.

Question: Is that why we spend so much time in our minds?
Whether you encourage a worldly thought or a Divine thought, they both bring you pleasure. Worldly thought leads to indulgence, which brings you down from pleasure to disappointment and dejection. Divine thought takes you up from pleasure to Bliss, Intelligence, and progress in life. Worldly thought brings pleasure only as memory, whereas Divine thought comes as Reality.

Question: What is a Divine thought?
"I am not the body; I am bliss, satchitananda; I am unbounded space; I am love; I am peace; I am light."

Question: What is a worldly thought?
It is about money, sex, food, power, status and self-image.






Be In The Present Moment

"Be in the present moment. If you live fully now, tomorrow will take care of itself. If you are happy now, the past will not torment you. That is the Art of Living."

Using Google as a Hindi to English dictionary

Recently, an employee at a client’s place was trying to understand an article in Hindi. She came across a word मूल्य वर्धित (Mulya Vardhit) in Hindi. She wanted to know its meaning. Me and other people in the room started guessing and arguing, based on the context, in which the term was used. But no one was sure. Leaving others to guess, I did the following:


Went to Google Indic Transliteration at http://www.google.com/transliterate/indic
Typed in Mulya Vardhit (in English) in the text area. It showed me Mulya Vardhit in Hindi (note that this is transliteration and not translation).
Selected Mulya Vardhit in Hindi, right clicked and selected Copy. Basically copied Mulya Vardhit’s text in Hindi.
Note: The above step saved me from typing in Hindi using a Hindi virtual keyword (for example).
Then I went to Google Translate at http://translate.google.com/translate_t
On the tab “Text and Web”, I pasted (CTRL-V) the hindi text into the text area (labelled as “Original Text”).
From the dropdowns, I selected Hindi >> English.
Clicked on Translate.
I popped up and declared to everyone that “Mulya Vardhit” stands for “Value Added”. The person was reading an article about mobile services and the article was talking about some “value added” servcies.
Obviously there may be other, quicker or better ways to Hindi to English. But this is the Google way

Exception Handling Unplugged..!!

What is Exception Handling and why do we need it?

The mark of a good, robust program is planning for the unexpected, and recovering if it does happen. Errors can happen at almost any time during the compilation or execution of a program. We can detect and deal with these errors using Exception Handling. Exception handling is an in built mechanism in .NET framework to detect and handle run time errors. At the heart of the .NET Framework is the Common Language Runtime (CLR) which in addition to acting as a virtual machine and interpreting and executing IL code on the fly, performs numerous other functions such as type safety checking, memory management, garbage collection and Exception handling. The .NET framework contains lots of standard exceptions. It allows you to define how the system reacts in unexpected situations like 'File not found' , 'Out of Memory' , bad logic, non-availability of operating system resources other than memory, 'Index out of bounds' and so on.

When the code which has a problem, is executed, it 'raises an exception'. If a programmer does not provide a mechanism to handle these anomalies, the .NET run time environment provides a default mechanism, which terminates the program execution. This mechanism is a structured exception handling mechanism




Exceptions in C#

Exceptions in C# are represented by objects with type names representative of the type of error that occurred in the program. Exceptions in C# provide a structured, uniform, and type-safe way of handling both system level and application level error conditions. . In C#, all exceptions must be represented by an instance of a class type derived from System.Exception. System.Exception class is the base type of all exceptions.An object of an exception is that which describes the exceptional conditions occuring in a code that means, we are catching an exception, creating an object of it, and then throwing it.

Like other modern and structured programming languages, C# also provides a rich mechanism of Exception Handling. Exceptions are handled in C# using the 'try/catch/finally' statements. These keywords are also named as Structured Exception Handling (SEH). The code which 'may cause an exception' is enclosed within a 'try' block as shown below:

try
{
// this code may cause an exception.
}

Your code feels safe now as it has been protected. If an exception does occurs in the code enclosed within the 'try' block, you can handle it. To handle an exception, attach a 'catch' block to the 'try'.

try
{
// this code may cause an exception.
// If it does cause an exception, the execution will not continue.
// Instead,it will jump to the 'catch' block.
}
catch (Exception ex)
{
// I get executed when an exception occurs in the try block.
// Write the error handling code here.
}

Having understood the basic syntax, let's rewrite the example ShowingExceptions

// Example ShowingExceptions using structured exception handling the C# way.

class ShowingExceptions
{
static void main()
{
Console.Write("Please enter a number :");
string str = Console.ReadLine();
double dNo;
}
try
{
dNo = double.Parse(str);
Console.WriteLine("Parsing successfully without errors");
}
catch(Exception ex)
{
Console.WriteLine("Error : {0} is not a valid number", str);
}

}

Execution :
Please enter a number : Hello

Output:

Error: Hello is not a valid number.

Thus here we notice that when the exception does occur, the program stops executing code from the try block and immediately jumps to the catch block. This is why the output, " Parsing successfully without errors " is not displayed when the exception occurs.

NOTE:

It is not a good idea to display the raw exception message to the user. Instead, show a friendly message to the user and log the actual exception message to some log file for trouble shooting purposes.

Moreover, in the above example, we are handling all types of exceptions. But it is a bad practise to catch all exceptions. You should catch only specific exceptions which are expected in the specific code block. For example, if you are attempting to allocate the memory, you may catch 'System.OutOfMemoryException' and if you are performing mathematical operations, you may catch
'System.DivideByZeroException' exception. Also, you can create and throw custom exceptions.

Eg:



ArgEx ArgumentException = new ArgumentException("You entered bad data");
throw ArgEx;

Ok, But what about the finally block?

C# provides the finally block to enclose a set of statements that need to be executed regardless of the course of control flow. So as a result of normal execution, if the control flow reaches the end of the try block, the statements of the finally block are executed. Moreover, if the control leaves a try block as a result of a throw statement or a jump statement such as break , continue, or goto, the statements of the finally block are executed. The finally block is basically useful in three situations: to avoid duplication of statements, to release resources after an exception has been thrown and to assign a value to an object or display a message that may be useful to the program.

Let's see the example Showing Exceptions again:

// Example ShowingExceptions using finally
class ShowingExceptions
{
static void main()
{
Console.Write("Please enter a number :");
string str = Console.ReadLine();
double dNo;
}
try
{
dNo = double.Parse(str);
Console.WriteLine("Parsing successfully without errors");
}
finally
{
Console.WriteLine("Storing the number as 1.0");
dNo = 1.0; // dNo is assigned the value 1.0 irrespective of an error.
}
}

What are the other Exception Classes?

Here's a list of few Common Exception Classes:

System.ArithmeticException-A base class for exceptions that occur during arithmetic operations, such as System.DivideByZeroException


System.ArrayTypeMismatchException-Thrown when a store into an array fails because the actual type of the stored element is incompatible with the actual type of the array.


System.DivideByZeroException-Thrown when an attempt to divide an integral value by zero occurs.


System.IndexOutOfRangeException-Thrown when an attempt to index an array via an index that is less than zero or outside the bounds of the array.


System.InvalidCastExceptionThrown when an explicit conversion from a base type or interface to derived types fails at run time.


System.MulticastNotSupportedException-Thrown when an attempt to combine two non-null delegates fails, because the delegate type does not have a void return type.


System.NullReferenceException-Thrown when a null reference is used in a way that causes the referenced object to be required.


System.OutOfMemoryException-Thrown when an attempt to allocate memory (via new) fails.


System.OverflowException-Thrown when an arithmetic operation in a checked context overflows.

Best Interview

One of the best interviews!!!




Interviewer: Tell me about yourself.




Candidate: I am SAMEER GUPTA. I did my Tele Communication engineering from
BabanRao Dhole-Patil Institute of Technology.




Interviewer: BabanRao Dhole-Patil Institute of Technology? I had never heard
Of this college before!




Candidate: Great! Even I had not heard of it before getting an admission
Into it . What happened is - due to cricket world cup I scored badly! In 12th.I
Was getting a paid seat in a good college. But my father said (I prefer to
Call him 'baap') - "I can not invest so much of money".(The baap actually said
- "I will never waste so much of money on you"). So I had to join this
College. Frankly speaking this name - BabanRao Dhole-Patil, can at the most be
Related to a Shetakari Mahavidyalaya.







Interviewer: ok, ok. It seems you have taken 6 years to complete your
Engineering.




Candidate: Actually I tried my best to finish it in 4 years. But you
Know, these cricket matches and football world cup, and tennis
Tournaments. It is difficult to concentrate. So I flunked in 2nd and
3rd year. So in all I took 4 + 2 = 7 years.




Interviewer: But 4+2 is 6.




Candidate: Oh, is it? You know I always had KT in maths. But I will try
To keep this in mind. 4+2 is 6, good, thanks. These cricket matches
Really affect exams a lot. I think they should ban it.




Interviewer: Good to know that you want cricket matches to be banned.




Candidate: No, no... I am talking about Exams!!




Interviewer: Ok, What is your biggest achievement in life?




Candidate: Obviously, completing my Engineering. My mom never thought I
Would complete it. In fact, when I flunked in 3rd year, she was looking for a job
For me in BEST (Bus corporation in Maharashtra) through some relative.




Interviewer: Do you have any plans of higher study?




Candidate: he he he.. Are you kidding? Completing 'lower' education
Itself was so much of pain!!




Interviewer: Let's talk about technical stuff. On which platforms have
You worked?




Candidate: Well, I work at SEEPZ, so you can say Andheri is my current
Platform. Earlier I was at Vashi center. So Vashi was my platform then. As you can
See I have experience of different platforms! (Vashi and Andheri are the
Places in Mumbai)




Interviewer: And which languages have you used?




Candidate: Marathi, Hindi, English. By the way, I can keep quiet in
German, French, Russian and many other languages.




Interviewer: Why VC is better than VB?




Candidate: It is a common sense - C comes after B. So VC is a higher
Version than VB. I heard very soon they are coming up with a new
Language VD!




Interviewer: Do you know anything about Assembly Language?




Candidate: Well, I have not heard of it. But I guess, this is the
Language our ministers and MPs use in assembly.




Interviewer: What is your general project experience?




Candidate: My general experience about projects is - most of the times
They are in pipeline!




Interviewer: Can you tell me about your current job?




Candidate: Sure, Currently I am working for Bata InfoTech Ltd. Since
Joining BIL, I am on Bench. Before joining BIL, I used to think that
Bench was another software like Windows.




Interviewer: Do you have any project management experience?




Candidate: No, but I guess it shouldn't be difficult. I know Word and
Excel. I can talk a lot. I know how to dial for International phone call
And use speaker facility. And very important - I know few words like -
'Showstoppers ' , 'hotfixes',
'SEI-CMM','quality','versioncontrol','deadlines' , 'Customer
Satisfaction' etc. Also I can blame others for my mistakes!




Interviewer: What are your expectations from our company?







Candidate: Not much.



1. I should at least get 40,000 in hand.



2. I would like to work on a live EJB project. But it should not have
Deadlines. I personally feel that pressure affects natural talent.



3. I believe in flexi-timings.



4. Dress code is against basic freedom, so I
Would like to wear t-shirt and jeans.



5. We must have sat-sun off. I will suggest Wednesday off also, so as to
Avoid breakdown due to overwork.



6. I would like to go abroad 3 times a year on short term
preferably 2-4 months) assignments. Personally I prefer US, Australia and
Europe. But considering the fact that there is a world cup in West Indies in
2007, I don't mind going there in that period. As you can see I am modest and
don't have many expectations. So can I assume my selection?







Interviewer: he he he ha ha ha. Thanks for your interest in our
organization. In fact I was never entertained so much before. Welcome to
INFOSYS .. :-))




No intention to offend anybody..

Getting Started with IIS7

Introduction


Visual Studio comes with an inbuilt web server. No doubt the inbuilt web server comes handy during development. However, finally your web site needs to sit inside Internet Information Services (IIS). If you are an ASP.NET developers you are probably familiar with IIS6. The new generations of Windows namely Windows Vista and Windows Server 2008 come with IIS7. The new version of IIS is different than earlier versions in many areas. In fact the entire architecture of IIS has been revamped for the good. In this article I am going to give you a jump start on IIS7. I will confine myself to the features that are most commonly needed by ASP.NET developers. If you wish to deploy your websites on IIS7 then this article should give you a good start.

New Architecture of IIS7
As I mentioned earlier, IIS7 has been revamped since its previous versions. The most significant areas of improvement (for developers) are modular architecture, IIS user interface, request processing pipeline and ASP.NET integration. Let's see each of these improvements in brief.

Modular Architecture
The new architecture introduced in IIS7 is modular in nature. Individual features of IIS are organized in various functionally related modules. This allows administrators to install only the required features resulting in decreased footprint of the web server. Additionally, they can install patches and upgrades related to installed components only. These modules can be turned on or off using "Windows Features" dialog of Windows Vista.



Request Processing Pipeline
In the early versions of IIS there were essentially two request pipelines. One used by IIS and one used by ASP.NET. The request authentication, execution of ISAPI extensions and filters etc. used to happen at IIS level first and then the request used to reach ASP.NET. Then ASP.NET used to run its own authentication and HTTP handlers and modules. As you might have guessed there was some duplication of work and responsibilities. The IIS7 on the other hand provides an integrated requested processing pipeline that combines IIS and ASP.NET processing into a single step.

ASP.NET integration
With ASP.NET 2.0 Microsoft added the ASP.NET tab to the IIS application property dialog. Taking this integration further IIS7 adds a lot more integration that makes administrator's job easy.

IIS User Interface
IIS user interface has been greatly redesigned for better organization.


Now that you have some idea of what IIS7 has to offer, let's see how some common tasks can be performed. I am going to use Windows Vista for all the discussion below. The concepts remain the same for IIS under Windows Server 2008 also.

IIS Manager
The IIS manager can be accessed from Control Panel > System and Maintenance > Administrative Tools > Internet Information Services Manager.

The IIS manager user interface consists of three panes. The left hand side pane is Connections, the middle pane is Workspace and the right hand side pane is Actions.

The Connections pane lists application pools and websites. The workspace pane consists of two tabs at the bottom namely Features View and Content View. The Features View allows you to work with the settings of the selected item from Connections pane whereas the Content View displays all the child nodes (content) of the selected item. The following Figure shows these two views for the "Default Web Site"





Working with Application Pools
Application pool is a group of IIS applications that are isolated from other application pools. Each application pool runs in its own worker process. Any problem with that process affects the applications residing in it and not the rest of the applications. You can configure application pools individually.

In order to create a new application pool, select "Application Pools" under Connections pane. Then click on "Add application pool" from Actions pane. This will open a dialog as shown below:



Specify a name for the new pool to be created. Select .NET framework version that all the applications from the pool will use. Also select pipeline mode. There are two pipeline modes viz. integrated and classic. The integrated mode uses the integrated request processing model whereas the classic mode uses the older request processing model. Click OK to create the application pool.

Your new application pool will now be displayed in the Workspace pane. To configure the application pool click on the "Advanced Settings" option under Actions pane. The following figure shows many of the configurable properties of an application pool.



Creating Websites
One good feature of IIS7 under Vista is that it allows you to create multiple web sites. This feature was missing on Windows XP or Windows 2000 Professional. Server editions of Windows obviously don't have such limitation. To create a new web site, select Web Sites node under Connections pane and then click on "Add Web Site" under Actions pane. This opens a dialog as shown below:



Here, you can specify properties of the new web site including its application pool and physical location.

Creating IIS Applications
Creating an IIS application or a Virtual Directory is quick and simple. Just right click on the web site and choose either "Add Application" or "Add Virtual Directory" to open respective dialogs .





An existing Virtual directory can be marked as an IIS application by right clicking on it and selecting "Convert to Application".

Once you create a website or an IIS application, you can then set several ASP.NET related configuration properties via Workspace pane.

Gridview Row DataBound and Row Command

PageIndexChanged
Occurs when one of the pager buttons is clicked, but after the GridView control handles the paging operation.
PageIndexChanging
Occurs when one of the pager buttons is clicked, but before the GridView control handles the paging operation.
PreRender
Occurs after the Control object is loaded but prior to rendering. (Inherited from Control.)
RowCancelingEdit
Occurs when the Cancel button of a row in edit mode is clicked, but before the row exits edit mode.
RowCommand
Occurs when a button is clicked in a GridView control.
RowCreated
Occurs when a row is created in a GridView control.
RowDataBound
Occurs when a data row is bound to data in a GridView control.
RowDeleted
Occurs when a row's Delete button is clicked, but after the GridView control deletes the row.
RowDeleting
Occurs when a row's Delete button is clicked, but before the GridView control deletes the row.
RowEditing
Occurs when a row's Edit button is clicked, but before the GridView control enters edit mode.
RowUpdated
Occurs when a row's Update button is clicked, but after the GridView control updates the row.
RowUpdating
Occurs when a row's Update button is clicked, but before the GridView control updates the row.
SelectedIndexChanged
Occurs when a row's Select button is clicked, but after the GridView control handles the select operation.
SelectedIndexChanging
Occurs when a row's Select button is clicked, but before the GridView control handles the select operation.
Sorted
Occurs when the hyperlink to sort a column is clicked, but after the GridView control handles the sort operation.
Sorting
Occurs when the hyperlink to sort a column is clicked, but before the GridView control handles the sort operation.
Unload
Occurs when the server control is unloaded from memory. (Inherited from Control.)



protected void gvWebSite_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) {
LinkButton btnButt = (LinkButton)e.Row.Cells[1].FindControl("btnDelete");
btnButt.CommandArgument = e.Row.RowIndex.ToString();
}
if (e.Row.RowType == DataControlRowType.DataRow) { LinkButton l = (LinkButton)e.Row.FindControl("btnDelete"); l.Attributes.Add("onclick", "javascript:return " + "confirm('Are you sure you want to delete " + DataBinder.Eval(e.Row.DataItem, "websitename") + " and all its contents?')");
} }



protected void gvWebSite_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName.Equals("Delete")) { int rowNumber = Convert.ToInt32(e.CommandArgument); string SiteName = ((Label)gvWebSite.Rows[rowNumber].FindControl("lblSiteName")).Text; string path = ((Label)gvWebSite.Rows[rowNumber].FindControl("lblAdsPath")).Text;
CurrentContext context = (CurrentContext)Session["CurrentContext"]; CurrentUser cuser = (CurrentUser)Session["CurrentUser"]; string PreferredDC = ConfigurationManager.AppSettings["PreferredDC"].ToString(); Microsoft.Provisioning.MPSWSProxy.WindowsBasedHosting.WindowsBasedHosting wbh = new Microsoft.Provisioning.MPSWSProxy.WindowsBasedHosting.WindowsBasedHosting(); wbh.Credentials = new NetworkCredential(cuser.SamAccountName, cuser.Password, cuser.Domain);
string mpsResponse = wbh.DeleteCustomerWebSite(Utilities.RemoveDCFromLdap(PreferredDC, path), SiteName, string.Empty, PreferredDC, string.Empty, true); Retrieve(); }
}



In Design Mode::

'> '>

Configuration Files

Web.Config File:

It is an optional XML File which stores configuration details for a specific asp.net web application.
Note: When you modify the settings in the Web.Config file, you do not need to restart the Web service for the modifications to take effect.. By default, the Web.Config file applies to all the pages in the current directory and its subdirectories.
Extra: You can use the tag to lock configuration settings in the Web.Config file so that they cannot be overridden by a Web.Config file located below it. You can use the allowOverride attribute to lock configuration settings. This attribute is especially valuable if you are hosting untrusted applications on your server.


Machine.Config File:


The Machine.Config file, which specifies the settings that are global to a particular machine. This file is located at the following path:
\WINNT\Microsoft.NET\Framework\[Framework Version]\CONFIG\machine.config
As web.config file is used to configure one asp .net web application, same way Machine.config file is used to configure the application according to a particular machine. That is, configuration done in machine.config file is affected on any application that runs on a particular machine. Usually, this file is not altered and only web.config is used which configuring applications.
You can override settings in the Machine.Config file for all the applications in a particular Web site by placing a Web.Config file in the root directory of the Web site as follows:
\InetPub\wwwroot\Web.Config




Web.Config Vs Machine.Config

Machine.Config:
i) This is automatically installed when you install Visual Studio. Net.
ii) This is also called machine level configuration file.
iii)Only one machine.config file exists on a server.
iv) This file is at the highest level in the configuration hierarchy.

Web.Config:
i) This is automatically created when you create an ASP.Net web application project.
ii) This is also called application level configuration file.
iii)This file inherits setting from the machine.config