some interesting responses on UTF-16 problem with XMLTextWriter

 This is what hb replied with :

yar may be, because
utf-16 is two byte per character.
so with string writer its unicode.
if u enforece ascii then utf-8 would be there.

(note: my reply is just an argument, i might need correction, so dont hesitate to correct me)


I replied hb’s mail as following:

yes exactly thats wat the point is.. it sounds reasonable for string writer to generate a utf-16 prologues .. but my amazement revolves around the fact there isnt any support for parametrizing prologue specually encoding specs..

This is what Ahsan had to add:

There is one thing that i think you are missing here. you should be using XmlTextWriter for writing xml to stream.
Dim writer As New System.Xml.XmlTextWriter(“”, System.Text.Encoding.Unicode)

here you specify the encoding for the xml so it spefically know in which way it should be written.

Stringwriter is generic for all types of files, it will not cater specifics of the xml schema

Also please read this
This tell the capabilities of IE

Follwing is my response to Ahsan’s mail:

Ahsan my friend! you dint get me right. System.Xml.XMLTextWriter has three constructors

1- public XmlTextWriter(Stream, Encoding);// IOStream required
2- public XmlTextWriter(TextWriter); // valid reference to TextWriterRequired
3- public XmlTextWriter(string, Encoding); // string is for FileName

The problem is I dont want to user stream (binary or filestream). I want to build an an in memory representation of XML Document without using binary/file stream ( requirement!). Now I am left with using only constrcutor number 2.

And I believe you know that TextWriter is an abstract base class so I am left to look for any of the two implementations 1- StreamWriter and 2- StringWriter. And you can realize i cant go for option 1 so it has to be StringWriter and thats where I faced the problem that i posted. What do you say ?

System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Xml.XmlTextWriter xmlTextWriter = new System.Xml.XmlTextWriter(stringWriter);
xmlTextWriter.WriteStartDocument(); // here it writes prologue :/

System.IO.StringWriter and UTF-16 Encoding problem with System.XML.XMLDocument

 I am continuing my work with System.XML and System.XML.XPath namespaces. This implies that my adventure with XML and .NET is not over yet. I came across this interesting situation while freezing my code for next release.

I was actually generating XML document using System.IO.StringWriter and System.XML.XMLDocument. Apparently there shouldnt be any issues with it. But actually there is a small problem with that. When you use StringWriter to write XMLDocuments it appends a prologue with “UTF-16” encoding specified. Now theres a big problem if you want to change the encoding to “UTF-8” or any thing else (available in System.Text.Encoding). You cant really do that… since there is no provision for it. Strange as it may sound, I came across a hack for this situation as well located at . And then i came across a reason why XMLDocument generated from StringWriter has to be encoded using UTF-16 encoding.

Well the strange most part of this adventure was that IE 6.0 din’t support viewing utf-16 encoded strings. Heck!. While Mozilla Firefox was graceful enough to show tree view of utf-16 encoded XML document.

So here are the two things that I as a developer would have liked to see in .NET and IE.

1- There should have been some way provided to change the encoding scheme, yes even using System.StringWriter. I believe this thing could have been supported through System.XML.XMLDocument constructor.

2-IE should have supported viewing UTF-16 document.

Extracting XMLNode from XPathNodeIterator

The project that I am working on these days require me to play a lot with XML. To navigate XML and fetch required information I use XPath to query XML. Though XPath offers significant performance gains over XMLNode (DOM) based parsing. However, there are times when you just want to use XMLNode perhaps you want to get hold of OuterXML or  want to append certain element to DocumentElement of XML document. In these scenarios XPathNodeIterator apparently is of no particular help, or so I thought atleast.
I was actually iterating an XML document using XPathNodeIterator and wanted to fetch the XMLNode instance for the current node that I was on. I really did not wanted to go for DOM based parsing and XPathNodeIterator wasnt helping me with XMLNode instance either. So I was virtually staring down the barrel 😉 and dint know how to go about it. Then one of my juniors said “GOOGLE HAI NA!”… He googled it came up with this awesome post from Daniel Cazzulino.

After going through his post I was able to extract XMLNode from XPathNodeIterator. The catch was that XPathNavigator implements IHasXMLNode interface and you can type cast XPathNodeIterator.Current into IHasXMLNode and then call GetNode() to get instance of XMLNode.  Following is a sample code that I used:

