WCF sets the default message size really low. I think the reason they did this was to slap the face of all the lazy developers out there. Just to wake them up. A limit that low is almost guaranteed to be hit in development rather than production. That is the WCF team saying "SMACK! Pay attention, what you do here is very important to the performance of the app."

There are three ways of fixing this "problem".

  1. Increase the maximum message size This will only get you so far, and should only be used when two conditions apply. The first is that you know the maximum size a message can be, and the second is that that maximum size multiplied by the maximum number of simultaneous messages can fit in the lowest amount of memory that your service application can run with.
  2. Chunk the message into smaller messages This is especially a good solution when ordering is not needed. For example if I was going to send my CD collection over the wire I might chose to chunk it. If you happen to get the Beatles before ABBA (cough, um… that one must be my wife’s CD) it is no big deal. However if you were to chunk a file, there could be problems because if chunk #3 arrived before chunk #2 you now have a corrupted file.
  3. Turn on streaming This one should really only be used if you are simply copying that network stream to some other input / output device, like your monitor or a hard drive. To do this means you have to have a special contract which takes a stream as the single message body.

Let’s take a simple file storage service as an example. The Store file could have a single Stream parameter, but what about the other information that needs to be passed along with the Stream, like the name and author? The contract will probably end up looking something like this:

	[MessageContract]
	public class FileMessage
	{
		[MessageHeader]
		public string fileName;

		[MessageBodyMember]
		public Stream fileStream;

		public FileMessage()
		{
		}

		public FileMessage(string fileName, Stream fileStream)
		{
			this.fileName = fileName;
			this.fileStream = fileStream;
		}
	}

	[ServiceContract]
	public interface IFileService
	{
		[OperationContract]
		void StoreFile(FileMessage fileMessage);
		[OperationContract]
		Stream GetFile(string fileName);
	}

When you go to implement the contract people often wonder when to close the stream. The advice given in "Programming WCF Services" is a little confusing (and not entirely correct) around this topic. Page 204 states:

When the client passes a request stream to the service, the service may read from the stream long after the client is gone. The client has no way of knowing when the service is done using the stream. Consequently the client should not close the stream— WCF will automatically close the client-side stream once the service is done using the stream.

A similar problem exists when the client interacts with a response stream. The stream was produced on the service side, and yet the service does not know when the client is done using the stream, nor can WCF help, because it has no idea what the client is doing with the stream. The client is always responsible for closing reply streams.

The first paragraph is not really correct because if the client is calling the service synchronously then it knows exactly when to close the stream. It turns out that the second paragraph is the only case when you don’t close the stream. So really to summarize – Always close the stream, except when you don’t know when to close it. The only time that is true is when the stream is being returned from the service and you don’t know when it has finished being written into the outgoing buffer. Here is the code first on the client side:

using (var fs = new FileStream(uploadPath, FileMode.Open, FileAccess.Read))
{
	client.StoreFile(new FileMessage(uploadPath, fs));
} // NOTE: the stream is closed here
...
using (Stream s = client.GetFile(downloadFileName))
{
	// do something with the stream
} //NOTE: the stream is closed here

Then on the service side:

public Stream GetFile(string fileName)
{
	// this is the only place that we don't close the stream
	// WCF does it for us in this case, whenever it is done sending the message
	return new FileStream(fileName, FileMode.Open);
}

public void StoreFile(FileMessage msg)
{
	// do something with the stream
	msg.fileStream.Close();
}

I have had the pleasure (or excruciating pain depending on the point of view) of interviewing a lot of candidates for the various technical positions that are open at my company. One of the questions I often ask, “If I have two machines and I want to communicate between them, what are some of my options in .NET?” Far too often when the candidate mentions .NET Remoting as one of the answers, they throw in a side comment like: “although it is an obsolete technology,” or “even though you aren’t supposed to use that anymore,” or “with WCF coming out I believe web services are the preferred method.”

Having played with both .NET Remoting *and* WCF, I fundamentally disagreed with the candidates. I think there is a pretty easy upgrade path between the two. So I set out to prove:

  1. Which technology would be easier to upgrade to WCF?
  2. What are the guidelines that one should follow when choosing a inter-machine communications mechanism (assuming you can’t use WCF, yet)?

I was pre-biased so I guess I should mention that in case I skewed the results in some subconscious way. I felt that the answer to #1 would be a wash, and that #2 would depend solely on things like whether .NET was guaranteed to be running on both endpoints, and whether there was a firewall between the machines.

.NET Remoting

