<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Matt's Blog &#187; .Net</title>
	<atom:link href="http://blog.rueedlinger.ch/category/net/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.rueedlinger.ch</link>
	<description>Software Engineering and Java</description>
	<lastBuildDate>Tue, 07 Sep 2010 17:38:55 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>.Net (C#) and SOAP with Attachments</title>
		<link>http://blog.rueedlinger.ch/2009/01/net-c-and-soap-with-attachments/</link>
		<comments>http://blog.rueedlinger.ch/2009/01/net-c-and-soap-with-attachments/#comments</comments>
		<pubDate>Fri, 30 Jan 2009 14:24:48 +0000</pubDate>
		<dc:creator>Matthias Rüedlinger</dc:creator>
				<category><![CDATA[.Net]]></category>
		<category><![CDATA[woolly thoughts]]></category>

		<guid isPermaLink="false">http://blog.rueedlinger.ch/?p=40</guid>
		<description><![CDATA[In our project we offer a web service to our customers and to simplify the use of the web service we have implemented web service clients as examples in different frameworks. So we have the usual suspects for Java (JAX-WS, Apache CXF and Axis).
I was asked if I’m interested in program a web service client [...]]]></description>
			<content:encoded><![CDATA[<p>In our project we offer a web service to our customers and to simplify the use of the web service we have implemented web service clients as examples in different frameworks. So we have the usual suspects for Java (JAX-WS, Apache CXF and Axis).</p>
<p>I was asked if I’m interested in program a web service client for the .Net framework. I had already some little experience with C# and ASP.Net and so I thought it would be nice to see what .Net has to offer.</p>
<p>So first the goal was to implement a web service client for a contract first document / literal / wrapped web service which is WS-I Attachments Profile conform.</p>
<p>The big problem is that .Net does not support SwA (SOAP Messages with Attachments). There are three approaches which could work for you when you have the same problem.</p>
<ul>
<li>Use the open source library <a href="http://www.pocketsoap.com/">PocketSOAP </a></li>
<li>Use the commercial library from <a href="http://www.alotsoft.com/view/product.jsf">Alotsoft.com</a></li>
<li>Create your own web service stub</li>
</ul>
<p>In this post I will show you how you could send a SOAP request manually, receive the SOAP response and parse the MIME attachments with the open source library <a href="http://anmar.eu.org/projects/sharpmimetools/">SharpMimeTools</a>.</p>
<p>So keep in mind that I&#8217;m a Java developer and not a C# developer. I also wrote these pieces of code only to show that there is also a simple way to receive a SOAP response with MIME attachments when your were forced to write a web service stub manually in C#.</p>
<h3>Data contract</h3>
<p>So first we create our Data contract with the <strong>xsd.exe</strong>. After that we can serialize or deserialize XML with the <strong>System.Xml.XMLSerializer</strong> from the .Net framework. You will find a reference to a XSD schema in your WSDL file from your web service for which you want to create a web service client.</p>
<pre class="code">Xsd.exe data_contract.xsd /c /o:c:\out</pre>
<h3>Send SOAP request</h3>
<p>With <strong>System.Net.HttpWebRequest</strong> you can send a SOAP request manually to your endpoint. We serialize our XML with the <strong>XMLSerializer </strong>and add the SOAP Envelope, SOAP Header and SOAP Body.</p>
<p>The followng example show how you could use the <strong>XMLSerializer </strong>and the <strong>HttpWebRequest </strong>to create a SOAP request and send it to a web service endpoint.</p>
<pre class="code">FileStream fs = new FileStream(“C:\data.xml”, FileMode.Open);
XmlSerializer serializer = new XmlSerializer(typeof(MyData));
MyData myData = (MyData) serializerReq.Deserialize(fs);

XmlWriterSettings writerSettings = new XmlWriterSettings();
writerSettings.OmitXmlDeclaration = true;
StringWriter stringWriter = new StringWriter();

using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter,
	writerSettings))
      {
                serializerReq.Serialize(xmlWriter, myData);
      }

string xmlText = stringWriter.ToString();
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.ContentType = @"text/xml;charset=""utf-8""";
req.Accept = "text.xml";
req.Method = "POST";

// create soap message (with SOAP Header, Body and Envelope)
String msg = START_MSG + xmlText + END_MSG;
byte[] reqBytes = System.Text.Encoding.UTF8.GetBytes(msg);
req.ContentLength = reqBytes.Length;
Stream reqStream = req.GetRequestStream();

// send soap request
reqStream.Write(reqBytes, 0, reqBytes.Length); reqStream.Close();

reqStream.Close();</pre>
<h3>Receive SOAP response</h3>
<p>We will use the <a href="http://anmar.eu.org/projects/sharpmimetools/">SharpMimeTools </a>to parse MIME attachments. So for that we have to make our response stream MIME multipart conform.</p>
<p>The example show how you can create a stream which can be parsed from the SharpMimeTool library. You have to copy the HTTP headers <strong>Date</strong>, <strong>Content-Type</strong>, <strong>Content-Length</strong> and the content of the HttpWebReponse stream to a memory stream. The new memeory stream can then be parsed by the SharpMimeTool library.</p>
<pre class="code">HttpWebResponse res = …;
MemoryStream httpStream = …;
MemoryStream mimeStream = …;
Encoding utf8 = Encoding.UTF8;
TextReader readerReq = new StreamReader(httpStream, utf8);
TextWriter writer = new StreamWriter(mimeStream, utf8);

// create a correct mime stream form the HttpResponseStream
// add http headers which were required for a correct mime
// format
writer.WriteLine("Date: " + res.GetResponseHeader("Date"));
writer.WriteLine("Content-Type: " + res.ContentType);
writer.WriteLine("Content-Length: " + res.ContentLength);
writer.WriteLine(Environment.NewLine);

// copy rest of the stream
while (true)
{
      string line = readerReq.ReadLine();
      if (line == null)
      {
                break;
      }
      writer.WriteLine(line);
}
writer.Flush();
mimeStream.Position = 0;

// parse  the stream for mime attachments
SharpMessage message = new SharpMessage(mimeStream,
   SharpDecodeOptions.Default | SharpDecodeOptions.DecodeTnef |
   SharpDecodeOptions.UuDecode);</pre>
<h3>Parse MIME attachments from the SOAP response</h3>
<p>With the SharpMessage from the <a href="http://anmar.eu.org/projects/sharpmimetools/">SharpMimeTools </a>we can access the SOAP response and also the MIME attachments.</p>
<pre class="code">SharpMessage message = …;
if (message.Attachments != null)
{
  foreach (attachment in message.Attachments)
  {
    Stream stream = attachment.Stream;
    …
  }</pre>
<h3>Finally&#8230;</h3>
<p>To access the soap payload you could retrieve it with XPath and then deserialize it with the XMLSerializer.</p>
<p>&#8230; I hope this post and line of codes gave you a hint how you could parse a SOAP response with MIME attachments manually in C#.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.rueedlinger.ch/2009/01/net-c-and-soap-with-attachments/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>