font-size: small;
color: black;
font-family: Courier New , Courier, Monospace;
background-color: #ffffff;
/*white-space: pre;*/
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
background-color: #f4f4f4;
width: 100%;
margin: 0em;
.csharpcode .lnum { color: #606060; }

   1:  // Task XML Declaration
   2:              if(xpTaskXMLIterator.MoveNext())
   3:              {                    
   4:                  taskInfo    =    new Kalsoft.BusinessProcess.Core.Task();
   5:                  //taskInfo.TaskXml = xpTaskXMLIterator.Current.g
   6:                  int taskType=    int.Parse(xpTaskXMLIterator.Current.GetAttribute
   7:                      (Constants.Attributes.Type,
   8:                      xpTaskXMLIterator.Current.NamespaceURI));
   9:                  /// Task Type
  10:                  if(    taskType!=Kalsoft.BusinessProcess.Core.TaskType.EmailTask 
  11:                      &&    
  12:                      taskType!=Kalsoft.BusinessProcess.Core.TaskType.SpsDocLibTask )
  13:                  {
  14:                      throw new InvalidOperationException();
  16:                  }                                        
  17:                  taskInfo.Type    =    taskType;
  18:                  xmlNode            =    
  19:                  ((System.Xml.IHasXmlNode)xpTaskXMLIterator.Current).GetNode();
  21:                  taskInfo.TaskXml=    xmlNode.InnerXml;
  22:              }

System.Enum.Parse :: The right way!

To compare strings with enums the right way, one should use enum.parse rather than comparing string literals. Following is an example where i am parsing a string type variable named messageId and creating an enum of type MessageType

MessageType messageType = (MessageType) System.Enum.Parse(typeof(MessageType),messageId,true);

Last argument in System.Enum.Parse specifies if the enumeration/comparison should be case sensitive or not.

Visualise XPath Queries with Visual XPath

Any one who has used XPath to navigate XML Documents knows that it is a tricky business to do. Selecting specified node(s), evaluating expressions and things like that could actually take a bit of your time. And this all isnt much intuitive to a common developr.

I my self usually have to refer to XPath query syntax whenever i intend to use it. I came across this awesome tool that was written by my senior and mentor Noman Laghari.

The best part with Visual XPath is that you dont really have to compile and execute your code just check if you wrote the correct XPath Query. All you have to do is to load an XML Document (any XML file) and then select the node you want to query. The tool will automatically create an XPath query for the selected node.

Visual XPath is a must have tool for any serious XML Developer. Its source code is available along with the executable for download. I feel one could add a bit or two of functionality to this already awesome tool. What do you people say ?

Undserstanding Microsoft Integration Technologies

In todays world of EAI (Enterprise Application Integration) and SO (Service Orientation) its very important to understand integrating technologies and tools that are made available to us. I always say that todays is the information world that can be thought of applications as an islands automated within themselves but not usually connected to others. And to connect them is “the task“. Sooner or later our most of efforts and development time would be consumed in either integrating applications or architecting/developing applications in such a way that they are easilyconnectable“.

Microsoft has provided us with a number of options for architecting/designing/developing “connected applications“. Microsoft has also produced a number of integration technologies. Some of these technologies are tightly integrated with data stores e.g. SQL Server Replication Services and SQL Server 2005’s Service Broker(SSB), while others talk about application level integration using ASMX Web Services, .NET Remoting or COM+(Enterprise Services). And then there are MSMQ for queue based integration. To complement this all is a broker based .NET Server that we are all in love with : BizTalk Server. Not to forget INDIGO that provides a single consistent platform for .NET Remoting, XML Web Services, MSMQ, Enterprise Services etc in a “Service Oriented

While a number of things pertaining to integration can be done in number of ways using any number of above mentioned technologies, there is no single rule of thumb for us developers/consultants to either opt for or recommend to a client when it comes to “integration” scenarios.

Just to make our lives easier Microsoft has published a white paper that i came to know about when i was visiting Scot Woodgate’s Blog. I believe it is a must read for any serious developer/architect. You can download this white paper here.

ps: I am also uploading this document to DotNetWizard’s yahoo group file section