First I created a .NET Remoting solution. I used a Console application for the server, and a Windows forms application for the client, just to make sure that it wasn’t easier to upgrade one versus the other. Per best practices I split the interface into a separate class library which I referenced from both. I also stored the Remoting configuration in the app.config files for both the client and the server.  I chose the standard calculator interface, because that had about the right number of methods (according to Juval Lowy of IDesign, a good number of methods for an interface is 3-5 and if you reflect on .NET itself, that is what you will find). So my interface had the standard Add, Subtract, Multiply and Divide methods.  Once I had that working, I started changing it to use WCF, while taking careful notes of what I had to change.

First things first, I modified the interface by adding the service and operation contract attributes. The interface now looked like this (with new lines in bold):

using System;
using System.ServiceModel;

namespace Calculator
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        int Add(int n1, int n2);
        [OperationContract]
        int Subtract(int n1, int n2);
        [OperationContract]
        int Multiply(int n1, int n2);
        [OperationContract]
        double Divide(int n1, int n2);
    }
}
  Lines Changed Lines Added Lines Removed
here 0 6 0
total 0 6 0

Next on the server I had to change both the config file and the server class itself. I also had to add the ServiceModel project reference again.

using System;
using System.Runtime.Remoting;
using System.ServiceModel;

namespace Calculator
{
    class Program
    {
        static void Main(string[] args)
        {
            RemotingConfiguration.Configure("CalcServer.exe.config", true);
            ServiceHost serviceHost = new ServiceHost(typeof(CalcServer))
            serviceHost.Open();
            Console.WriteLine("Calculator running (press any key to close)");
            Console.ReadKey();
        }
    }
}

The line that actually fetches the configuration information changed from Configure to a line starting the host, something that was implied before.

  Lines Changed Lines Added Lines Removed
here 2 1 0
total 6 7 0

In the server config file the damage was:

<configuration>
  <system.runtime.remoting>
  <system.serviceModel>
    <application name="CalcServer">
    <services>
      <wellknown mode="SingleCall" objectUri="Calc" 
        type="Calculator.CalcServer, CalcServer" />
      <service name="Calculator.CalcServer">
        <endpoint address="net.tcp://localhost:123/CalcServer/Calc"
                  binding="netTcpBinding"
                  contract="Calculator.ICalculator" />
      </service>
      <channels>
        <channel ref="tcp server" port="123" />
      </channels>
    </application>
    </services>
  </system.runtime.remoting>
  </system.serviceModel>
</configuration>

Notice the near 1-1 mapping.

system.runtime.remoting -> system.serviceModel

application -> services

wellknown[@type] -> service[@name]

channel -> endpoint

Actually wellknown and channel morphed into a concept of service and endpoint.  WellKnown is really representing the type of the service being hosted, as is service.  But it includes two other pieces of information: the “mode”, which is described in WCF using a behavior, and the objectUri which is shifted into part of the endpoint address in WCF.  Channel describes the rest of the features present on the endpoint element.  This was a tricky one to count, and I guess this is were my biases come into play.   Because the lines were semantically the same I counted them as changes per the transforms listed above, the add of an end service tag, and the removal of the begin and end channel tags.

  Lines Changed Lines Added Lines Removed
here 6 1 2
total 12 8 2

One more line of code should change on the server side.
The CalcServer object itself also no longer needs to derive from MarshalByRefObject.

public class CalcServer : MarshalByRefObject, ICalculator

This brings the totals to:

  Lines Changed Lines Added Lines Removed
here 1 0 0
total 13 8 2

On to the client. At this point you should be getting the idea.
Almost everything in .NET Remoting has a corresponding object in WCF.

For the client we need to change the buttonAdd_Click event to look like this:

private void buttonAdd_Click(object sender, EventArgs e)
{
    double num1 = double.Parse(textBox1.Text);
    double num2 = double.Parse(textBox2.Text);

    RemotingConfiguration.Configure("CalcClient.exe.config", false);
    WellKnownClientTypeEntry[] entries = RemotingConfiguration.GetRegisteredWellKnownClientTypes();
    ICalculator calc = (ICalculator)Activator.GetObject(typeof(ICalculator), entries[0].ObjectUrl);

    ChannelFactory<ICalculator> factory = new ChannelFactory<ICalculator>("Calc");
    ICalculator calc = factory.CreateChannel();

    double result = calc.Add(num1, num2);
    textBoxResult.Text = result.ToString();
}

Two lines were changed and one was removed. Really the 3 lines in remoting were morphed into the 2 lines of WCF.

  Lines Changed Lines Added Lines Removed
here 2 0 1
total 15 8 3

The client configuration file changed almost exactly like the server one did, other than the endpoint having a name.

<configuration>
  <system.runtime.remoting>
  <system.serviceModel>
    <application name="CalcClient">
    <client>
      <endpoint name="Calc" address="net.tcp://localhost:123/CalcServer/Calc"
                binding="netTcpBinding" contract="Calculator.ICalculator" />
      <wellknown url="tcp://localhost:123/CalcServer/Calc" type="Calculator.ICalculator, CalcInterface" />
      <channels>
        <channel ref="tcp client" />
      </channels>
    </client>
    </application>
  </system.runtime.remoting>
  </system.serviceModel>
