<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Kiener&#039;s Blog &#187; WCF</title>
	<atom:link href="http://blog.thekieners.com/tag/wcf/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.thekieners.com</link>
	<description>Blog of Beat Kiener, containing my experiences, thoughts, comments and questions</description>
	<lastBuildDate>Thu, 26 Jan 2012 02:01:22 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='blog.thekieners.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://s2.wp.com/i/buttonw-com.png</url>
		<title>Kiener&#039;s Blog &#187; WCF</title>
		<link>http://blog.thekieners.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://blog.thekieners.com/osd.xml" title="Kiener&#039;s Blog" />
	<atom:link rel='hub' href='http://blog.thekieners.com/?pushpress=hub'/>
		<item>
		<title>Optimize Data Contracts for better WCF Performance</title>
		<link>http://blog.thekieners.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/</link>
		<comments>http://blog.thekieners.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/#comments</comments>
		<pubDate>Tue, 04 May 2010 06:59:00 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">https://bkiener.wordpress.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/</guid>
		<description><![CDATA[Out of the box Silverlight provides two message encoding types for sending SOAP messages over the wire. These are TextEncoding and BinaryEncoding. MTOM encoding is still not available within Silverlight. Binary encoded messages produce a payload that is about half the size of a message encoded with standard text encoding. Please note that binary encoding [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=457&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Out of the box Silverlight provides two message encoding types for sending SOAP messages over the wire. These are <i>TextEncoding</i> and <i>BinaryEncoding</i>. MTOM encoding is still not available within Silverlight.</p>
<p>Binary encoded messages produce a payload that is about half the size of a message encoded with standard text encoding. Please note that binary encoding is a Microsoft proprietary implementation and therefore not interoperable outside the .NET framework.</p>
<p>In our Silverlight applications we use a .NET to .NET messaging scenario (like many other SL apps too), which means Silverlight communicates with a WCF backend. Using then binary encoded messages is obvious.    <br />You will find a lot of blog posts out there in the community when you are interested in binary vs. text-encoding comparison.</p>
<h2>What exactly does BinaryEncoding?</h2>
<p><b></b></p>
<p>When the encoding is set to binary, then the <em>DataContractSerializer</em> still produces SOAP messages as XML but after that the messages get transformed into a binary representation of the XML with help of the <em>XmlDictionaryWriter</em> class.</p>
<p>The following code snippet shows the usage of the <em>XmlDictionaryWriter</em> class (not WCF related).</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb.png?w=713&#038;h=418" width="713" height="418" /></a> </p>
<p>You should not compare the <em>XmlDictionaryWriter</em> with the well-known <em>BinaryFormatter</em> in the mscorlib. The <em>BinaryFormatter</em> produces a binary representation of an object graph. The <em>XmlDictionaryWriter</em> on the other hand translates a textual XML into a binary representation. Serializing a XML string with the <em>BinaryFormatter</em> will not reduce the size, because the XML is just a single string from this point of view.</p>
<p>The textual output form the example above indicates that it is a kind of an optimized XML structure. </p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image1.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb1.png?w=828&#038;h=73" width="828" height="73" /></a> </p>
<p><b></b></p>
<h2>Optimize Data Contracts</h2>
<p>Binary XML still includes the names of the elements and attributes as plain text.</p>
<p>When setting the name of my data contracts to a single character then the SOAP message size will be reduced by additional 30-50 percent (depends on the data structure).</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image2.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb2.png?w=363&#038;h=288" width="363" height="288" /></a> </p>
<p>&#160;</p>
<p>The SOAP-Envelop then look like this:</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image3.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb3.png?w=468&#038;h=248" width="468" height="248" /></a> </p>
<p>Rules for setting the name: </p>
<ul>
<li>Each data contract must have a unique name in the scope of its namespace </li>
<li>Each data member must have a unique name in the scope of its class. </li>
<li>Use character [A-Za-z], you can mix upper and lower case. </li>
</ul>
<p>After these changes the generated proxy on client side is quite unhandy, because the classes and members are named like they are declared in the contracts. Therefore I created a shared lib and reuse the data contracts on client side.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image4.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb4.png?w=523&#038;h=344" width="523" height="344" /></a> </p>
<p>Assemblies built in Silverlight are in general not binary compatible with the .NET Framework, so if you want to share code you need to dual-compile your code. Since Silverlight 4 you will be able to use some Silverlight-based assemblies from within .NET 4. In order to load a Silverlight assembly in .NET, the assembly may only reference the following assemblies: mscorlib.dll, System, System.Core.dll, System.ComponentModel.Composition.dll, Microsoft.VisualBasic.dll. </p>
<p>Well, my shared data contracts dll needs a reference to System.Runtime.Serialization.dll which is currently not binary compatible with the Silverlight runtime. </p>
<p>Therefore I do a dual-compile by adding the same source file with “Add As Link” to my Silverlight library.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/clip_image008.png"><img style="display:inline;border-width:0;" title="clip_image008" border="0" alt="clip_image008" src="http://bkiener.files.wordpress.com/2010/05/clip_image008_thumb.png?w=513&#038;h=401" width="513" height="401" /></a></p>
<p>As final task I add a reference to SharedDataContract.SL assembly and update my service reference. Please check that the option “Reuse types in referenced assemblies” is checked.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/clip_image009.png"><img style="display:inline;border-width:0;" title="clip_image009" border="0" alt="clip_image009" src="http://bkiener.files.wordpress.com/2010/05/clip_image009_thumb.png?w=334&#038;h=66" width="334" height="66" /></a></p>
<p>&#160;</p>
<p><b></b></p>
<p><b></b></p>
<h2>Comparison of different configurations </h2>
<p><b></b></p>
<p><strong>Text encoding / standard contract</strong></p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image5.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb5.png?w=294&#038;h=192" width="294" height="192" /></a>&#160;</p>
<p>&#160;</p>
<p><strong>Text encoding / optimized contracts</strong></p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image6.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb6.png?w=297&#038;h=198" width="297" height="198" /></a>&#160;</p>
<p>&#160;</p>
<p><strong>Binary encoding / standard contracts</strong></p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image7.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb7.png?w=299&#038;h=173" width="299" height="173" /></a> </p>
<p>&#160;</p>
<p><strong>Binary encoding / optimized contracts</strong></p>
<p><a href="http://bkiener.files.wordpress.com/2010/05/image8.png"><img style="display:inline;border-width:0;" title="image" border="0" alt="image" src="http://bkiener.files.wordpress.com/2010/05/image_thumb8.png?w=300&#038;h=172" width="300" height="172" /></a> </p>
<h2>Summary</h2>
<p>When communicating in a .NET to .NET messaging scenario then optimizing the data contracts is an additional way to reduce the SOAP message size. This together with binary encoding will reduce the message size about 4 times. Especially looking to the Windows Phone 7 development this will help when the traffic goes over a low bandwidth network.</p>
<p>&#160;</p>
<h2>Demo Project</h2>
<p><a href="http://files.thekieners.com/blogcontent/2010/OptimizedWcfPerformance.zip" target="_blank">Download it here</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/457/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/457/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/457/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=457&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/05/04/optimize-data-contracts-for-better-wcf-performance/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb1.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb3.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/clip_image008_thumb.png" medium="image">
			<media:title type="html">clip_image008</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/clip_image009_thumb.png" medium="image">
			<media:title type="html">clip_image009</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb6.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb7.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/05/image_thumb8.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>Opening a Microsoft Office documents with Silverlight</title>
		<link>http://blog.thekieners.com/2010/04/21/opening-an-microsoft-office-documents-with-silverlight/</link>
		<comments>http://blog.thekieners.com/2010/04/21/opening-an-microsoft-office-documents-with-silverlight/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 08:37:09 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Office]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2010/04/21/opening-an-microsoft-office-documents-with-silverlight/</guid>
		<description><![CDATA[Situation From our Silverlight application we must be able to view documents. Documents are stored in an existing document management system and are accessible through a WCF REST service. It sounds very easy, but it was quite hard to understand all the stuff going on behind the Internet Explorer and the Microsoft Office. Simplest solution [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=427&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<h2>Situation</h2>
<p>From our Silverlight application we must be able to view documents. Documents are stored in an existing document management system and are accessible through a WCF REST service. It sounds very easy, but it was quite hard to understand all the stuff going on behind the Internet Explorer and the Microsoft Office.</p>
<h2>Simplest solution</h2>
<p>Download the content via a WebClient instance and save it with help of the Silverlight SaveFileDialog to the users local disk. Unfortunately this simple solution provides not the expected user experience, because Silverlight is not able to set the file name for the SaveFileDialog and after saving the user must manually navigate to the local folder and open the document by hand. The user experience should like be “Click &amp; View” and not “Click, Safe, Search, Open &amp; View”.</p>
<h2>Expected solution</h2>
<p>Open a popup from the Silverlight application with the URL pointing to the document.</p>
<p>Via HtmlPage:</p>
<pre>Uri docUri = <span style="color:#0000ff;">new</span> Uri("<span style="color:#8b0000;">http://mydomain/docs/test.docx</span>");
HtmlPage.PopupWindow(docUri, "<span style="color:#8b0000;">windwow1</span>", <span style="color:#0000ff;">null</span>);</pre>
<p>Or via a HyperlinkButton:</p>
<pre><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">HyperlinkButton</span> <span style="color:#ff0000;">Content</span>=<span style="color:#0000ff;">"open document"</span>
                <span style="color:#ff0000;">NavigateUri</span>=<span style="color:#0000ff;">"http://mydomain/docs/test.docx"</span>
                <span style="color:#ff0000;">TargetName</span>=<span style="color:#0000ff;">"_blank"</span> <span style="color:#0000ff;">/&gt;</span></pre>
<h2>The service part</h2>
<p>We deliver documents through a simple WCF REST service from our middle layer infrastructure. We use a custom authentication system that relies on HTTP session cookies for client identification. When the user isn’t authenticated then the service will redirect the request to the logon page (status code 302). The REST service is a self-hosted windows service (existing middle layer). The service is available with the URI pattern: <em>http://&lt;myhost&gt;/docs/&lt;docname&gt;</em></p>
<p>As example: <em>http://mydomain/docs/test.docx</em></p>
<p>Here the simplified version of our REST service.</p>
<pre><span style="color:#0000ff;">public</span> Stream GetContent(<span style="color:#0000ff;">string</span> docId)
{

    WebOperationContext context = WebOperationContext.Current;

    <span style="color:#008000;">// read session cookie</span>
    <span style="color:#0000ff;">string</span> cookies = context.IncomingRequest.Headers[HttpRequestHeader.Cookie];
    <span style="color:#0000ff;">string</span> sessionId = "";
    <span style="color:#0000ff;">if</span> (cookies != <span style="color:#0000ff;">null</span>)
    {
        <span style="color:#008000;">// parse cookie values</span>
        var cookieItems = from c <span style="color:#0000ff;">in</span> cookies.Split(';')
                            let cc = c.Split('=')
                            where cc.Length == 2
                            select <span style="color:#0000ff;">new</span> { Name = cc[0].Trim().ToLower(), Value = cc[1].Trim() };

        var items = cookieItems.ToDictionary(c =&gt; c.Name);

        <span style="color:#0000ff;">if</span> (items.ContainsKey("<span style="color:#8b0000;">sessionid</span>"))
            sessionId = items["<span style="color:#8b0000;">sessionid</span>"].Value;
    }

    <span style="color:#008000;">// check session is valid</span>
    <span style="color:#0000ff;">bool</span> sessionValid = <span style="color:#0000ff;">false</span>;
    sessionValid = sessionId == "<span style="color:#8b0000;">1234</span>"; <span style="color:#008000;">// todo</span>

    <span style="color:#0000ff;">if</span> (!sessionValid)
    {
        <span style="color:#008000;">// redirect uri</span>
        <span style="color:#0000ff;">string</span> redirectUri = "<span style="color:#8b0000;">http://mydomain/logon.html</span>";
        <span style="color:#008000;">// ...set the location the logon site should naviagate to after the successful logon</span>
        redirectUri += "<span style="color:#8b0000;">?redirect=</span>" + context.IncomingRequest.UriTemplateMatch.RequestUri.ToString();
        <span style="color:#008000;">// redirect to the logon page </span>
        context.OutgoingResponse.Location = redirectUri;
        context.OutgoingResponse.StatusCode = HttpStatusCode.Redirect;
        <span style="color:#008000;">// response has header only</span>
        <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
    }
    <span style="color:#0000ff;">else</span>
    {

        <span style="color:#0000ff;">try</span>
        {

            <span style="color:#008000;">// check if document exists </span>
            <span style="color:#0000ff;">bool</span> docExists = <span style="color:#0000ff;">true</span>; <span style="color:#008000;">// todo</span>

            <span style="color:#0000ff;">if</span> (docExists)
            {
                <span style="color:#008000;">// todo</span>
                FileInfo requestedFile = <span style="color:#0000ff;">new</span> FileInfo("<span style="color:#8b0000;">todo</span>");

                <span style="color:#008000;">// set mime type (firefox, chrome and safari requires them)</span>
                context.OutgoingResponse.ContentType = GetMimeType(requestedFile.Extension);
                <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> FileStream(requestedFile.FullName, FileMode.Open);
            }
            <span style="color:#0000ff;">else</span>
            {
                <span style="color:#008000;">// doc not found</span>
                context.OutgoingResponse.StatusCode = HttpStatusCode.NotFound;
                context.OutgoingResponse.StatusDescription = "<span style="color:#8b0000;">Document not found</span>";
                <span style="color:#008000;">// response has header only</span>
                <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
            }

        }
        <span style="color:#0000ff;">catch</span> (Exception ex)
        {
            <span style="color:#008000;">// general error</span>
            context.OutgoingResponse.StatusCode = HttpStatusCode.InternalServerError;
            <span style="color:#008000;">// response has header only</span>
            <span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;
        }
    }
}</pre>
<p>At this point everything works fine with Firefox, Google Chrome and Safari on Mac.</p>
<h2>Internet Explorer is different</h2>
<p>Internet Explorer acts a little bit different as expected. When opening an office document (Word, Excel, PowerPoint) from a web page in Internet Explorer the Fiddler call stack lock like this:</p>
<pre>winword:  HEAD    http://mydomain/docs/test.docx HTTP/1.1     405 NotAllowed
winword:  OPTIONS http://mydomain/docs/ HTTP/1.1              405 NotAllowed
winword:  GET     http://mydomain/docs/test.docx HTTP/1.1     302 Redirect</pre>
<p>As you can see the iexplore process isn’t involved. What’s going on? IE detects the mime type from the file name extension, if it is preserved in the URL string. Here some examples:</p>
<pre> </pre>
<table border="0" cellspacing="2" cellpadding="2" width="600">
<tbody>
<tr>
<td width="300" valign="top">http://mydomain/docs/test.docx</td>
<td width="300" valign="top">IE detects mime type as docx</td>
</tr>
<tr>
<td width="300" valign="top">http://mydomain/service.svc/test.docx</td>
<td width="300" valign="top">IE cannot detect mime type (it isn’t svc)</td>
</tr>
<tr>
<td width="300" valign="top">http://mydomain/resource.ashx?file=test.docx</td>
<td width="300" valign="top">IE cannot detect mime type (it isn’t ash)</td>
</tr>
</tbody>
</table>
<p>What happened with iexplore? Office 2007 and 2010 Beta are designed to make a more collaborative workspace. Therefore, several changes have been made to how Office works with web content. These changes provide better authoring features for the following Web servers that support Office:</p>
<ul>
<li>Microsoft Windows SharePoint Services</li>
<li>Microsoft SharePoint Portal Server</li>
<li>Microsoft Exchange Web Store</li>
</ul>
<p>IE detects if the web resource is an Office format by analyzing the URL. If so IE will start the corresponding Office program with the URL as process start parameter like the following:</p>
<p><em>&#8220;C:\Program Files\Microsoft Office\Office14\WINWORD.EXE&#8221; /n http://mydomain/docs/test.docx”</em></p>
<p>Office is now downloading the content from the web:</p>
<p><a href="http://bkiener.files.wordpress.com/2010/04/image.png"><img style="display:inline;border-width:0;" title="image" src="http://bkiener.files.wordpress.com/2010/04/image_thumb.png?w=347&#038;h=121" border="0" alt="image" width="347" height="121" /></a></p>
<p>The request will end with the status code 302 and a redirect location to our logon page, because session cookies are not shared between Internet Explorer and winword process. Well, Office Word will follow this redirection and tries to display our Silverlight logon page. This isn’t possible because the SL plug-in isn’t available for the Office suite and Word shows the following content.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/04/image4.png"><img style="display:inline;border-width:0;" title="image" src="http://bkiener.files.wordpress.com/2010/04/image_thumb4.png?w=582&#038;h=346" border="0" alt="image" width="582" height="346" /></a> </p>
<p>When we change our service so that it doesn’t make a redirection and returning the status code 404 (Not Found), then word is telling me that it wasn’t able to open the doc.</p>
<p><a href="http://bkiener.files.wordpress.com/2010/04/image2.png"><img style="display:inline;border-width:0;" title="image" src="http://bkiener.files.wordpress.com/2010/04/image_thumb2.png?w=348&#038;h=160" border="0" alt="image" width="348" height="160" /></a></p>
<h2>First improvement</h2>
<p>Changing the service to get another URL pattern for our documents so that IE cannot detect the mime type through the URL.</p>
<p>Something like this.</p>
<ul>
<li><em>http://mydomain/docs/id=test.docx </em></li>
<li><em>http://mydomain/docs.svc/test.docx</em></li>
</ul>
<p>What’s happening now. Let’s look at Fiddler’s call stack.</p>
<pre>iexplore: GET     http://mydomain/docs/test.docx HTTP/1.1     200 OK
winword:  HEAD    http://mydomain/docs/test.docx HTTP/1.1     405 NotAllowed
winword:  OPTIONS http://mydomain/docs/ HTTP/1.1              405 NotAllowed
winword:  GET     http://mydomain/docs/test.docx HTTP/1.1     302 Redirect</pre>
<p>Now IE is downloading the content as expected. But then winword comes into the play again. What’s going on in this situation?</p>
<p>IE cannot detect the mime type from the URL so it will download the web content as any other browser. With the request to our service the browser is sending our session cookie to the server too. Based on the mime type from the response IE decides to open Microsoft Word. IE does that the same way as before: starting the winword process with a startup argument including the URL instead of the downloaded local file.</p>
<p>&#8220;C:\Program Files\Microsoft Office\Office14\WINWORD.EXE&#8221; /n http://mydomain/docs/test.docx”</p>
<p>Same situation, Office looks like this again:</p>
<p><a href="http://bkiener.files.wordpress.com/2010/04/image5.png"><img style="display:inline;border:0;" title="image" src="http://bkiener.files.wordpress.com/2010/04/image_thumb5.png?w=339&#038;h=202" border="0" alt="image" width="339" height="202" /></a> </p>
<p>Why the Office suite is doing that? Because Office lets you edit and author documents on a Web site if the server supports Web authoring and collaboration (Sharepoint, Exchange, etc). First, Office tries to communicate with the Web server with a series of HEAD and OPTIONS requests to discover the possibilities of the webserver (“Microsoft Office Protocol Discovery”, “Microsoft Office Existence Discovery” and “Microsoft Office Core Storage Infrastructure”). Then Office tries to directly bind to the resource with a GET request to the web resource.</p>
<h2>Second improvement</h2>
<p>Our WCF REST service doesn’t handle the HEAD and OPTIONS request from the “Microsoft Office Protocol Discovery” and “Microsoft Office Existence Discovery”, but it redirects the GET request from the “Microsoft Office Core Storage Infrastructure” to the logon page while winword can’t deliver the session cookie.</p>
<p>What we can do is to detect the caller via the User-Agent header. There are three main User-Agent’s used from the Office suite.</p>
<ul>
<li>Microsoft Office Protocol Discovery</li>
<li>Microsoft Office Core Storage Infrastructure</li>
<li>Microsoft Office Existence Discovery</li>
</ul>
<p>In case of one of these 3 user-agents our service returns the status code 401 (Unauthorized) instead of the 302 (Redirect).</p>
<p>Then winword ignores the 401 and opens the document from the cached document which was previously downloaded from IE.</p>
<p>Here the code snippet to do that:</p>
<pre><span style="color:#008000;">// check user agent for office product suite</span>
<span style="color:#0000ff;">bool</span> isOfficeSuite = <span style="color:#0000ff;">false</span>;
<span style="color:#0000ff;">if</span> (!<span style="color:#0000ff;">string</span>.IsNullOrEmpty(WebOperationContext.Current.IncomingRequest.UserAgent))
{
    <span style="color:#0000ff;">string</span>[] officeUserAgents = { "<span style="color:#8b0000;">Microsoft Office Protocol Discovery</span>",
                                    "<span style="color:#8b0000;">Microsoft Office Existence Discovery</span>",
                                    "<span style="color:#8b0000;">Microsoft Office Core Storage Infrastructure</span>" };

    <span style="color:#0000ff;">string</span> requestUserAgent = WebOperationContext.Current.IncomingRequest.UserAgent.ToLower();

    var q = from userAgent <span style="color:#0000ff;">in</span> officeUserAgents
            where requestUserAgent.ToLower().Replace("<span style="color:#8b0000;"> </span>", "")
                               .Contains(userAgent.ToLower().Replace("<span style="color:#8b0000;"> </span>", ""))
            select userAgent;

    isOfficeSuite = q.Count() &gt; 0;
}

<span style="color:#0000ff;">if</span> (isOfficeSuite)
{
    <span style="color:#008000;">// don't redirect when office program want getting the document via </span>
    <span style="color:#008000;">// "Microsoft Office Protocol Discovery" or </span>
    <span style="color:#008000;">// "Microsoft Office Core Storage Infrastructure" requests.</span>
    <span style="color:#008000;">// Excel/word whould redirect to the logon page an display the html!</span>
    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized;
}
<span style="color:#0000ff;">else</span>
{
    <span style="color:#008000;">// redirect to the logon page</span>
    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Redirect;
    <span style="color:#008000;">// TODO</span>
    WebOperationContext.Current.OutgoingResponse.Location = "<span style="color:#8b0000;">http://rnd.glauxsoft.ch/evidencenovaweb/</span>";
}

<span style="color:#008000;">// response has header only</span>
<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">null</span>;</pre>
<p> </p>
<p>Unfortunately this works well with Office 2007, but first tests with Office 2010 Beta are different again. Excel and PowerPoint 2010 doesn’t ignore the 401 status code and telling us “Could not open the document &#8230;”. Maybe this is an error in the beta.</p>
<h2>Third improvement</h2>
<p>However, this kind of communication doesn’t make me happy. What can we do that IE downloads the content and then simply start the process associated to the mime type as that other browsers still do?</p>
<p>The typical workaround I found is to use the Content-Disposition attachment header in the GET response when returning the file. This header will tell the web browser to treat the file as a download (read-only), so the file will open in Office from the web browser cache location instead of a URL. With that setting, the Office application will treat the file as local, and will therefore not make calls back to the web server.</p>
<p>Content-disposition is an extension to the MIME protocol that instructs a MIME user agent on how it should display an attached file. When Internet Explorer receives the header, it raises a <strong>File Download</strong> dialog box whose file name box is automatically populated with the file name that is specified in the header</p>
<p>In our service we set this header for all well-known Office formats, because other mime types should still be opened inline within the browser such as PDF, TXT or JPG, GIF, etc.</p>
<p>Here the code snippet to doing that</p>
<pre><span style="color:#008000;">// well-know office formats</span>
<span style="color:#0000ff;">string</span>[] officeMimeTypes =  {  "<span style="color:#8b0000;">.doc</span>","<span style="color:#8b0000;">.dot</span>","<span style="color:#8b0000;">.docx</span>","<span style="color:#8b0000;">.dotx</span>","<span style="color:#8b0000;">.docm</span>","<span style="color:#8b0000;">.dotm</span>",
        "<span style="color:#8b0000;">.xls</span>","<span style="color:#8b0000;">.xlt</span>","<span style="color:#8b0000;">.xla</span>","<span style="color:#8b0000;">.xlsx</span>","<span style="color:#8b0000;">.xltx</span>","<span style="color:#8b0000;">.xlsm</span>",
        "<span style="color:#8b0000;">.xltm</span>","<span style="color:#8b0000;">.xlam</span>","<span style="color:#8b0000;">.xlsb</span>","<span style="color:#8b0000;">.ppt</span>","<span style="color:#8b0000;">.pot</span>","<span style="color:#8b0000;">.pps</span>",
        "<span style="color:#8b0000;">.ppa</span>","<span style="color:#8b0000;">.pptx</span>","<span style="color:#8b0000;">.potx</span>","<span style="color:#8b0000;">.ppsx</span>","<span style="color:#8b0000;">.ppam</span>","<span style="color:#8b0000;">.pptm</span>",
        "<span style="color:#8b0000;">.potm</span>","<span style="color:#8b0000;">.ppsm</span>"};

<span style="color:#008000;">// add content-disposition header.This header will tell the web browser </span>
<span style="color:#008000;">// to treat the file as a download (read-only), so the file will open </span>
<span style="color:#008000;">// in Office from the web browser cache location instead of a URL. </span>
<span style="color:#0000ff;">if</span> (officeMimeTypes.Contains(requestedFile.Extension.ToLower()))
{
    WebOperationContext.Current.OutgoingResponse.Headers.Add("<span style="color:#8b0000;">Content-disposition</span>",
                                            "<span style="color:#8b0000;">attachment;filename=</span>" + requestedFile.Name);
}

<span style="color:#008000;">// set mime type (firefox, chrome and safari requires them always)</span>
WebOperationContext.Current.OutgoingResponse.ContentType = GetMimeType(requestedFile.Extension);
<span style="color:#0000ff;">return</span> <span style="color:#0000ff;">new</span> FileStream(requestedFile.FullName, FileMode.Open);

 </pre>
<h2>Summary</h2>
<p>Internet Explorer handles Microsoft Office formats other than expected. The main reason is to make a more collaborative workspace when working with SharePoint and Exchange. This different behavior let you run into troubles when you have your own service providing the documents.</p>
<p>In brief you should consider the following to get around these troubles:</p>
<ul>
<li>Don’t let the IE detect the mime type from the URL</li>
<li>Don’t redirect to the logon page when the User-Agent is “Microsoft Office Core Storage Infrastructure”</li>
<li>Set the Content-disposition header for all well-known Office formats when returning the file.</li>
</ul>
<h2>Resources</h2>
<p><a title="http://support.microsoft.com/kb/260519/en-us" href="http://support.microsoft.com/kb/260519/en-us">http://support.microsoft.com/kb/260519/en-us</a></p>
<p><a title="http://support.microsoft.com/default.aspx?scid=kb;EN-US;899927" href="http://support.microsoft.com/default.aspx?scid=kb;EN-US;899927">http://support.microsoft.com/default.aspx?scid=kb;EN-US;899927</a></p>
<p><a title="http://blogs.msdn.com/vsofficedeveloper/pages/Office-Existence-Discovery-Protocol.aspx" href="http://blogs.msdn.com/vsofficedeveloper/pages/Office-Existence-Discovery-Protocol.aspx">http://blogs.msdn.com/vsofficedeveloper/pages/Office-Existence-Discovery-Protocol.aspx</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/427/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/427/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/427/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=427&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2010/04/21/opening-an-microsoft-office-documents-with-silverlight/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/04/image_thumb.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/04/image_thumb4.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/04/image_thumb2.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>

		<media:content url="http://bkiener.files.wordpress.com/2010/04/image_thumb5.png" medium="image">
			<media:title type="html">image</media:title>
		</media:content>
	</item>
		<item>
		<title>BasicHttpBinaryBinding for Silverlight</title>
		<link>http://blog.thekieners.com/2009/05/22/basichttpbinarybinding-for-silverlight/</link>
		<comments>http://blog.thekieners.com/2009/05/22/basichttpbinarybinding-for-silverlight/#comments</comments>
		<pubDate>Fri, 22 May 2009 08:25:00 +0000</pubDate>
		<dc:creator>beatkiener</dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[Silverlight]]></category>
		<category><![CDATA[WCF]]></category>

		<guid isPermaLink="false">http://bkiener.wordpress.com/2009/05/22/basichttpbinarybinding-for-silverlight/</guid>
		<description><![CDATA[Silverlight 3 beta introduces a binary message encoder on the channel stack. Binary encoding is implemented as a custom binding, there is no out-of-the-box binary binding. &#60;bindings&#62; &#60;customBinding&#62; &#60;binding name=&#34;binaryHttpBinding&#34;&#62; &#60;binaryMessageEncoding /&#62; &#60;httpTransport /&#62; &#60;/binding&#62; &#60;/customBinding&#62; &#60;/bindings&#62; &#60;endpoint address=&#34;&#34; binding=&#34;customBinding&#34; bindingConfiguration=&#34;binaryHttpBinding&#34; contract=&#34;Service&#34; /&#62; If you would set the binding programmatically you have to configure your [...]<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=216&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></description>
			<content:encoded><![CDATA[<p>Silverlight 3 beta introduces a binary message encoder on the channel stack.</p>
<p>Binary encoding is implemented as a custom binding, there is no out-of-the-box binary binding.</p>
<pre><span style="color:#0000ff;">&lt;</span><span style="color:#800000;">bindings</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">customBinding</span><span style="color:#0000ff;">&gt;</span>
	<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">binding</span> <span style="color:#ff0000;">name</span>=<span style="color:#0000ff;">&quot;binaryHttpBinding&quot;</span><span style="color:#0000ff;">&gt;</span>
	   <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">binaryMessageEncoding</span> <span style="color:#0000ff;">/&gt;</span>
         <span style="color:#0000ff;">&lt;</span><span style="color:#800000;">httpTransport</span> <span style="color:#0000ff;">/&gt;</span>
      <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">binding</span><span style="color:#0000ff;">&gt;</span>
  <span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">customBinding</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;/</span><span style="color:#800000;">bindings</span><span style="color:#0000ff;">&gt;</span>
<span style="color:#0000ff;">&lt;</span><span style="color:#800000;">endpoint</span> <span style="color:#ff0000;">address</span>=<span style="color:#0000ff;">&quot;&quot;</span>
          <span style="color:#ff0000;">binding</span>=<span style="color:#0000ff;">&quot;customBinding&quot;</span>
          <span style="color:#ff0000;">bindingConfiguration</span>=<span style="color:#0000ff;">&quot;binaryHttpBinding&quot;</span>
          <span style="color:#ff0000;">contract</span>=<span style="color:#0000ff;">&quot;Service&quot;</span> <span style="color:#0000ff;">/&gt;</span></pre>
<p>If you would set the binding programmatically you have to configure your own CustomBinding instance.</p>
<p>This was the reason to implement the BasicHttpBinaryBinding class as you can find below.</p>
<p><strong>UPDATE May 2010:</strong> The method CreateBindingElements copies now the reader quotas and other settings to the binary element.</p>
<pre><span style="color:#808080;">/// &lt;summary&gt;</span>
<span style="color:#008000;">// Represents a basic http binding with binary encoding.</span>
<span style="color:#808080;">/// &lt;/summary&gt;</span>
<span style="color:#0000ff;">public</span> <span style="color:#0000ff;">class</span> BasicHttpBinaryBinding : BasicHttpBinding
{
  <span style="color:#808080;">/// &lt;summary&gt;</span>
  <span style="color:#808080;">///  Initializes a new instance of the BasicHttpBinaryBinding class.</span>
  <span style="color:#808080;">/// &lt;/summary&gt;</span>
  <span style="color:#0000ff;">public</span> BasicHttpBinaryBinding()
    : <span style="color:#0000ff;">this</span>(BasicHttpSecurityMode.None)
  {
  }

  <span style="color:#808080;">/// &lt;summary&gt;</span>
  <span style="color:#808080;">/// Initializes a new instance of the BasicHttpBinaryBinding class.</span>
  <span style="color:#808080;">/// &lt;/summary&gt;</span>
  <span style="color:#808080;">/// &lt;param name=&quot;securityMode&quot;&gt;</span>
  <span style="color:#808080;">/// The value of System.ServiceModel.BasicHttpSecurityMode that specifies </span>
  <span style="color:#808080;">/// the type of security that is used with the SOAP message and for the client.</span>
  <span style="color:#808080;">/// &lt;/param&gt;</span>
  <span style="color:#0000ff;">public</span> BasicHttpBinaryBinding(BasicHttpSecurityMode securityMode)
    : <span style="color:#0000ff;">this</span>(securityMode, <span style="color:#0000ff;">true</span>)
  {
  }

  <span style="color:#808080;">/// &lt;summary&gt;</span>
  <span style="color:#808080;">/// Initializes a new instance of the BasicHttpBinaryBinding class.</span>
  <span style="color:#808080;">/// &lt;/summary&gt;</span>
  <span style="color:#808080;">/// &lt;param name=&quot;securityMode&quot;&gt;</span>
  <span style="color:#808080;">/// The value of System.ServiceModel.BasicHttpSecurityMode that specifies </span>
  <span style="color:#808080;">/// the type of security that is used with the SOAP message and for the client.</span>
  <span style="color:#808080;">/// &lt;/param&gt;</span>
  <span style="color:#808080;">/// &lt;param name=&quot;binaryEncoding&quot;&gt;</span>
  <span style="color:#808080;">/// Indicates whether the binary encoding is enabled or not</span>
  <span style="color:#808080;">/// &lt;/param&gt;</span>
  <span style="color:#0000ff;">public</span> BasicHttpBinaryBinding(BasicHttpSecurityMode securityMode, <span style="color:#0000ff;">bool</span> binaryEncoding)
    : <span style="color:#0000ff;">base</span>(securityMode)
  {
    <span style="color:#0000ff;">this</span>.BinaryEncoding = <span style="color:#0000ff;">true</span>;
    <span style="color:#0000ff;">this</span>.BinaryEncoding = binaryEncoding;
  }

  <span style="color:#808080;">/// &lt;summary&gt;</span>
  <span style="color:#808080;">/// Gets or sets a value that indicates whether the binary encoding is enabled or not. </span>
  <span style="color:#808080;">/// Default is true.</span>
  <span style="color:#808080;">/// &lt;/summary&gt;</span>
  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">bool</span> BinaryEncoding { <span style="color:#0000ff;">get</span>; <span style="color:#0000ff;">set</span>; }

  <span style="color:#808080;">/// &lt;summary&gt;</span>
  <span style="color:#808080;">/// Returns an ordered collection of binding elements contained in the current binding.</span>
  <span style="color:#808080;">/// &lt;/summary&gt;</span>
  <span style="color:#0000ff;">public</span> <span style="color:#0000ff;">override</span> BindingElementCollection CreateBindingElements()
  {
    BindingElementCollection elements = <span style="color:#0000ff;">base</span>.CreateBindingElements();

    <span style="color:#0000ff;">if</span> (<span style="color:#0000ff;">this</span>.BinaryEncoding)
    {
      <span style="color:#008000;">// search the existing message encoding element (Text or MTOM) and replace it</span>
      <span style="color:#008000;">// note: the search must be done with the base type of text and mtom binding element, </span>
      <span style="color:#008000;">// because this code is compiled against silverlight also </span>
      <span style="color:#008000;">// and there is no mtom encoding available</span>
      <span style="color:#0000ff;">for</span> (<span style="color:#0000ff;">int</span> i = elements.Count - 1; i &gt;= 0; i--)
      {
        BindingElement element = elements[i];
        <span style="color:#0000ff;">if</span> (element.GetType().IsSubclassOf(<span style="color:#0000ff;">typeof</span>(MessageEncodingBindingElement)))
        {
          BinaryMessageEncodingBindingElement binaryElement = <span style="color:#0000ff;">null</span>;

          <span style="color:#0000ff;">if</span> (element <span style="color:#0000ff;">is</span> TextMessageEncodingBindingElement)
          {
            <span style="color:#008000;">// copy settings to binary element</span>
            TextMessageEncodingBindingElement textEncoding = element <span style="color:#0000ff;">as</span> TextMessageEncodingBindingElement;
            binaryElement = <span style="color:#0000ff;">new</span> BinaryMessageEncodingBindingElement();

            <span style="color:#008000;">// copy settings</span>
            binaryElement.ReaderQuotas.MaxArrayLength = textEncoding.ReaderQuotas.MaxArrayLength;
            binaryElement.ReaderQuotas.MaxBytesPerRead = textEncoding.ReaderQuotas.MaxBytesPerRead;
            binaryElement.ReaderQuotas.MaxDepth = textEncoding.ReaderQuotas.MaxDepth;
            binaryElement.ReaderQuotas.MaxNameTableCharCount = textEncoding.ReaderQuotas.MaxNameTableCharCount;
            binaryElement.ReaderQuotas.MaxStringContentLength = textEncoding.ReaderQuotas.MaxStringContentLength;
            binaryElement.MaxReadPoolSize = textEncoding.MaxReadPoolSize;
            binaryElement.MaxWritePoolSize = textEncoding.MaxWritePoolSize;

            <span style="color:#008000;">// binary uses always soap-1.2</span>
            <span style="color:#008000;">//binaryElement.MessageVersion = textEncoding.MessageVersion;</span>
          }
          <span style="color:#0000ff;">else</span> <span style="color:#0000ff;">if</span> (element <span style="color:#0000ff;">is</span> MtomMessageEncodingBindingElement)
          {
            <span style="color:#008000;">// copy settings to binary element</span>
            MtomMessageEncodingBindingElement mtomEncoding = element <span style="color:#0000ff;">as</span> MtomMessageEncodingBindingElement;
            binaryElement = <span style="color:#0000ff;">new</span> BinaryMessageEncodingBindingElement();

            <span style="color:#008000;">// copy settings</span>
            binaryElement.ReaderQuotas.MaxArrayLength = mtomEncoding.ReaderQuotas.MaxArrayLength;
            binaryElement.ReaderQuotas.MaxBytesPerRead = mtomEncoding.ReaderQuotas.MaxBytesPerRead;
            binaryElement.ReaderQuotas.MaxDepth = mtomEncoding.ReaderQuotas.MaxDepth;
            binaryElement.ReaderQuotas.MaxNameTableCharCount = mtomEncoding.ReaderQuotas.MaxNameTableCharCount;
            binaryElement.ReaderQuotas.MaxStringContentLength = mtomEncoding.ReaderQuotas.MaxStringContentLength;
            binaryElement.MaxReadPoolSize = mtomEncoding.MaxReadPoolSize;
            binaryElement.MaxWritePoolSize = mtomEncoding.MaxWritePoolSize;

            <span style="color:#008000;">// binary uses always soap-1.2</span>
            <span style="color:#008000;">//binaryElement.MessageVersion = mtomEncoding.MessageVersion;</span>
          }
          <span style="color:#0000ff;">else</span> <span style="color:#0000ff;">if</span> (element <span style="color:#0000ff;">is</span> BinaryMessageEncodingBindingElement)
          {
            <span style="color:#008000;">// it's already binary</span>
          }
          <span style="color:#0000ff;">else</span>
          {
            <span style="color:#0000ff;">string</span> exStr = <span style="color:#0000ff;">string</span>.Format(&quot;<span style="color:#8b0000;">Message encoding type {0} is not implemented.</span>&quot;, element.GetType().Name);
            <span style="color:#0000ff;">throw</span> <span style="color:#0000ff;">new</span> NotImplementedException(exStr);
          }

          <span style="color:#0000ff;">if</span> (binaryElement != <span style="color:#0000ff;">null</span>)
          {
            elements.RemoveAt(i);
            elements.Insert(i, binaryElement);
            <span style="color:#0000ff;">break</span>;
          }
        }
      }
    }

    <span style="color:#0000ff;">return</span> elements;
  }

}</pre>
<p>The class is Silverlight compilable, therefore you can share it along the Silverlight and wcf-service project.</p>
<p>How to use: instead of the BasicHttpBinding you can use BasicHttpBinaryBinding as following to enable binary encoding.</p>
<p><span style="text-decoration:line-through;">BasicHttpBinding binding = new BasicHttpBinding();</span></p>
<p>BasicHttpBinding binding = new <strong>BasicHttpBinaryBinding</strong>();</p>
<p><a href="http://files.thekieners.com/blogcontent/BasicHttpBinaryBinding" target="_blank">Download the code here</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godelicious/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/delicious/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gofacebook/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/facebook/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gotwitter/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/twitter/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gostumble/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/stumble/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/godigg/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/digg/bkiener.wordpress.com/216/" /></a> <a rel="nofollow" href="http://feeds.wordpress.com/1.0/goreddit/bkiener.wordpress.com/216/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/reddit/bkiener.wordpress.com/216/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=blog.thekieners.com&amp;blog=7436128&amp;post=216&amp;subd=bkiener&amp;ref=&amp;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://blog.thekieners.com/2009/05/22/basichttpbinarybinding-for-silverlight/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://1.gravatar.com/avatar/bbdffd0b655e44e12898217ff1973ad3?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">beatkiener</media:title>
		</media:content>
	</item>
	</channel>
</rss>
