Implementing Custom BodyWriter

Damir Dobric Posts

Next talks:

 

    

Follow me on Twitter: #ddobric



 

 

Archives

By sending of messages directly on the message layer, you will often have to create and manipulate the message itself.
Unfortunately WCF does not offer a very powerful support for message manipulation.
For example following code shows how to send the message:

ChannelFactory<IRequestChannel> nativeRequestFactory =
new ChannelFactory<IRequestChannel>(httpBinding, endpointAddress);

IRequestChannel reqChannel = nativeRequestFactory.CreateChannel();

Message reply = reqChannel.Request(
msg);

However, there is one thing missing in this example. That is, how to create the message. There are various ways
how to do this, but personally, I miss the way to build the message from string and XmlDocument. Fortunately, there is a relative simple way
to do that. The method Message.CreateMessage, which creates the message has, following signature:

Message msg = Message.CreateMessage(MessageVersion, string , BodyWriter);

All it has to be done is to derive the class BodyWriter. Following example shows how to implement custom body writer which
creates the message from string and XmlDocument.

using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel.Channels;
using System.Xml;
namespace Client {

public class MyBodyWriter : BodyWriter
{
  
XmlDocument m_XDoc;
  
  
public MyBodyWriter(XmlDocument xDoc) : base(false)
  
{
    
m_XDoc = xDoc; 
  
}

   public MyBodyWriter(string message) : base(false)
  
{
     
m_XDoc = new XmlDocument();
    
m_XDoc.LoadXml(message);
  
}

   protected override void
   OnWriteBodyContents(System.Xml.XmlDictionaryWriter writer)
  

      
writer.WriteRaw(m_XDoc.OuterXml);
  

 
}
}


Now, by using of the custom writer following code can be used to create and send the message:

ChannelFactory<IRequestChannel> nativeRequestFactory =
new ChannelFactory<IRequestChannel>(httpBinding, endpointAddress);

IRequestChannel reqChannel = nativeRequestFactory.CreateChannel();

string st = @"<QueryMessage xmlns=""cevapproduction"">
<CevapQuery xmlns:a="http://schemas.datacontract.org/2004/07/Server"
xmlns:i=""http://www.w3.org/2001/XMLSchema-instance""><a:Cijena>7</a:Cijena>
<a:KajmakYesNo>true</a:KajmakYesNo></CevapQuery></QueryMessage>";

MyBodyWriter bodyWriter1 = new MyBodyWriter(st);

Message msg = Message.CreateMessage(MessageVersion.Soap11,
"cevapproduction/ICevap/ImaLiCevapa", bodyWriter);

Message reply = reqChannel.Request(msg1);


Posted Apr 08 2007, 11:42 PM by Damir Dobric
Filed under:

Comments

Damir Dobric wrote re: Implementing Custom BodyWriter
on 04-09-2007 12:45
Damir Dobric Posts wrote Custom BodyWriter Part II
on 04-25-2007 13:50

Few days ago I posted an example which shows how to implement the custom BodyWriter class which helps

developers.de is a .Net Community Blog powered by daenet GmbH.