<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
    <title>monogatari</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/" />
    <link rel="self" type="application/atom+xml" href="http://veritas-vos-liberabit.com/monogatari/atom.xml" />
    <id>tag:veritas-vos-liberabit.com,2008-10-01:/monogatari//1</id>
    <updated>2010-12-07T12:26:00Z</updated>
    
    <generator uri="http://www.sixapart.com/movabletype/">Movable Type 4.21-en</generator>

<entry>
    <title>call for testing System.Xaml.dll</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2010/12/call-for-testing-systemxamldll.html" />
    <id>tag:veritas-vos-liberabit.com,2010:/monogatari//1.102</id>

    <published>2010-12-07T11:28:36Z</published>
    <updated>2010-12-07T12:26:00Z</updated>

    <summary>This year was disasterous for me regarding machine troubles. I had to send my Acer laptop three times for repair (I have to say, their product is too fragile) and I also got Macbook white broken, which was worse, it...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>This year was disasterous for me regarding machine troubles. I had to send my Acer laptop three times for repair (I have to say, their product is too fragile) and I also got Macbook white broken, which was worse, it was after 15 months since I bought it (out of warrant). And every time I got them broken, I suspend ongoing work and moved to some lightweight tasks. So that's how I started ongoing System.Xaml work these days.</p>

<p>Our System.Xaml.dll was initially written in last string, which was included in Mono 2.8 and had basic type system support. It also contained XAML readers and writers too, but they were far from usable. They were tested only in a few primitive use cases, and I didn't have much time to hack them either.</p>

<p>After System.Xaml.dll in our git master is a lot better. I have rewritten all of XamlObjectReader, XamlXmlWriter, XamlXmlReader and XamlObjectWriter with the actual object graphs. It also involved a lot of fixes in the type system (XamlType etc.).</p>

<p>In addition to our <a href="http://go-mono.com/status/status.aspx?reference=4.0&amp;profile=4.0&amp;assembly=System.Xaml">class status page</a>, I created a <a href="http://www.mono-project.com/SystemXamlHacking">wiki page</a> on System.Xaml.dll work that describes the status in human language.</p>

<p>It should work fine with ordinal constructs such as Type (TypeExtension), Array (ArrayExtension), List, Dictionary and IXmlSerializable (XData). But it still doesn't support lots of "settings", and attachable properties are not supported either (as we don't have WPF or anything that provides them).</p>

<p>Now that I feel I am done with basic features, I'd like to ask anyone who uses this System.Xaml.dll in .NET 4 try our System.Xaml.dll in git master and see if it works. Make sure that your Xaml usage is independent of things like WPF (we don't have it, so it won't work). To check this, there is <a href="http://www.mono-project.com/MoMA">MoMA</a>.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Current WCF 4.0 status in Mono</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2010/09/current-wcf-40-status-in-mono.html" />
    <id>tag:veritas-vos-liberabit.com,2010:/monogatari//1.101</id>

    <published>2010-09-21T03:57:41Z</published>
    <updated>2010-09-21T04:05:25Z</updated>

    <summary>Mono 2.8 is approaching and I should indeed blog about it, but this post is about my recent hack in git head. Within the current future plan, we will be releasing 2.8.2 based on the git head, and by that...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Mono 2.8 is approaching and I should indeed blog about it, but this post is about my recent hack in git head. Within the current future plan, we will be releasing 2.8.2 based on the git head, and by that time we'll deliver our results that I'm going to write here.</p>

