December 28, 2016

Exception: This document already has a 'DocumentElement' node Exception in C#

While manipulating an XML file I came across with this exception and googled it out for solution. I found many stuffs but none of those were relevant and could not resolve my problem. After few minutes of analysis, I came to know that I was doing something wrong.


I was trying to add element directly to XML document, which was not correct. It should be added within the root element. I changed my code accordingly and it was resolved. Full XML file and C# code is given below. Hope this will be helpful for others, and please feel free to add comments or any queries.


XML file:











C# code:

XmlDocument doc = new XmlDocument();
            doc.Load("xml_file_path");

            // Create new element:
            XmlElement book = doc.CreateElement("Book");

            // Create child elements:
            XmlElement title = docDestn.CreateElement("Title");
            title.InnerText = "Mastering in ASP.Net 4.5";

            XmlElement author = docDestn.CreateElement("Author");
            title.InnerText = "Unknown Author";

            XmlElement version = docDestn.CreateElement("Version");
            title.InnerText = "V4.5";

            book.AppendChild(title);
            book.AppendChild(author);
            book.AppendChild(version);

            // Read the root node:
            XmlNode root = doc.SelectSingleNode("AllBooks");
            root.AppendChild(book);
            doc.Save("xml_file_path");

July 29, 2016

Microsoft message queue (MSMQ) in C# and .NET

This article is written based on Microsoft Windows 7 using C# and .NET framework 2.0.


Microsoft message queue (MSMQ) is one of the technique with which you can achieve communication between two application processes running in same machine, under Windows platform.

To use MSMQ, you need to add reference System.Messaging explicitly in to your project and then you can avail its functionalities. Two very basic functions of MessageQueue class are Send() and Receive().

Send() method sends data to the message queue while Receive() method reads data from the message queue.

Microsoft Windows OS have three types of message queuing techniques and those are: -
1. Outgoing queue
2. Private queue
3. System queue

To view a queue, right click on MyCoputer -> Manage, expand Services and Applications and then expand Message QueuingAll queue used to enlist here, under the respective category that you have chosen while creating a message queue.






C# code to send send and receive data:


// Write data:
            string qPath = ".\\Private$\\MyQueue";
            MessageQueue mq;

            if (!MessageQueue.Exists(qPath))
            {
                mq = MessageQueue.Create(qPath);
            }
            else
                mq = new MessageQueue(qPath);

            Message msg = new Message();
            msg.Label = "TestQueue";
            msg.Body = "This is a test method.";
            mq.Send(msg);



// Read data:
try
            {
string qPath = ".\\Private$\\MyQueue";
Message msg = new Message();
                  MessageQueue msQ = new MessageQueue(qPath);
                  msg = msQ.Receive();
msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
                  string msgReceived = msg.Body.ToString();
            }
            catch { }



Possible Errors:

1. The queue does not exist or you do not have sufficient permissions to perform the operation.
This is because if you havn’t created any queue or the queue does not exist and you are trying to use a queue. Conditional check  if(!MessageQueue.Exists(qPath)) generally resolve this error.

    2. Cannot find a formatter capable of reading this message.
    This is because you have not defined the respective format of received queue data. Below code can be used to define formatter.

    msg.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

    Here, I have used XML format and therefore, used XmlMessageFormatter class. Please change in your code for its format accordingly.

    February 17, 2016

    Pointer in C#, use of unsafe keyword

    In this article, we will understand the concept of pointers in C# and how we can use it in our C# code. While learning, I heard that C# does not support pointer which is not exactly true. It does support pointers but we do not have full control over it as in C++. Basically, to maintain type safety and security, C# does not support pointers but by explicit changes we can work with C# pointers.


    Use of 'unsafe' keyword

    By using ‘unsafe’ keyword, you can perform an operation that deals with pointers. Code or method used ‘unsafe’ modifier does not mean it is not safe but it is not verifiable by CLR. Unsafe code blocks are not dangerous but its safety does not verified by CLR, means if you are using pointers it is your responsibility to handle security risks and pointer errors.

    • Unsafe keyword can be used with- methods, types or code blocks.
    • Use of ‘unsafe’ keyword introduced security risks, as these are not handled by CLR and it is developer’s responsibility to manage all.
    • Use of ‘unsafe’ keyword can increase the application’s performance as it directly working wit memory addresses.

    Defining with ‘unsafe’ keyword

    Example: 1
    public unsafe void TestUnsafe()
    {
        //TODO:
    }

    Example: 2
    public void TestUnsafe()
    {
        unsafe
        {
           //TODO:
        }
    }

    Compiling above code you may get below error:

    Unsafe code may only appear if compiling with /unsafe

    To resolve it, right click on project > properties >
    Select ‘Build’ tab, check the option for ‘Allow unsafe code’. Save it and now compile.