Search code examples
c#msmq

Problems with Sending message to MSMQ


I have a scenario where in i have to send a message to the msmq below in the format of message header + payload. Below is the example.

        Person Message
        <? Xml version="1.0"?>
        <Person>
        <Employee>
         <Name>Manthan</name>
        </employee>
        </Person>

How to send above message to msmq, i have tried all possible solution but still no success. Any help will be appreciated. Thanks in advance

Below is the code

       StringBuilder sb = new StringBuilder();
       sb.Append("Person Message"); 
       sb.Append("<?XML Version=\"1.0\">");
       sb.Append("<Person>");
       sb.Append("<Employee>");
       sb.Append("<Name>Manthan</Name>");
       sb.Append("</Employee>");
       sb.Append("</Person>");

      MessageQueue  msMq = new MessageQueue(MQPath);
      msmq.Send(sb.tostring());

Output in MSMQ is

        <?xml version="1.0"?>
         <string>Person Message&lt;?XML       Version="1.0"&gt;&lt;Person&gt;&lt;Employee&gt;&lt;Name&gt;Manthan&lt;/Name&gt;&lt;/Employee&gt;&lt;/Person&gt;</string>

Above message is not same as expected output how to get the expected output


Solution

  • MSMQ put messages in SOAP you will have to deserialize the results ....

    MessageQueue  msMq = new MessageQueue(MQPath);
    msmq.Send(sb.tostring());
    
    Message[] msgs = msMq.GetAllMessages();
    
    foreach (var msg in msgs)
          {
                System.IO.StreamReader reader = new System.IO.StreamReader(msg.BodyStream);
                MSGtext = reader.ReadToEnd();
    
                string MSGValue = (string)XmlDeserializeFromString(MSGtext);
    
            }
     }
     public object XmlDeserializeFromString(string objectData)
        {
            var serializer = new XmlSerializer(typeof(string));
            object result;
    
            using (TextReader reader = new StringReader(objectData))
            {
                result = serializer.Deserialize(reader);
            }
            return result;
        }