<p>It is about WCF 4.0 implementation status in Mono. While it was not my priority, I have been somehow working on it (initially it was due to my laptop's crash and repair, now I rather want to finish this ongoing side work), it seemed good to write about it.</p>

<p>WCF 4.0 had added a lot of new features that didn't exist in 3.5/SP1. <a href="http://msdn.microsoft.com/en-us/library/ee354381.aspx">An excellent article</a> by Aaron Sconnard is on MSDN, so I'll describe our ongoing effort based on the items he described.</p>

<table border="black">
  <tr>
    <th>featured area</th><th>current status</th>
  </tr><tr>
    <td>Simplified Configuration</td><td>almost done</td>
  </tr><tr>
    <td>Discovery</td><td>Announcement: done. Discovery: ongoing.</td>
  </tr><tr>
    <td>Routing</td><td>done</td>
  </tr><tr>
    <td>REST improvements</td><td>not done.</td>
  </tr><tr>
    <td>WF4 support</td><td>no plan yet.</td>
  </tr>
</table>

<p>(Note that this table does not contain other components such as WCF Data Services.)</p>

<h3>Simplified configuration</h3>

<p>In WCF4, configuration description can be reduced and it became much simpler to write. It's not always good as it also hides what WCF actually does from application developers, but almost everyone wouldn't understand what the engine does anyways, so no need to worry about that.</p>

<p>Default Endpoint was the last thing I actually hacked (as of now). In WCF 3.x, you always had to add service endpoints either in your app.config or by call to AddServiceEndpoint(). Since you wouldn't host more than two contract interfaces at a time and had to specify explicit endpoints for each, it is almost always waste of time, so in WCF4 it is automatically configured if you didn't provide explicit endpoint.</p>

<p>To achieve Default Endpoints, contract, binding and endpoint address must be provided. Since contract and endpoint can be given at ServiceHost constructors, only binding needs to be automatically guessed. And here is the practical use of Protocol Mapping. It is URIscheme-to-BindingType mapping, and the base addresses in a service host contain URI scheme.</p>

<p>The default Protocol Mappings are not visible in the machine.config in .NET 4.0, but they are filled at <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.protocolmappingsection.aspx">ProtocolMappingSection</a>'s <a href="http://msdn.microsoft.com/en-us/library/system.configuration.configurationelement.initializedefault.aspx">InitializeDefault</a> method. (You cannot see this overriden method in MSDN API reference - it could be confirmed through our class status pages, or some people like me could smell it because <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.configuration.clientsection.aspx">ClientSection</a> also had overriden InitializeDefault implementation like this and hence it lacked the actual config section.)</p>

<p>Standard Endpoints are implemented in accordance with WCF Discovery work. While I don't really like WCF configuration stack, there would be a couple of samples that are based on configuration to run, and I didn't want to get messed just by lack of it while dogfooding.</p>

<p>File-less activation is also what I think nice-to-have feature, but not implemented yet. (Well, and actually whatever I haven't written here aren't yet either.)</p>

<h3>Discovery</h3>

<p><a href="http://msdn.microsoft.com/en-us/library/dd456782.aspx">WCF Discovery</a> is a <a href="http://en.wikipedia.org/wiki/WS-Discovery">WS-Discovery</a> implementation, which enables us to dynamically register and dispatch the destination information for specific type of services by announcement by service providers and queries by client consumers. Sadly it is SOAP-based and useless for other bindings.</p>

<p>WCF Discovery needed some tricks and underlying layers that I had to (and need to) work on:</p>

<ul>
<li>Standard endpoint support. Both AnnouncementEndpoint and DiscoveryEndpoint are standard endpoints that needed extra work on WCF 4.0 stack done earlier.</li>
<li>UDP transport. It is so far available only through those standard endpoints (ServiceEndpoint's Binding property). .NET UDP transport implementation as well as ours has some hacky code, for example it repeats sending messages a couple of times so that the recipients will rarely miss it, so I can understand why it's not exposed as part of public API. (Repeating UDP messages won't fit other UDP uses such as sending OSC messages to instruments.)</li>
<li>Multiple WS-Discovery spec. version support. There are <a href="http://docs.oasis-open.org/ws-dd/discovery/1.1/wsdd-discovery-1.1-spec.html">WS-Discovery 1.1</a>, <a href="http://docs.oasis-open.org/ws-dd/discovery/1.1/cd-01/wsdd-discovery-1.1-spec-cd-01.html">WS-Discovery CD1</a> (committee draft), and <a href="http://schemas.xmlsoap.org/ws/2005/04/discovery/">WS-Discovery April 2005</a>. They reside in different namespaces, yet have almost identical set of elements and functionality. Different namespaces means different service contracts, but there are no contract types in WCF Discovery assembly (System.ServiceModel.Discovery.dll). In fact those types exist as "internal" interfaces which are implemented in AnnouncementEndpoint, DiscoveryService or DiscoveryProxy.</li>
<li>The trickiest part is that the contract type differs when the binding supports request-reply and when the binding supports duplex. I got request-reply style discovery (actually only Find operation) working, but not for duplex discovery yet so far. Actually, this complexity affects all over the API (indirectly).</li>
</ul>

<h3>Routing</h3>

<p>Actually our WCF Routing implementation had been there since Mono 2.6 and <a href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-13-wcf-40-routing.html">I have already wrote about it</a>, so I don't write duplicates here.</p>

<p>Routing configuration types are implemented, so at some stage it will be completed when some people (or we) would like to use it in practice.</p>

<h3>Other tasks</h3>

<p>REST improvements is sort of on our stack, but I have no concrete plan to work on it yet. It also applies to some new features such as receive context. WF4 support too, but it's very different as we don't have WF4 itself. BTW WF4 is made into System.ServiceModel.dll and now it messed me a lot by injecting a lot of <a href="http://go-mono.com/status/status.aspx?reference=4.0&amp;profile=4.0&amp;assembly=System.ServiceModel">our class status pages</a>. As compared to <a href="http://go-mono.com/status/status.aspx?reference=3.5&amp;profile=2.0&amp;assembly=System.ServiceModel">that of 3.5</a>, the number of missings looks quite big, but we don't lack new features that much.</p>

<p>And, while I wrote about 4.0, my primary hacking area is 3.0 stack. I'm likely go back to components that make up WSHttpBinding and further ones once I achieved duplex Discovery work.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>ServiceMetadataExtension refactoring story</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2010/06/servicemetadataextension-refactoring-story.html" />
    <id>tag:veritas-vos-liberabit.com,2010:/monogatari//1.100</id>

    <published>2010-06-28T12:23:20Z</published>
    <updated>2010-06-28T14:39:56Z</updated>

    <summary>I had been fixing several bugs in our WCF code these months. Yeah, I kept silent just because it is too boring topic to blog :p One of the most problematic one was ServiceMetadataExtension support, which is for WSDL output...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>I had been fixing several bugs in our WCF code these months. Yeah, I kept silent just because it is too boring topic to blog :p</p>

<p>One of the most problematic one was ServiceMetadataExtension support, which is for WSDL output on the service site (the ones you get when you access to http://yourwebsite/yourservice.svc?wsdl). Yes, surprisingly. You would not understand why that is so problematic.</p>

<p>(0) (re)introduction</p>

<p>For public API wise, I once wrote an <a href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-4-expose-and-consume-wsdls.html">entry-level entry for entrypoint to service metadata support</a> last year. I didn't give any explanation on its internals at all. Now it's time.</p>

<p>A simple code for hosting a WCF service with metadata support would look like:</p>

<pre>
var host = new ServiceHost (typeof (FooService), new Uri (uri));
host.AddServiceEndpoint (typeof (ITestService),
    new BasicHttpBinding (),
    new Uri ("", UriKind.Relative));
host.Description.Behaviors.Add (
    new ServiceMetadataBehavior () { HttpGetEnabled = true });
host.Open ();
</pre>

<p>Today, in the example above, what actually creates a working service listener is only the last line: host.Open (); only the last line matters. I explain what it's doing there, step by step.</p>

<p>(1) ServiceHostBase and Binding</p>

<p>First, I'll explain what ServiceHostBase supports and what you can do only with Binding.</p>

<p>Basically, ServiceHost(Base) manages more than one service "endpoint". You can call "AddServiceEndpoint" on the same host multiple times. A service endpoint is a set of an "endpoint address", a "binding" and a "service contract". You can implement multiple service contract interface within a service type (FooService) and serve requests to different interfaces at different endpoint URIs (addresses), using the same or different binding. A binding can be things like BasicHttpBinding, NetTcpBinding, WebHttpBinding, WSHttpBinding (not supported in mono yet) or anything that derives from <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.binding.aspx">Binding</a>.</p>

<p>You might know that Binding class has a method that creates an IChannelListener object that is to actually listen for requests. Actually, to receive requests in <a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.channels.message.aspx">Message</a> form, you don't have to even use ServiceHost. Instead, you can do this:</p>

<pre>
var binding = new BasicHttpBinding ();
IChannelListener&lt;IReplyChannel&gt; listener =
   binding.BuildChannelListener&lt;IReplyChannel&gt; (
      new Uri ("http://localhost:8080/"));
listener.Open ();
IReplyChannel ch = listener.AcceptChannel ();
ch.Open ();
RequestContext ctx = ch.ReceiveRequest ();
</pre>

<p>RequestContext has a request Message that is created from the HTTP SOAP request it received. You can use Reply(Message) method to return a message in whatever form you want.</p>

<p>You wouldn't find it very useful. You'd rather use strongly-typed services instead so that you don't have to get messes by Message object. Also you wouldn't like to call ReceiveRequest() every time explicitly. Hence, there is ServiceHost(Base). It handles those tasks.</p>

<p>(2) ChannelDispatcher and EndpointDispatcher basics</p>

<p>When ServiceHostBase.Open() is called, the host creates a set of "<a href="http://msdn.microsoft.com/en-us/library/system.servicemodel.servicehostbase.channeldispatchers.aspx">ChannelDispatchers</a>" in the host. A channel dispatcher is created for each Binding used in the ServiceHostBase (actually for each of its service endpoints).</p>

<p>A ChannelDispatcher manages an IChannelListener created from Binding.BuildChannelListener&lt;TChannel&gt; method. TChannel can be something other than IReplyChannel, but I don't explain it here (not primary topic today).</p>

<p>A ChannelDispatcher holds one or more "endpoint". In ServiceHostBase, there could be multiple ServiceEndpoints and they have a Binding and an EndpointAddress. Actually the Binding instance can be shared, and in such case, those ServiceEndpoints that shares the same Binding also shares the same ChannelDispatcher.</p>

<p>In ChannelDispatcher, the set of endpoints is represented as Endpoints property and an endpoint becomes an EndpointDispatcher. EndpointDispatcher is hence bound to a contract. When a request to the channel listener arrives (e.g. HTTP request), the ChannelDispatcher has to determine which "endpoint" (EndpointDispatcher) should process the request. Usually it is determined by its ContractFilter and AddressFilter properties, and since usually service endpoint URIs differ, it does not matter much (Use "/foo" for IFooService and "/bar" for IBarService.</p>

<p>... well, I wrote "basics". Yes, it is basic part. The core part starts from here.</p>

<p>(3) IMetadataExchange, ServiceMetadataBehavior and ServiceMetadataExtension</p>

<p>With BasicHttpBinding, an IChannelListener is created for HTTP scheme, and its listening URI is typically a local HTTP URI. In mono, it is either done by ASP.NET (xsp) or HttpListener (non-ASP.NET). In both cases, the services blocks the listening URI, and if we simply try to serve WSDLs using another HttpListener, there is no more room. Since WSDL requests could be sent to the same URI of the service itself, typically only differentiating the query parameter, there sould be some trick. (Do you understand it's getting messier?)</p>

<p>Another complication factory is that there is ServiceMetadataBehavior and ServiceMetadataExtension that have some Binding and Uri properties and show capability of handling "metadata exchange" requests. So it's not only about WSDL. Its endpoints must be exposed at users' will.</p>

<p>Interestingly, MetadataExchangeBindings class exposes a couple of static methods that creates a Binding for mex endpoints. And they are actually used by ServiceMetadataExtension, that is an IExtension for ServiceHostBase and realizes ServiceMetadataBehavior's requirements. Since Binding instance are different, it can create another IChannelListener, which typically has the identical listen URI as the service endpoint itself has.</p>

<p>The different Binding instance results in different ChannelDispatcher in the ServiceHostBase. I was originally aware of the fact that when the ServiceHostBase is opened there are two ChannelDispatchers (the reason came later). Different channel disptatchers have (again) different IChannelListener instances. And they still point to the same listen URI.</p>

<p>That's problematic. It makes request dispatching difficult. To make it worse, ChannelDispatcher has MessageVersion property. If they resided in the same ChannelDispatcher, it would have been easier since we could use message filters to select appropriate EndpointDispatcher. HTTP request interpretation varies dependin on the target MessageVersion. So the target ChannelDispatcher and EndpointDispatcher must be selected before IChannelListener.ReceiveContext() is done.</p>

<p>(4) HTTP listener manager</p>

<p>Hence we have to create another management layer for HTTP channel listener to reuse the same HttpListener (and some equivalent management layer for ASP.NET). Actually <a href="http://mono-project.com/WCF#Brief_History">when Mainsoft hackers were working on it</a>, they were aware of this issue, and created a management layer. It mostly worked until we reached the point that we have to handle more strict differentiation.</p>

<p>Basically, we determine if the request is GET and if the target URL matches the wsdl GET URL, then it is for WSDL. Actually there is ServiceDebugBehavior so we also handle it (if you omit "?wsdl" query parameter in your HTTP request, you'll see some "help page" for the service. It is what ServiceDebugBehavior is for).</p>

<p>BUT, we can't bindly determine such requests as for WSDLs. Do you remember there is WebHttpBinding? With this binding, you can access services by UriTemplate, and it is todally done by GET request (with no request stream). Whenever applicable, we should handle requests to the RESTful services within the binding. Interestingly, WebHttpBinding uses WebHttpBehavior to adjust endpoint behaviors, and it actually raises its EndointDispatcher's FilterPriority(!). So IF the endpoint dispatcher is in the same ChannelDispatcher as ServiceMetadataBehavior yields, there was no problem. Sadly, WebHttpBinding is, again, a different binding that ServiceMetadataBehavior gives, so it creates different ChannelDispatcher (as BasicHttpBinding does).</p>

<p>To get the higher priority settings working, we have to "hack" the order of searching appropriate ChannelDispatcher to dispatch an HTTP request, by its <em>Endpoints</em> (EndpointDispatchers).</p>

<p>All of those behaviors cannot be completely done within WCF public API. So, ServiceMetadataBehavior and ServiceMetadataExtension are special. You cannot create functionally-equivalent one without giving up some aspects (e.g. it would be able to be done if you don't allow hosting WSDL on the same URI as the service is listening).</p>

<p>(5) done</p>

<p>It had been a longstanding issue that attacked me over and over again (fix->regress->fix->regress...), and history may repeat, but I rewrote the HTTP listener stack and relevant stuff last week, it should work today, hopefully in more reliable state. And since that fixes I feel much comfortable than those annoyed days in my hacking life :)</p>
]]>
        

    </content>
</entry>

<entry>
    <title>initial System.Xaml work</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2010/04/initial-systemxaml-work.html" />
    <id>tag:veritas-vos-liberabit.com,2010:/monogatari//1.99</id>

    <published>2010-04-16T16:58:42Z</published>
    <updated>2010-04-16T17:17:50Z</updated>

    <summary>These days I have been running away from WCF and hacking new System.Xaml.dll which is new in .NET 4.0 last week. I needed some break and fresh air. It is already in mcs tree, and not a few of them...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>These days I have been running away from WCF and hacking new System.Xaml.dll which is new in .NET 4.0 last week. I needed some break and fresh air.</p>

<p>It is already <a href="http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/System.Xaml/">in mcs tree</a>, and not a few of them are <a href="http://go-mono.com/status/status.aspx?reference=4.0&amp;profile=4.0&amp;assembly=System.Xaml">implemented</a> and already working, though there's a lot of things left to do.</p>

<p>In .NET land, there seems to be some class libs such as WPF and new Workflow that depend on it. And I'm guessing it could be reused for some sort of my own designing tool.</p>

<p>My primary work area is still WCF so I won't be able to finish it soon, but I hope I get it practically working by the next 2.8 release (which is not in certain scope yet).</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 13: WCF 4.0 Routing</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-13-wcf-40-routing.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.98</id>

    <published>2009-12-28T09:00:00Z</published>
    <updated>2009-12-28T09:20:19Z</updated>

    <summary>While we don&apos;t have some significant parts of WCF 3.0 stack such as working message security, we have some new stuff, like WebHttpBinding I explained on Day 9. It also applies to WCF 4.0. We have new routing stack. WCF...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>While we don't have some significant parts of WCF 3.0 stack such as working message security, we have some new stuff, like WebHttpBinding I explained on Day 9. It also applies to WCF 4.0. We have new routing stack.</p>

<p>WCF router support is only in SVN trunk, in System.ServiceModel.Routing assembly, mostly in System.ServiceModel.Routing namespace. Note that .NET 4.0 is still in beta, so things may change as .NET 4 development goes on.</p>

<h3><b>Router usage</b></h3>

<p>Message router is to dispatch messages that it received from clients, to certain servers. A WCF router is a WCF service for router client users, while the router works as a WCF client for routed services (which may not be WCF).</p>

<p>Routing design is almost simple: a WCF router service has a table of a message filter that is used to test if a message matches it or not, and a set of endpoints to dispatch messages it received. The table is represented as MessageFilterTable&lt;MessageFilter,IEnumerable&lt;ServiceEndpoint&gt;&gt;.</p>

<p>(Usually just one service endpoint is enough; simplex or duplex channels may dispatch messages to more than one service endpoints.)</p>

<p>Message router often has to rebuild the input message, like, adjusting message versions and To message header.</p>

<p>I haven't prepared an entire routing example (I tested it with MS sample in 4.0), but router usage would look like:</p>

<pre>
var host = new ServiceHost (typeof (RoutingService));
host.AddServiceEndpoint (
  typeof (IRequestReplyRouter),
  new BasicHttpBinding (),
  new Uri ("http://localhost:8081/router"));
var config = new RoutingConfiguration ();
var clientEndpoint = new ServiceEndpoint (
  ContractDescription.GetContract (typeof (IRequestReplyRouter)),
  new BasicHttpBinding (),
  new EndpointAddress ("http://localhost:8080/service"));
var list = new List&lt;ServiceEndpoint> ();
list.Add (clientEndpoint);
config.FilterTable.Add (new MatchAllMessageFilter (), list);
host.Description.Behaviors.Add (new RoutingBehavior (config));
</pre>

<h3><b>Internals</b></h3>

<p>There is not many things to explain for WCF routing, so I'd explain its internals instead so that some people might want to write similar code for several purposes.</p>

<p>To host a routing service, RoutingService is used. It has four interfaces for several channel interface types;</p>

<ul>
<li>IRequestReplyRouter for typical request-reply channels</li>
<li>ISimplexDatagramRouter for input/output channels</li>
<li>ISimplexSessionRouter for input/output sessions channels</li>
<li>IDuplexSessionRouter for duplex session channels</li>
</ul>

<p>To add routing with a specific table, you'll first have to create the table. It is represented as FilterTable property in RoutingConfiguration class. Once you have created a configured RoutingConfiguration instance, then use RoutingBehavior object, which is of IServiceBehavior interface (a behavioral extension to ServiceDescription, see Day 5 for quick introduction to "service behaviors") and takes RoutingConfiguration as its constructor argument.</p>

<p>Once you have set routing configuration in above manner, then what to do next is to call AddServiceEndpoint() with (1) an interface type I listed above, (2) a binding for the router "(as a) service", and (3) an endpoint address for the router "(as a) service". (1) must be determined as to comply with the routed servers' requirements, and (2) and (3) represent the endpoint information for routers' client (and of course, a client must comply with (1) to properly communicate with the router).</p>

<p>Those four routing interfaces I listed above, all have Message as its one input argument (and output for IRequestReplyChannel). Since the contracts are very generic, a routing service can handle any communication between the client and the routed server (i.e. since they just take Message, it involves no typed serialization regardless of the contract of the routed service).</p>

<p>When a RoutingBehavior is called its ApplyDispatchBehavior() with a  ServiceHostBase argument, it adds RoutingExtension to the service host. Then (1) it updates its service "instance context provider" (IInstanceContextProvider) that instantiates a RoutingService (which has no public constructor) and sets the routing configuration to it, and (2) creates a set of clients for the dispatched services internally. </p>

<p>There is another "endpoint behavior" SoapProcessingBehavior. It takes part in the router-to-service communication and adjusts messages (as I explained above e.g. updating message versions). You don't have to deal with it.</p>

<p>It is in very early stage and in fact I only tried request-reply style router.</p>

<h3><b>Bonus</b></h3>

<p>Our Routing stack should work on .NET 3.5 too. Try "make" under mcs/class/System.ServiceModel.Routing - it will build mcs/class/lib/net<em>2</em>0/System.ServiceModel.Routing.dll i.e. for 2.0 profile. There is nothing new I depended for its underlying layer.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 12: NetPeerTcpBinding</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-12-netpeertcpbinding.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.97</id>

    <published>2009-12-27T15:16:47Z</published>
    <updated>2009-12-27T15:20:32Z</updated>

    <summary>With related to NetTcpBinding, I have also implemented NetPeerTcpBinding, which is based on peer-to-peer communication. NetPeerTcpBinding involves a lot of complicated things, so I&apos;m not likely to explain a lot. Peer to peer channel overview NetPeerTcpBinding itself is a binding...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>With related to NetTcpBinding, I have also implemented NetPeerTcpBinding, which is based on peer-to-peer communication.</p>

<p>NetPeerTcpBinding involves a lot of complicated things, so I'm not likely to explain a lot.</p>

<h3><b>Peer to peer channel overview</b></h3>

<p>NetPeerTcpBinding itself is a binding for duplex messaging with binary message encoders (like NetTcpBinding) and its own transport, namely PeerTransportBindingElement. It also involves a "peer resolver" which is used to manage peer node statuses.</p>

<p>PeerTransportBindingElement is a transport binding element like HttpTransportBindingElement or TcpTransportBindingElement. While HTTP endpoint is a typical http URI (locally it is most likely only about the port), and TCP endpoint is about an IP endpoint (I forgot to mention yesterday, but its URI is like "net.tcp://localhost:808"), peer transport endpoint is about a "mesh" name which is handled by a "peer resolver". Its URI looks like "net.p2p://mymesh/" . Messages are transmitted to all the "peer nodes" in the specified peer "mesh".</p>

<p>(If you read PeerTransportBindingElement API, you'd notice that it takes an IP endpoint for listening peer connections. But it is not the endpoint - peer transport indirectly uses it, unlike an IP endpoint for TCP endpoint.)</p>

<p>Actually, a peer resolver, which is represented as PeerResolverBindingElement, is more inportant to know the actual peer transport destination. On .NET there are (nominally) two ways to "resolve" peer nodes to transmit messages: (1) PNRP, represented as PnrpPeerResolverBindingElement is Windows peer node resolution protocol, and (2) custom resolver, represented as PeerCustomResolverBindingElement, is resolver-instance-by-user peer resolver with IPeerResolverContract and CustomPeerResolverService API.</p>

<p>With PNRP you don't have to specify anything to resolve peers. It is however not available in Mono (PNRP is Windows specific and I haven't spent any time to implement it). With custom resolver, you have to (only) specify a service endpoint (Binding and EndpointAddress) to IPeerResolverContract service, which is typically CustomPeerResolverService.</p>

<p>Having your host is simple. Just create a ServiceHost with CustomPeerResolverService and add a service endpoint for IPeerResolverContract.</p>

<h3><b>Usage example</b></h3>

<p>(NOTE: As it depends on NetTcpBinding and it has some blocking issues right now, this binding does not likely work fine either.)</p>

<p>I haven't written any cool net-peer application beyond simple tests. Instead, I used <a href="http://www.codeproject.com/KB/WCF/Chat_application_using_WC.aspx">chat application</a> which used to be the top Google results for "WCF application". The server isn't really a peer channel server but rather a custom peer resolver, but the clients show basic use of net-peer communication.</p>

<p>The example code makes use of PeerNode and its interface IOnlineStatus.</p>

<h3><b>Implementation internals</b></h3>

<p>The public peer resolver API does not tell much, but its internals are complicated. It has to provide several operations such as, register node to the target mesh (Register), resolve nodes in the target mesh (Resolve), updates node availability statuses (Refresh) and unregister the node from the mesh (Unregister).</p>

<p>Microsoft has a dedicated Windows protocol documentation. The expected peer resolver mechanism is documented as <a href="http://msdn.microsoft.com/en-us/library/cc219558%28PROT.10%29.aspx">[MC-PRCR]</a> and <a href="http://msdn.microsoft.com/en-us/library/cc219453%28PROT.10%29.aspx">[MC-PRCH]</a>.</p>

<p>In .NET, CustomPeerResolverService internally uses PNRP to implement IPeerResolverContract, So, while "nominally" custom peer resolver is one of the two peer resolver kinds, there is actually only PNRP on .NET.</p>

<p>In Mono, I created BasicHttpBinding-based ad-hoc peer resolver service that is launched within a mono process that uses custom resolvers (the internal "LocalPeerResolverService" class in System.ServiceModel.dll implements the service). It checks port 8931 availability, and if it is already used then it premises as if it were occupied by another custom resolver of our implementation. This behavior may change in future versions.</p>

<h3><b>For paranoiac</b></h3>

<p>It is a trivia I found during NetPeerTcpBinding hacking. You cannot expose WSDL for IPeerResolverContract using ServiceMetadataBehavior (see Day 5) because of duplicate global element for 'http://schemas.microsoft.com/net/2006/05/peer:Update' . 99.999% of WCF users wouldn't have to do it though (say, you don't have to implement CustomPeerResolverService).</p>

<p>The reason for this is complicated: it is because RegisterResponseInfo and UpdateInfo have conflicting return element name "Update" (in the same XML namespace) due to its MessageBodyMemberAttribute. That's my guess though - as IPeerResolverContract methods use message contracts for its argument and return value types. But as the contract there wouldn't be other possibilities so it should be almost precise.</p>

<p>The above story is almost nothing for you. But this kind of faulty contract design could happen by chance and it cannot be checked very obviously. The only way I can suggest to try to avoid such problem is to check WSDL generation frequently (like, every time you change the message contract).</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 11: NetTcpBinding</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-11-nettcpbinding.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.96</id>

    <published>2009-12-26T15:33:58Z</published>
    <updated>2009-12-26T15:39:27Z</updated>

    <summary>Until today I have explain only two Bindings (or three): BasicHttpBinding and WebHttpBinding (and CustomBinding if it counts). But as I implied earlier, we have more. Today I&apos;d explain TCP transport and NetTcpBinding and couple of new things. In short,...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Until today I have explain only two Bindings (or three): BasicHttpBinding and WebHttpBinding (and CustomBinding if it counts). But as I implied earlier, we have more. Today I'd explain TCP transport and NetTcpBinding and couple of new things.</p>

<p>In short, NetTcpBinding is WCF-only, non-interoperable binding based on binary messages and TCP transport.</p>

<h3><b>Binary XML serialization</b></h3>

<p>"Binary XML" is not really XML. It is fake, a buzzword. It actually means, a binary representation based on XML Infoset (or something, depending on what it would describe). In WCF land, binary XML usually means an XML binary format used by XML reader and writer from XmlDictionaryReader.CreateBinaryReader() and XmlDictionaryWriter.CreateBinaryWriter().</p>

<p>While we have corresponding implementation since 2005, its data format has been recently published as <a href="http://msdn.microsoft.com/en-us/library/cc219210%28PROT.10%29.aspx">[MC-NBFX]</a> as part of Microsoft's Windows Protocol documentation.</p>

<p>In WCF, there is BinaryMessageEncodingBindingElement that uses this binary XML representation to serialize and deserialize messages. You can explicitly use it as message encoder part of your binding (using CustomBinding) as I did on Day 3. NetTcpBinding uses this one without customization.</p>

<h3><b>Request/Response vs. Duplex</b></h3>

<p>Message transport protocol also involves its own binary representation, but I have to explain "channel types" in prior. Until today I haven't explain about channel types, in other words types of IChannel interface variety - as BasicHttpBinding and WebHttpBinding are both for request-reply style communication. WCF is not only about it - it actually supports:</p>

<ul>
<li>request-reply messaging: represented as IRequestChannel and IReplyChannel. A client sends a request to a server, then the server receives it and sends reply back to the client, and the client receives it.</li>
<li>simplex messaging: represented as IOutputChannel and IInputChannel. A client sends a message to a server, then the server receives it. No further communication is performed.</li>
<li>duplex messaging: represented as IDuplexChannel. Either of the communication sides may perform simplex messaging.</li>
</ul>

<p>They may also involve sessions and in such case they become IFooSessionChannel (e.g. IRequestSessionChannel). To know which kind of messaging is supported by the Binding you are using, you can use CanBuildChannelFactory&lt;TChannel&gt;() method for clients or CanBuildChannelListener&lt;TChannel&gt;() method for servers.</p>

<p>It may look strange, but duplex messaging could be still used to support service method that has both invocation parameters (request) and return value (reply).</p>

<h3><b>TCP binary data exchange</b></h3>

<p>Back to NetTcpBinding, it supports two kinds of above, under different configuration; NetTcpBinding has TransferMode property and it indicates the communication channel style. If the property value is TransferMode.Streamed, then it creates request-reply type channel. If it is TransferMode.Buffered, then it results in duplex channel. While duplex channel could be used for RPC-style service calls, the underlying communication protocol becomes different. So you have to adjust the transfer mode between client and server.</p>

<p>The communication protocol is also documented, as <a href="http://msdn.microsoft.com/en-us/library/cc219293%28PROT.10%29.aspx">[MC-NMF]</a> and some related docs in Windows Protocol documentation.</p>

<h3><b>NetTcpBinding example</b></h3>

<p>Here is an example pair of NetTcpBinding client and server, using buffered == duplex communication mode.</p>

<p>[NOTE] It turned out that I brought some regressions which broke some binary message communication. It has been a while since I have implemented a couple of months ago. I've been fixing some bugs these days.</p>

<pre>
// client
using System;
using System.Xml;
using System.ServiceModel;
using System.ServiceModel.Channels;

public class Test
{
  public static void Main ()
  {
    var binding = new NetTcpBinding ();
    binding.Security.Mode = SecurityMode.None;
    var endpoint = new EndpointAddress ("net.tcp://localhost:8080/");
    var proxy = new ChannelFactory&lt;IFoo> (binding, endpoint).CreateChannel ();
    Console.WriteLine (proxy.Echo ("TEST FOR ECHO"));
    Console.WriteLine (proxy.Add (1000, 2000));
  }
}

[ServiceContract]
public interface IFoo
{
  [OperationContract]
  string Echo (string msg);

  [OperationContract]
  uint Add (uint v1, uint v2);
}
</pre>

<pre>
// service.cs
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

public class Tset
{
  public static void Main ()
  {
    ServiceHost host = new ServiceHost (typeof (Foo));
    NetTcpBinding binding = new NetTcpBinding ();
    binding.Security.Mode = SecurityMode.None;
    var uri = new Uri ("net.tcp://localhost:8080");
    host.AddServiceEndpoint ("IFoo", binding, uri);
    host.Open ();
    Console.WriteLine ("Hit [CR] key to close ...");
    Console.ReadLine ();
    host.Close ();
  }
}

[ServiceContract]
public interface IFoo
{
  [OperationContract]
  string Echo (string msg);

  [OperationContract]
  uint Add (uint v1, uint v2);
}

class Foo : IFoo
{
  public string Echo (string msg)
  {
    return msg;
  }

  public uint Add (uint v1, uint v2)
  {
    return v1 + v2;
  }
}
</pre>

<h3><b>Limitation</b></h3>

<p>.NET NetTcpBinding is actually capable of handling some complicated things such as message security, but we don't provide message security support yet. If you have NetTcpBinding configured to use message security, NetTcpBinding.Security.Mode has to be set as None.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 10: ASP.NET AJAX Integration</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-10-aspnet-ajax-integration.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.95</id>

    <published>2009-12-25T08:30:00Z</published>
    <updated>2009-12-25T08:25:59Z</updated>

    <summary>Well, yes, it continues a bit more... Yesterday I explained WebHttpBinding which is dedicated to REST world. It is however just one aspect of the new REST support in .NET 3.5. Here is another one - you can invoke remote...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Well, yes, it continues a bit more...</p>

<p>Yesterday I explained WebHttpBinding which is dedicated to REST world. It is however just one aspect of the new REST support in .NET 3.5. Here is another one - you can invoke remote WCF services from ASP.NET AJAX.</p>

<h3><b>Javascript proxy generator</b></h3>

<p>What's done here is, basically the same as what ASP.NET AJAX do for System.Web.Services asmx support. In asmx integration land, there is Javascript proxy generator that accesses to the remote service and returns server responses back to Javascript land. The Javascript proxy source is retrieved at http://your.host.name/service.svc/js or http://your.host.name/service.svc/jsdebug (with debugging info).</p>

<p>The implementation is in ProxyGenerator class in ASP.NET AJAX assembly (System.Web.Ext.dll). By using ProxyGenerator.GetClientProxyScript() method, you can see how the raw Javascript proxy code is generated from your service contract, without actually deploying your service at your host.</p>

<p>It matches the Javascript code that you can see at somewhere like: http://your.host.name/service.svc/jsdebug</p>

<h3><b>WebScriptEnablingBehavior</b></h3>

<p>The next question is, how to provide such Javascript proxy at ./js or ./jsdebug for each service (endpoint). When there are two or more services, there will be two or more js proxies (foo.svc/js and bar.svc/js).</p>

<p>To resolve this, there is "WebScriptServiceHostFactory" which adds support for those js proxies for each service endpoint. It internally uses WebScripeEnablingBehavior which is derived from WebHttpBehavior. When WebScriptEnablingBehavior is attached to a service endpoint, it adds a special request "dispatcher" (precisely, EndpointDispatcher) to the host to handle requests to ./js or ./jsdebug as to return js proxy string.</p>

<p>I don't explain the mechanism a lot here, but in case you are curious, ChannelDispatcher, EndpointDispatcher and DispatchRuntime have a lot of customizible things at service host.</p>

<p>(In my previous post, I didn't explain much about WebHttpBehavior, an implementation of IEndpointBehavior. It actually plays the primary role on the REST binding support such as, setting "message formatter" to serialize request parameters using JSON serializer, to bind to and generate parameters from "URI template", etc. etc.)</p>

<p>Anyways, now we have a dedicated endpoint for Javascript for each service endpoint from the service instance. The service instance should be adjusted to use WebHttpBinding which is configured to use JSON as its message format so that the service can communicate with the JS proxy running in users' browser.</p>

<h3><b>ASP.NET hosting</b></h3>

<p>The entire service host setup above is valid to standalone ServiceHost too. But it does not make sense to do so - the primary purpose of those js proxies is reference from ASP.NET AJAX web pages. Hence there is almost no use for standalone hosting.</p>

<p>I don't write a lot to explain how to use &lt;asp:ServiceReference &gt; and proxies in your ASP.NET AJAX web page (Javascript) here - our <a href="https://bugzilla.novell.com/show_bug.cgi?id=525575">bug #525575</a> shows simple usage.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Xmas!</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/xmas.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.94</id>

    <published>2009-12-24T20:18:53Z</published>
    <updated>2009-12-24T20:39:56Z</updated>

    <summary>It&apos;s 5am here so I don&apos;t think I can give long explanation on my hack so I&apos;ll do it in later days, but here is one of my hobby hack of this year: visual MIDI player based on Moonlight desktop....</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>It's 5am here so I don't think I can give long explanation on my hack so I'll do it in later days, but here is one of my hobby hack of this year: visual MIDI player based on Moonlight desktop.</p>

<p><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="mldsp-gtk-2009xmas.png" src="http://veritas-vos-liberabit.com/monogatari/2009/12/25/mldsp-gtk-2009xmas.png" width="764" height="552" class="mt-image-none" style="" /></span></p>

<p>Sources and brief introduction are <a href="http://github.com/atsushieno/mldsp">on github</a>.</p>

<p>Merry Christmas!</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 9: RESTful WebHttpBinding</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-9-restful-webhttpbinding.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.93</id>

    <published>2009-12-24T09:00:00Z</published>
    <updated>2009-12-24T09:35:04Z</updated>

    <summary>REST support has been introduced in .NET 3.5. It includes JSON support for message serialization, and support for RSS and Atom for consuming web feeds (as serialization contract). It is implemented as WebHttpBinding in System.ServiceModel.Web.dll. Unlike some of the topics...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>REST support has been introduced in .NET 3.5. It includes JSON support for message serialization, and support for RSS and Atom for consuming web feeds (as serialization contract). It is implemented as WebHttpBinding in System.ServiceModel.Web.dll.</p>

<p>Unlike some of the topics I wrote earlier, our REST support compatibility for .NET 3.5 is almost feature complete (yes I prefer RESTians than SOAPy people).</p>

<h3><b>URI Templates</b></h3>

<p>REST services have "resources" identified by URLs, like: http://localhost/ShoppingService/Products/by-name/Ruperts<em>Dance</em>Lesson_DVD</p>

<p>While HTTP transport stack is reusable, the existing BasicHttpBinding does not fill such needs - the destination of its request is identified by SOAP request header or HTTP request content body. A dedicated message encoder is required.</p>

<p>The alternative mechanism used for processing such requests in WebHttpBinding is "UriTemplate" which is a syntax based on URI but includes expressions like '{x}'. For example: "/ShoppingService/Products/by-name/{name}"</p>

<p>When a client is to send a request with certain set of parameters, the client first determines the request URI by filling dynamic parts of the URI template. Then the client sends the request to the service. When the service received a request, it tries to determine which operation in the service should handle it, and extract parameter values from the actual request URI. There won't be files at the corresponding destination URI. It's all virtual.</p>

<h3><b>JSON reader, writer, serializer</b></h3>

<p>Requests in WebHttpBinding are created as an URI. Responses in REST services are often returned as JSON. With WebHttpBinding, you can read and write JSON in certain structure - since WCF Messages are serialized as "XML", which strictly means, XmlDictionaryReader/Writer, the JSON input and output are also represented as the XML reader and writer. I don't explain the details, but you can start reading from JsonReaderWriterFactory.</p>

<p>There also is another specialized type for JSON serialization i.e. DataContractJsonSerializer. It reads and writes JSON instead of XML.</p>

<p>JSON serializer could be also used for serializing complex request parameters.</p>

<p>Of course, WebHttpBinding does not always use JSON. Rather, it uses POX (plain old xml) by default.</p>

<h3><b>RSS and Atom serialization</b></h3>

<p>Another typical practice in REST world is use of syndication feeds such as RSS and Atom. WCF 3.5 added support for serialization of those feeds. In System.ServiceModel.Syndication namespace there is a couple of types for data contract serialization of feeds and feed items.</p>

<h3>Operations using WebGet and WebInvoke</h3>

<p>With WebHttpBinding the existing OperationContractAttribute is not sufficient to provide how to host services. A URI template must be associated to each operation. WebGetAttribute or WebInvokeAttribute are used onto an operation method to bind URI template. Though, you don't have to explicitly design the service URI; it will be automatically inferred like: http://...[baseuri]/[operation]?argFoo={argFoo}&amp;argBar={argBar}...</p>

<p>Adding [WebGet] or [WebInvoke] does not automatically work for WCF engine to assure that it is RESTful service. You also have to use either a dedicated channel factory or a service host, or WebHttpBehavior, a custom IEndpointBehavior. While WebHttpBehavior plays the primary role for everything I explained above and more, former approach would be easier.</p>

<p>Now we are ready to write sample code and run.</p>

<pre>
// client
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Web;

[ServiceContract]
public interface IMyService
{
  [OperationContract]
  [WebGet (RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]
  string Greet (string input);
}

public class Test
{
  public static void Main (string [] args)
  {
    string name = args.Length > 0 ? args [0] : "anonymous joe";
    string url = "http://localhost:8080";
    WebHttpBinding b = new WebHttpBinding ();
    var f = new WebChannelFactory<IMyService> (b, new Uri (url));
    IMyService s = f.CreateChannel ();
    Console.WriteLine (s.Greet (name));
  }
}

</pre>

<pre>
// service
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using System.ServiceModel.Web;

[ServiceContract]
public interface IMyService
{
  [OperationContract]
  [WebGet (RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json)]
  string Greet (string input);
}

public class MyService : IMyService
{
  public string Greet (string input)
  {
    return "hola, " + input;
  }
}

public class Test
{
  public static void Main ()
  {
    string url = "http://localhost:8080/";
    WebHttpBinding b = new WebHttpBinding ();
    var host = new WebServiceHost (typeof (MyService), new Uri (url));
    host.AddServiceEndpoint (typeof (IMyService), b, "");
    host.Open ();
    Console.WriteLine ("--- type [CR] to quit ---");
    Console.ReadLine ();
    host.Close ();
  }
}
</pre>

<p>In the example above, I used WebChannelFactory&lt;T&gt; instead of client class which is derived from ClientBase&lt;T&gt;, but as long as you use a gives instance of IMyService from it, its role is almost the same as ClientBase.</p>

<h3><b>Limitations</b></h3>

<p>Sadly WebHttpBinding is not available in Moonlight (nor Silverlight). It is not because the REST style does not fit Silverlight or RIA land in general, but because Silverlight API lacks behavioral extensibility API. I see there is no reason to not add things like IEndpointBehavior, but that's what Microsoft API does.</p>

<p>While WebHttpBinding is more WWW-friendly, it is not always possible to handle RESTful services. To handle JSON objects, it automatically adds type IDs during serialization and expects the IDs on deserialization.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 8: MonoTouch</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-8-monotouch.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.92</id>

    <published>2009-12-23T14:26:39Z</published>
    <updated>2009-12-23T14:29:56Z</updated>

    <summary>WCF is also available in iPhone land. MonoTouch had started based on &quot;2.1&quot; profile of Mono, which is for Moonlight, and then extended its coverage to some .NET API such as System.Web.Services and ADO.NET. Since WCF is part of Moonlight,...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p></p><p>WCF is also available in iPhone land. MonoTouch had started based on "2.1" profile of Mono, which is for Moonlight, and then extended its coverage to some .NET API such as System.Web.Services and ADO.NET. Since WCF is part of Moonlight, it was also possible to get included in MonoTouch.</p>

<h3><b>Example</b></h3>

<p>Here I'm sort of expecting you knowing basic how-to in MonoTouch land. I'm explaining the procedure below as what I did with MonoTouch on Snow Leopard and iPhone SDK 3.1:</p>

<ul>
<li>Edit MainWindow.xib to add a button.
-- Create "MonoTouch application project", say, monotouchwcf
-- Double click MainWindow.xib to open Interface Builder.
-- Select "Window" and add Round Rect Button and Label (drag them onto the Window for each).
-- Select the button and give the button title like "Tap me".
-- Go to library window, select "Classes" tab and select "AppDelegate" which is likely at the top of the list. Add "button" and "label" outlets.
-- Go to IB's main window and select AppDelegate there, and connect its "button" outlet to the actual Round Rect Button on Window. Do the same for "label" output and the actual Label on the Window. Save the XIB and it's done in IB.</li>
<li>Create and add client proxy code
-- Run service like we did for Moonlight.
-- run svcutil to create client proxy like we did for moonlight.
-- Add "output.cs" from svcutil result to the project.</li>
<li>Add service invocation via the client proxy in the application
-- Add reference to System.ServiceModel.dll in the project.
-- Add "using System.ServiceModel" at the top of the source.
-- In Main.cs, add code lines below in FinishedLaunching() method, like below.</li>
<li>Run the app and touch the button.</li>
</ul>

<pre>        public override bool FinishedLaunching (UIApplication app, NSDictionary options)
        {
            // If you have defined a view, add it here:
            // window.AddSubview (navigationController.View);

            window.MakeKeyAndVisible ();

            this.button.TouchDown += delegate {
                var binding = new BasicHttpBinding ();
                var address = new EndpointAddress ("http://192.168.1.3:8080/test.svc");
                var client = new HelloServiceClient (binding, address);
                client.GreetCompleted += delegate(object sender, GreetCompletedEventArgs e) {
                    this.InvokeOnMainThread (delegate {
                        this.label.Text = e.Result;
                    });
                };
                this.label.Text = "sending request...";
                client.GreetAsync ("monotouch");
            };
            return true;
        }
</pre>

<p>Note that:</p>

<ul>
<li>Do not use "localhost" as the remote endpoint address. It is not the iPhone itself but the development machine that runs corresponding WCF service. Use IP directly instead, for example.</li>
<li>Use InvokeOnMainThread() to update the application UI.</li>
</ul><br /><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><a href="http://veritas-vos-liberabit.com/monogatari/assets_c/2009/12/%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%EF%BC%882009-12-23%2023.13.13%EF%BC%89.html" onclick="window.open('http://veritas-vos-liberabit.com/monogatari/assets_c/2009/12/スクリーンショット（2009-12-23 23.13.13）.html','popup','width=1280,height=800,scrollbars=no,resizable=no,toolbar=no,directories=no,location=no,menubar=no,status=no,left=0,top=0'); return false"><img src="http://veritas-vos-liberabit.com/monogatari/assets_c/2009/12/%E3%82%B9%E3%82%AF%E3%83%AA%E3%83%BC%E3%83%B3%E3%82%B7%E3%83%A7%E3%83%83%E3%83%88%EF%BC%882009-12-23%2023.13.13%EF%BC%89-thumb-600x375.png" alt="sshot-mt-wcf.png" class="mt-image-none" style="" width="600" height="375" /></a></span><br />

<h3><b>Some notes on WCF in MonoTouch</b></h3>

<p>The usage in MonoTouch almost the same as Moonlight does, while there is no "async-only" limitation in the runtime. You can use sync operation calls. Though I used event-based async model in the example above. (The future versions of svcutil <em>might</em> stop supporting sync calls due to moonlight proxy generator limitation. But sync client should work at runtime level anyways.)</p>

<p>On the other hand, there is a big limitation in MonoTouch in general - you cannot dynamically generate runnable code. And since WCF often involves dynamic code generation, you have to be caucious to <em>not</em> do it. For example, you have to override ClientBase&lt;T&gt;.CreateChannel() by using ClientBase&lt;T&gt;.ChannelBase&lt;T&gt; . If you don't do that, the default Channel property is generated by ChannelFactory&lt;T&gt;.CreateChannel() method, which dynamically creates an implementation of the contract interface using System.Reflection.Emit API.</p>
<div><br /></div>]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 7: Moonlight</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-7-moonlight.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.91</id>

    <published>2009-12-22T05:43:17Z</published>
    <updated>2009-12-22T05:49:39Z</updated>

    <summary>Our WCF is ready in Moonlight 2.0. It provides Silverlight 2.0 compatibility, and filling 3.0 support should be almost easy (we need to implement things like CookieContainer support etc.). Actually our WCF stack has been improved a lot by the...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Our WCF is ready in <a href="http://mono-project.com/Moonlight">Moonlight</a> 2.0. It provides Silverlight 2.0 compatibility, and filling 3.0 support should be almost easy (we need to implement things like CookieContainer support etc.). Actually our WCF stack has been improved a lot by the moonlight effort (the team gave several bug reports).</p>

<p>I haven't explained how to prepare Moonlight environment. Theis a wiki page for instructions I linked above (I assume it will be frequently updated, so I'm not going to give the anchor to the build instruction section now).</p>

<p>Also, when creating moonlight apps, make sure you have 'moonlight-web-devel' package (in case it is available in your distro) or some sort of equivalents (e.g. "MoonSDK") installed and set up.</p>

<h3><b>Some notes</b></h3>

<ul>
<li>WCF in .NET and WCF in Moonlight are <em>significantly</em> different. We have almost feature complete WCF in Moonlight, while we lack a lot of features in .NET WCF. In WCF only BasicHttpBinding is supported in System.ServiceModel.dll (as Silverlight does).</li>
<li>As I mentioned on Day 5, Moonlight is the land of "async everywhere". So there isn't sync service calls. Operation methods are called with BeginFoo() and EndFoo() instead of Foo(). If you use them, EndFoo() is expected to be called inside AsyncCallback of the BeginFoo() argument. FooAsync() pattern is easier.</li>
<li>Silverlight applications may contain Microsoft's SDK assemblies. They are not what we implemented. For example, System.Xml.Linq.dll, System.Json.dll and System.ServiceModel.PollingDuplex.dll are SDK assemblies. I have never tried the last assembly, so it may or may not work.</li>
<li>Silverlight client can access the services only when it is from allowed domain by the website. "clientaccesspolicy.xml" and "crossdomain.xml" play the key role on the permission (I don't explain their details here, MSDN would give you hints).</li>
</ul>

<h3><b>Example</b></h3>

<p>Now, let's build a simple app and see it's working. (NOTE: Here I use the latest version of svcutil which includes support for event-based async call I explained on Day 5.)</p>

<p>While it is possible to create a Moonlight application from console using "smcs" and "mxap" tools, I take the easiest way to create Moonlight project.</p>

<ul>
<li>Start MonoDevelop (2.2 would be the best; earlier versions that support Moonlight project is fine).</li>
<li>Create a "Moonlight Application project", say, moonlight1. There are App.xaml, App.xaml.cs (folded), Page.xaml and Page.xaml.cs (folded) as the sources.</li>
<li>Just build and run to make sure it works (a web page with moonlight xap, printing "Hello Moon").</li>
<li>Prepare a WCF service which is hosted under xsp2 as explained on Day 6. It is important to host a service on ASP.NET since you have to provide access to "clientaccesspolicy.xml" (explained above). You cannot do it with a standalone ServiceHost at least in simple manner.</li>
<li>Create "clientaccesspolicy.xml" file on the hosted root directory. Moonlight WCF client will try to httpget the file. An example file content is pasted below, which states that it accepts SOAP requests from anywhere.</li>
<li>Create a client proxy explained on Day 5, by running: svcutil -moonlight http://localhost:8080/test.svc/wsdl</li>
<li>Open Page.xaml.cs on MonoDevelop, and add the code below for service invocation. The example means that the result from the SOAP response will be shown as a Javascript alert message when the application is loaded.</li>
<li>Run the Moonlight application project (F5 or F8). Moonlight addin will open your browser and show the test page.</li>
</ul>

<pre>&lt;!-- clientaccesspolicy.xml --&gt;
&lt;access-policy&gt;
  &lt;cross-domain-access&gt;
    &lt;policy&gt;
      &lt;allow-from http-methods="*" http-request-headers="*"&gt;
        &lt;domain uri="*"&gt;
        &lt;/domain&gt;
      &lt;/allow-from&gt;
      &lt;grant-to&gt;
        &lt;resource path="/" include-subpaths="true"&gt;
        &lt;/resource&gt;
      &lt;/grant-to&gt;
    &lt;/policy&gt;
  &lt;/cross-domain-access&gt;
&lt;/access-policy&gt;
</pre>

<pre>// Page.xaml.cs
this.Loaded += delegate {
  var binding = new BasicHttpBinding ();
  var address = new EndpointAddress ("http://localhost:8080/test.svc");
  var client = new HelloServiceClient (binding, address);
  client.GreetCompleted += delegate (object o, GreetCompletedEventArgs e) {
    System.Windows.Browser.HtmlPage.Window.Dispatcher.BeginInvoke (delegate {
        System.Windows.Browser.HtmlPage.Window.Alert (e.Result);
        tb.Text = e.Result;
    });
  };
  client.GreetAsync ("moonlight");
};
</pre>
<br /><span class="mt-enclosure mt-enclosure-image" style="display: inline;"><img alt="moonlight2-wcf-md.png" src="http://veritas-vos-liberabit.com/monogatari/2009/12/22/moonlight2-wcf-md.png" class="mt-image-none" style="" height="564" width="805" /></span><div><br /></div>]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 6: ASP.NET hosting</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-6-aspnet-hosting.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.90</id>

    <published>2009-12-21T08:01:23Z</published>
    <updated>2009-12-25T08:46:46Z</updated>

    <summary>Mono WCF services can be hosted through ASP.NET. Actually, lots of WCF consumers in .NET would be aware only of this path, like, you may be only aware of .svc files and not ServiceHost class. Service configuration through .config files...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Mono WCF services can be hosted through ASP.NET. Actually, lots of WCF consumers in .NET would be aware only of this path, like, you may be only aware of .svc files and not ServiceHost class.</p>

<h3><b>Service configuration through .config files</b></h3>

<p>Until today I haven't explain any of .config file support while lots of WCF introductions do. I personally don't like WCF config support which rather brought confusion (and I was right; WCF 4.0 came with some simplification in this area), but if we want to use ASP.NET, we sort of need to use it.</p>

<p>We partially support service and client configuration by config files. A WCF configuration would look like this:</p>

<pre>
&lt;configuration&gt;
  &lt;system.serviceModel&gt;
    &lt;services&gt;
      &lt;service name="HelloService" behaviorConfiguration="b"&gt;
        &lt;endpoint binding="basicHttpBinding" contract="IHelloService" /&gt;
      &lt;/service&gt;
    &lt;/services&gt;
    &lt;behaviors&gt;
      &lt;serviceBehaviors&gt;
        &lt;behavior name="b"&gt;
          &lt;serviceMetadata httpGetEnabled="true" httpGetUrl="wsdl" /&gt;
        &lt;/behavior&gt;
      &lt;/serviceBehaviors&gt;
    &lt;/behaviors&gt;
  &lt;/system.serviceModel&gt;
&lt;/configuration&gt;
</pre>

<p>By having this as "service.exe.config", you can omit these lines:</p>

<pre>
-    host.AddServiceEndpoint (
-      typeof (IHelloService), binding, address);

-    var meta = new ServiceMetadataBehavior () {
-      HttpGetEnabled = true,
-      HttpGetUrl = new Uri ("wsdl", UriKind.Relative) };
-    host.Description.Behaviors.Add (meta);
</pre>

<p>Note that configuration support is valid only on the full .NET profile. In Moonlight and MonoTouch there is an alternative (and much simpler) way to give configuration ("ServiceReferences.ClientConfig" file). I don't explain it here - try googling ServiceReferences.ClientConfig.</p>

<h3><b>.svc http handler</b></h3>

<p>.svc files in ASP.NET are processed by an IHttpHandler(Factory) to generate a service hosting class that internally starts ServiceHost and serves HTTP requests as a HTTP transport implementation. We do the same.</p>

<p>Now, it's time for instructions. First, create one-liner "test.svc" file as:</p>

<pre>
&lt;%@ServiceHost Service="HelloService, service" %&gt;
</pre>

<p>Then comment out the entire "Test" class from service.cs.</p>

<pre>
+ /*
  public class Test
(...)
  }
+ */
</pre>

<p>Create "bin" directory, and compile the service class into a library this time:</p>

<p>$ mkdir bin</p>

<p>$ gmcs -t:library -out:bin/service.dll service.cs -pkg:wcf</p>

<p>To run the service in ASP.NET, you need a configuration (now that you don't have configured service host in Test class). To do it, use web.config. Copy the example config above:</p>

<p>$ cp service.exe.config web.config</p>

<p>Then run:</p>

<p>$ xsp2</p>

<p>Now your service is hosted at http://localhost:8080/test.svc (note that the URL now ends with "test.svc"). Go to http://localhost:8080/test.svc/wsdl , there should be the WSDL we exposed at Day 5.</p>

<h3><b>Limitations</b></h3>

<p>ASP.NET integration is under some tricky situation to fit with existing HttpListener-based channel implementation, and actually have some safety nets that blocks concurrent calls. It would work, but is not likely to scale so far.</p>

<p>Though, as a HTTP server, xsp outperforms HttpListener a lot, so it may work nicer in the future (unless you hit WCF-specific bugs). The simpler (especially for debugging) is those without xsp. I have to admit that ASP.NET integration is somewhat buggy so far.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 5: expose and consume WSDLs</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-4-expose-and-consume-wsdls.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.88</id>

    <published>2009-12-20T06:42:39Z</published>
    <updated>2009-12-20T07:44:04Z</updated>

    <summary>WCF services can be exposed as a set of WSDL documents, and WCF client classes can be automatically generated by consuming such WSDLs. Today&apos;s topic is our WSDL support. It is not really perfect, but supporting code is there. ServiceDescription...</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>WCF services can be exposed as a set of WSDL documents, and WCF client classes can be automatically generated by consuming such WSDLs. Today's topic is our WSDL support. It is not really perfect, but supporting code is there.</p>

<h3><b>ServiceDescription</b></h3>

<p>When you create a ServiceHost with your service implementation class, WCF creates an object of "ServiceDescription" that describes the service details, such as set of endpoints, debugging support and service throttling. It is exposed as Description property of the ServiceHost instance.</p>

<p>As I explained Day 2 a bit, a service class may implement more than one service contract interfaces. Each service contract in the service is bound to a service endpoint URI (EndpointAddress) and a Binding. This set of A(ddress), B(inding) and C(ontract) are represented as a ServiceEndpoint class. To reflect these, a ServiceDescription has an Endpoints property which is a collection of ServiceEndpoints.</p>

<h3><b>WSDL output and ServiceMetadataBehavior</b></h3>

<p>To explain how to do it, I have to explain "service behaviors". A service behavior, which is represented as IServiceBehavior interface, is to add additional facilities or give behavioral changes to the service. ServiceDescription has a set of IServiceBehavior implementations as Behaviors property.</p>

<p>WSDL output support is represented as one of such an implementation of IServiceBehavior, namely ServiceMetadataBehavior. For example, to enable WSDL output, modify service.cs of Day 2 as:</p>

<pre>-    var host = new ServiceHost (typeof (HelloService));
+    var host = new ServiceHost (typeof (HelloService));
+    var meta = new ServiceMetadataBehavior () {
+      HttpGetEnabled = true,
+      HttpGetUrl = new Uri ("wsdl", UriKind.Relative) };
+    host.Description.Behaviors.Add (meta);
</pre>

<p>Run service.exe, and then visit http://localhost:8080/wsdl in your browser. It will show you the corresponding WSDL.</p>

<h3><b>svcutil.exe and clients</b></h3>

<p>On the client side, it is non-coding land. In the example in Day 2, we wrote "HelloClient" class by our own. However, by consuming the service's WSDL, we actually don't have to write that class. Instead, we can use "svcutil" tool. It is based on the same tool in Windows SDK (SvcUtil.exe).</p>

<p>To use it, start service.exe first and then run:</p>

<pre>$ svcutil http://localhost:8080/wsdl
</pre>

<p>So far it does not exactly behave like svcutil.exe in .NET, but gives resulting C# code as "output.cs".</p>

<p>Then, edit client.cs of Day 2 as:</p>

<pre>- [ServiceContract]
- public interface IHelloService
- {
-   [OperationContract]
-   string Greet (string name);
- }

-    var client = new HelloClient (binding, address);
+    var client = new HelloServiceClient (binding, address);
</pre>

<p>Then compile two sources into an exe:</p>

<p>$ gmcs client.cs output.cs</p>

<p>The resulting client.exe should work as the earlier client.exe used to do.</p>

<p>As of the end of year 2009, svcutil and WSDL support is in somewhat early stage, namely:</p>

<ul>
<li>It does not give default constructor that should give the expected binding and the endpoint address. You'll have to explicitly supply them so far.</li>
<li>There is no configuration output.</li>
<li>I am aware of some bogus behaviors of HTTP(s) GET URI patterns.</li>
</ul>

<h3><b>Asynchronous service contracts</b></h3>

<p>Our svcutil can also generate service contracts in "asynchronous" pattern. Use -async command line option, and you'll get an interface like:</p>

<pre>$ svcutil http://localhost:8080/wsdl -async
</pre>

<pre>[ServiceContract]
public interface IHelloService
{
    [OperationContract (AsyncPattern = true)]
    IAsyncResult BeginGreet (string name,
                 AsyncCallback callback,
                 object state);
    string EndGreet (IAsyncResult result);
}
</pre>

<p>Today in svn trunk I added support for another async alternative: event-based async operation pattern, which is at first introduced for Silverlight and then incorporated to .NET too. The corresponding option is "-targetClientVersion:Version35" or "-tcv:Version35" (aligned to .NET's svcutil.exe). Use it along with "-async" option. This asynchronous pattern is implemented in the (auto-generated) client class and is used like:</p>

<pre>$ svcutil http://localhost:8080/wsdl -async -tcv:Version35
</pre>

<pre>public class Test
{
  public static void Main (string [] args)
  {
    string name = args.Length &gt; 0 ? args [0] : "anonymous joe";
    var binding = new BasicHttpBinding ();
    var address = new EndpointAddress ("http://localhost:8080/");
    var client = new HelloServiceClient (binding, address);
    client.GreetCompleted += delegate (object o, GreetCompletedEventArgs e) {
      Console.WriteLine (e.Result);
    };
    client.GreetAsync (name);
    Console.WriteLine ("Type [CR] to quit");
    Console.ReadLine ();
  }
}
</pre>

<p>Again, note that the latter pattern is available only in trunk so far.</p>

<h3><b>Client proxies for Moonlight and MonoTouch</b></h3>

<p>WSDL support is mostly about full .NET compatibility and not for Moonlight or MonoTouch. You cannot do any of above for those limited environment.</p>

<p>In Silverlight, client proxies are generated by "slsvcutil.exe", which is svcutil.exe for Silverlight.</p>

<p>However, creating client proxies using svcutil is partly possible and especially recommended for MonoTouch. Unlike slsvcutil.exe, we have some extra command line options on svcutil.exe itself:</p>

<ul>
<li>-moonlight option gives you client proxies that uses Silverlight-only Channel implementation i.e. ClientBase&lt;T&gt;.ChannelBase&lt;T&amp;gt . It is used to provide async operation support as well as eliminating need for dynamic code generation.</li>
<li>-monotouch option is almost the same as -moonlight (it is especially important for MonoTouch to eliminate dynamic code generation), <del>but still gives you synchronous call proxy methods</del><ins>today it became unavailable. It may be temporarily, or might be permanently. It is due to some limitation in our svcutil. I'll sort out at some stage.</ins></li>
</ul>

<p>Note that Silverlight usually uses the event-based asynchronous pattern explained above, and it is (I repeat again) available only in svn trunk.</p>

<p>We don't have corresponding feature in MonoDevelop yet ("Add Service Reference" in Visual Studio), but it will be done at some stage. So far, live with svcutil.exe or manually write proxies.</p>
]]>
        

    </content>
</entry>

<entry>
    <title>Mono WCF Advent Day 4: Message and data contract</title>
    <link rel="alternate" type="text/html" href="http://veritas-vos-liberabit.com/monogatari/2009/12/mono-wcf-advent-day-4-message-and-data-contract.html" />
    <id>tag:veritas-vos-liberabit.com,2009:/monogatari//1.89</id>

    <published>2009-12-19T05:03:41Z</published>
    <updated>2009-12-20T02:54:49Z</updated>

    <summary>Until today I have carefully avoided any use of complex data transfer than mere string. Our WCF stack is however ready to use complex data than just a string. Data contract serialization Messaging system is tied to message serialization system....</summary>
    <author>
        <name>Atsushi Eno</name>
        
    </author>
    
    
    <content type="html" xml:lang="en" xml:base="http://veritas-vos-liberabit.com/monogatari/">
        <![CDATA[<p>Until today I have carefully avoided any use of complex data transfer than mere string. Our WCF stack is however ready to use complex data than just a string.</p>

<h3><b>Data contract serialization</b></h3>

<p>Messaging system is tied to message serialization system. WCF has "data contract" as its own data serialization framework. Objects that are attributed as [DataContractAttribute] are serialized in its own manner i.e. only fields and properties attributed as [DataMemberAttribute] are written to the serialization output.</p>

<p>A simple usage example:</p>

<pre>[DataContract]
public class UserInfo
{
  [DataMember]
  public string UserName { get; set; }
  [DataMember] // whoa, are you planning to send it via SOAP?
  public string Password { get; set; }

  public string Annotation { get; set; }
}
</pre>

In the example ablve, only UserName and Password will be serialized.

Data contract is actually sort of fake, you can serialize and deserialize non-datacontract objects. For example,

<ul><li>- Some types are serialized as "primitive". For example, XmlQualifiedName, Guid, UniqueId, DateTimeOffset, TimeSpan ...
</li><li>- [Serializable] objects are serialized only by its fields. You can use System.Net.IPAddress. (It is actually used in peer-to-peer connection internals.) [UPDATE] this is not working in moonlight 2.0. It needs some backporting.[/UPDATE]
</li><li>- By default, public fields and properties are serialized, unless it is marked as [IgnoreDataMember]. It should cover large amount of the classes in .NET land.
</li></ul>

We support DataContractSerializer, while we don't support "NetDataContractSerializer" which is an alternative serializer in .NET WCF to support complete(?) CLR object serialization (yet). There is actually another data contract serializer. I'll revisit it in later days.

<br /><br />Serialization output is written to XmlDictionaryWriter, which is a derived implementation of XmlWriter, and deserialization input is read from XmlDictionaryReader, which is based on XmlReader. While they are "XML" reader and writer, anything that is based on XmlReader and XmlWriter should work. I will introduce JSON reader and writer in later days.<br /><br /><h3>Message</h3>

In WCF, messages in the client-server system is represented as System.ServiceModel.Channels.Message class. A Message is originally mapped to the notion of a SOAP Envelope. A Message contains a set of Headers, Body (again, SOAP Header and SOAP Body), and message Properties (it is not transmitted).

In an operation contract, Message can be used as its input and output, like:<br /><br />

<pre>[ServiceContract]
public interface IRequestAnything
{
    [OperationContract]
    Message Request (Message input);
}
</pre>

<p>In this contract you can send and receive any kind of Messages. If your input and/or output do not fit any of the supported serialization strategy and you are willing to handle them by yourself, it is useful.</p>

<p>A Message can be created by a lot of CreateMessage() method overloads. For example, CreateMessage(messageVersion, soapAction, bodyXmlReader) is useful to create a message from server replies, and CreateMessage(MessageVersion, soapAction, bodyObject) is useful to create a message from a serializable object (for both cases you wouldn't have to do it usually though). WCF internally uses those methods to create and read messages.</p>

<p>A Message also has a set of "properties". They do not show up in outputs, but may control the message transfer, or serialization. For example, you can use  HttpRequestMessageProperty object which controls HTTP transport, for example by adding your own HTTP request header items.</p>

<h3><b>Message contract</b></h3>

<p>The last one I explain here is sorta confusing; you can sort of control the actual creation of messages by using "message contract", represented as [MessageContract] attribute. It is placed on sort of a data class where instances of it are to be serialized and deserialized.</p>

<p>Under message contract, members of the class with [MessageHeader] attribute are processed as message Headers, and members with [MessageBody] become the Body of the message. They can be any type and serialized using data contract serializer explained above. So, its' sort of confusing, but the usage is rather about message serialization, not arbitrary object serialization.</p>

<h3><b>Missing stuff</b></h3>

<p>In mono 2.6, I haven't finished (actually even haven't started) working on message fault contract support (such as FaultContractInfos). Things like MessageFault should work, but any further complicated contract stuff is left untouched yet.</p>
]]>
        

    </content>
</entry>

</feed>