</configuration>
  Lines Changed Lines Added Lines Removed
here 4 0 4
total 19 8 7

And there we have it, so a total of (19+8+7) = 34 changes in all…

ASMX Web Services

Most people don’t really use interfaces for WebServices (although it is possible), so I will show the default (although sub-optimal) implementation.

First I need to change the attribute names:

[WebService(Namespace = "urn:brainhz:calc")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ServiceContract]
public class CalcService : System.Web.Services.WebService
{
    [WebMethod]
    [OperationContract]
    public int Add(int n1, int n2)
    {
        return n1 + n2;
    }

    [WebMethod]
    [OperationContract]
    public int Subtract(int n1, int n2)
    {
        return n1 - n2;
    }

    [WebMethod]
    [OperationContract]
    public int Multiply(int n1, int n2)
    {
        return n1 * n2;
    }

    [WebMethod]
    [OperationContract]
    public double Divide(int n1, int n2)
    {
        return (double)n1 / (double)n2;
    }
}

So the question is: does WebService or WebServiceBinding to ServiceContract count as removing and adding or a changed line?  I decided that the intent was not the same, and in fact Indigo has attributes for [ServiceBehavior] to control things like the namespaces.  Then the same question for WebMethod to OperationContract.  Here I decided that the intent was the same (opting in methods) so I counted them as changed lines.  I counted 2 lines removed, one line added and 4 lines changed.

  Lines Changed Lines Added Lines Removed
here 4 1 2
total 4 1 2

Next the config file:

<configuration>
  <system.web>
    ...
  </system.web>
  <system.serviceModel>
    <services>
      <service name="CalcService" behaviorConfiguration="mex" >
        <endpoint address=" " 
          binding="basicHttpBinding" 
          contract="CalcService"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="mex">
          <serviceMetadata httpGetEnabled="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Notice that because we don’t have an interface assembly and therefore can’t add a .NET reference to the assembly, we also have to turn on the metadata exchange in the service behavior.

  Lines Changed Lines Added Lines Removed
here 0 14 0
total 4 15 2

The last thing we need to do is remove the asmx file and replace it with a service file. This too was a tricky one to count.
Technically you are deleting and asmx file and adding a svc file, so I am going to count them as adding a line and removing a line, even though the contents of the file barely changed at all, so if the file was staying the same I might count it differently.

<%@ WebService Language="CSharp" Class="CalcService" CodeBehind="~/App_Code/CalcService.cs" %>
<%@ ServiceHost Language="CSharp" Service="CalcService" CodeBehind="~/App_Code/CalcService.cs" %>

OK so for the service that brings us to

  Lines Changed Lines Added Lines Removed
here 0 1 1
total 4 16 3

And now onto the client…

We need to remove the old reference and add a reference to the new service.  Again I will count this as an add and a remove even though hundreds of lines are changing in the background.

  Lines Changed Lines Added Lines Removed
here 0 1 1
total 4 17 4

For the client we need to change the buttonAdd_Click event to look like this:

using ClientForm.localhost;

private void buttonAdd_Click(object sender, EventArgs e)
{
    double num1 = double.Parse(textBox1.Text);
    double num2 = double.Parse(textBox2.Text);
    CalcService calc = new CalcService();
    CalcServiceClient calc = new CalcServiceClient();
    double result = calc.Add(num1, num2);
    textBoxResult.Text = result.ToString();
}
  Lines Changed Lines Added Lines Removed
here 1 0 0
total 5 17 4

Results

OK, so that brings the comparison to:

  Lines Changed Lines Added Lines Removed
Remoting 18 7 9
WebService 5 17 4

34 to 26. It appears I was wrong – WebServices were a little easier to change.

Of course if there *was* an interface, and you wanted to keep your namespace, that would have brought the totals higher by a couple of lines.

And if you were using ASP.NET features in your web service (which is probable) and you wanted to keep using those in WCF that would have added 3 more lines.
First in the config file

<serviceHostingEnvironment aspNetCompatibilityEnabled="true" />

Then in code

using System.ServiceModel.Activation;

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]

This would bring the totals to: 34 to 31.

This would put it in the too close to call category, especially considering counting irregularities like the fact the we regenerated web references using asmx web services.

Editorial

Ultimately it is your requirements that dictate whether you go down the .NET Remoting or the ASMX web services route, not the fact the WCF is going to release soon. The real power of WCF is its ability to support both ways of communicating rather than forcing you to pick one over the other. It is really saving you from a later requirements change like, “I know we need the speed for our internal clients but we now need to support an external client as well, and they happen to be using Java.”