Monthly Archives: January 2017

Remoting in C# (legacy code)

In another post I looked at remoting using WCF but what were things like before WCF (or what’s an alternative to WCF)? I thought I’d post just the bare bones for getting a really simple service and client up and running.

Note: Microsoft recommends new remoting code uses WCF, so this post is more for understanding legacy code.

Note: I am not going to go into the lifecycle, singletons/single instances etc. here, I’m just going to concentrate on the code to get something working.

The Server

As per my previous post on WCF remoting, we’re going to simply create a console application to act as our server, so go ahead an create one (mine’s named OldRemoteServer) and then add the following

public interface IRemoteService
{
   void Write(string message);
}

into a file of it’s own, then our client can link to it in our client’s Visual Studio solution.

Here’s an implementation for the above

public class RemoteService : MarshalByRefObject, IRemoteService
{
   public void Write(string message)
   {
      Console.WriteLine(message);
   }
}

Note: The implementation needs to be derived from MarshalByRefObject or the class needs to be marked with the Serializable attribute or implement ISerializable which obviously makes sense. We’re solely going to look at MarshalByRefObject implementation for now as these will be passed by reference to the client, whereas the serializable implementations are aimed at passing by value.

Now let’s put some code in the Main method of our Console app.

var channel = new TcpChannel(1002);
ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(
  typeof(RemoteService), 
  "Remote", 
   WellKnownObjectMode.Singleton);

// now let's ensure the console remains open
Console.ReadLine();

In the above code we’re using a Tcp channel with the port number 1002 and in the RegisterWellKnownServiceType, we’re registering the service type (this should be the implementation, not the interface) and supply a name “Remote” for it. In this case I’m also setting it to be a Singleton.

You’ll need to add a reference to System.Runtime.Remoting and the following using clauses

using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Tcp;

The Client

Create another Console application to simply test this and add the file with the IRemoteService interface.

I’ve simply added it by selecting the client solution, the Add… | Existing Item, locate the file and instead of clicking the Add button select the dropdown to Add As Link. Then if you change the interface it’ll be immediately reflected in the client – ofcourse in a more complex application we’d have the interfaces in their own assembly.

Now to get the client to call the server we simply place the following in the Main method of the Console app.

var obj = (IRemoteService)Activator.GetObject(
   typeof(IRemoteService), 
   "tcp://localhost:1002/Remote");

obj.Write("Hello World");

In the above you’ll see that we use the Activator to get an object and supply the type, then the next line shows we’re using the Tcp channel, port 1002 as set up in the server and the name from the server we game our object “Remote”.

This creates a transparent proxy which we then simply call the interface method Write on.

Configuration

In the above example code I’ve simply hard-coded the configuration details but ofcourse we can create a .config file to instead handle such configurations.

Let’s replace all the server Main method code with the following

RemotingConfiguration.Configure("Server.config", false);

Add an App.config to the project, we’re going to rename it Server.config for this example and ensure that the files’s properties (in Visual Studio) are set to Copy Always (or Copy if newer) to ensure the copy in the bin folders is upto date.

Now here’s the Server.config which recreates the singleton, tcp, port 1002 settings previously handled in code

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
  <application>
    <service>
      <wellknown
        type="OldRemoteServer.RemoteService, OldRemoteServer"
        objectUri="Remote"
        mode="Singleton" />
    </service>
    <channels>
      <channel ref="tcp" port="1002"/>
    </channels>
  </application>

  </system.runtime.remoting>
</configuration>

Now if you run the server and then the client, everything should work as before.

Next up, let’s set the client up to use a configuration file…

So we’ll add an App.config file to the client now, but let’s name it Client.config and again set the Visual Studio properties to ensure it’s always copied to the bin folder.

Add the following to the configuration file

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown 
          type="OldRemoteServer.RemoteService, OldRemoteServer" 
          url="tcp://localhost:1002/Remote" />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

It might seem a little odd that we’re declaring the type as the implementation within the server code, but the reason will hopefully become clear.

Add a reference within the client to the RemoteServer (if you have the implementation in a DLL, all the better, we didn’t do that, so I’m referencing the server EXE itself). This now give us access to the implementation of the RemoteService.

Change the client Main method to

RemotingConfiguration.Configure("Client.config", false);

var obj = new RemoteService();
obj.Write("Hello World");

don’t forget to add the using clause

using System.Runtime.Remoting;

This bit might seem a little strange, based upon what we’ve previously done and how we’ve kept a separation of interface and implementation. Aren’t we now simply creating a local instance of the RemoteService, you might ask.

Well try it, run the server and then the client and you’ll find .NET has created a transparent proxy for us and calls to the RemoteService will in fact go to the server.

Whilst this makes things very easy, I must admit I prefer to not reference the implementation of the RemoteService.

What about named pipes?

Let’s now look at the changes to use the IPC protocol (for implementing named pipes) in .NET remoting. I’ll just briefly cover the changes required to implement this.

To start with let’s rewrite the server and client in code. So first the Main method in the server should now look like

var channel = new IpcChannel("ipcname");
ChannelServices.RegisterChannel(channel, false);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(RemoteService),
   "Remote",
   WellKnownObjectMode.Singleton);

Console.ReadLine();

So the only real difference from the Tcp implementation is the use of an IpcChannel and the name supplied instead of a port.

The client then looks like this

var obj = (IRemoteService)Activator.GetObject(
   typeof(IRemoteService), 
   "ipc://ipcname/Remote");

obj.Write("Hello World");

Simple enough.

Now let’s change the code to use a configuration file.

The server Main method should now look like this

RemotingConfiguration.Configure("Server.config", false);
Console.ReadLine();

and the Server.config should look like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
  <application>
    <service>
      <wellknown
        type="OldRemoteServer.RemoteService, OldRemoteServer"
        objectUri="Remote"
        mode="Singleton" />
    </service>
    <channels>
      <channel ref="ipc" portName="ipcname"/>
    </channels>
  </application>

  </system.runtime.remoting>
</configuration>

The client code should be

RemotingConfiguration.Configure("Client.config", false);
var obj = new RemoteService();
obj.Write("Hello World");

and it’s Client.config should look like this

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.runtime.remoting>
    <application>
      <client>
        <wellknown 
          type="OldRemoteServer.RemoteService, OldRemoteServer" 
          url="ipc://ipcname/Remote" />
      </client>
    </application>
  </system.runtime.remoting>
</configuration>

Remoting using WCF

It’s been a long while since I had to write any remoting code. However I came across a requirement to run a small out of process application which needed to be controlled by another application, I won’t bore you with the details, but suffice to say remoting seemed to be a good fit for this.

Let’s look at some code

Let’s start by creating the server/service. In this instance I will host the service in a Console application. So we need to create a Console solutions/project (mine’s named RemoteServer) and then (to allow us to reuse an interface file) add a Class library (mine’s named RemoteInterfaces).

Add the following to the class library

[ServiceContract]
public interface IRemoteService
{
   [OperationContract(IsOneWay = true)]
   void Write(string message);
}

Note: you’ll need a reference to System.ServiceModel in the RemoteInterfaces project, plus using System.ServiceModel; in the source

Add the class library as a reference to the RemoteServer console application.

Now, let’s create the implementation for the server…

[ServiceBehavior(
 ConcurrencyMode = ConcurrencyMode.Single,
 InstanceContextMode = InstanceContextMode.Single)]
public class RemoteService :
   IRemoteService
{
   private ServiceHost host;

   public void Start()
   {
      host = new ServiceHost(this);
      host.Open();
   }

   public void Stop()
   {
      if (host != null)
      {
         if (host.State != CommunicationState.Closed)
         {
            host.Close();
         }
      }
   }

   public void Write(string message)
   {
      Console.WriteLine(String.Format("[Service] {0}", message));
   }
}

We’re going to run this service as a singleton when the console starts, so in Program.cs we need to write the following

try
{
   var svc = new RemoteService();
   svc.Start();

   Console.ReadLine();

   svc.Stop();
}
catch (Exception e)
{
   Debug.WriteLine(e.Message);
}

Finally we need to put some configuration in place to tell WCF how this service is to be hosted, so in the console application, add an App.config (if not already available) and add the following

finally App.config looks like

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
    <services>
      <service name="RemoteServer.RemoteService">
        <endpoint binding="netTcpBinding"
                  contract="RemoteInterfaces.IRemoteService">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <host>
          <baseAddresses>
            <add baseAddress="net.tcp://localhost:8000/RemoteService"/>
          </baseAddresses>
        </host>
      </service>
    </services>
  </system.serviceModel></configuration>

Client implementation

Now, lets create a client to tests this service. For simplicity, we’ll assume the server is run automatically, either at startup or via our client application, but we won’t bother writing code for this. So when you’re ready to test the client just ensure you’ve run the server console first. You’ll need to reference the class library with the IRemoteService (RemoteInterfaces) also.

Note: you’ll need a reference to System.ServiceModel in the RemoteClient project, plus using System.ServiceModel; in the source

Change the client Main method to include the following

var channelFactory = new ChannelFactory<IRemoteService>(
   new NetTcpBinding(),
   new EndpointAddress("net.tcp://localhost:8000/RemoteService"));
var channel = channelFactory.CreateChannel();

channel.Write("Hello World");

channelFactory.Close();

Now if you run this client, the server should output the Hello World text.

We’ve initially created this client by hard coding the endpoint etc. but it might be better if this was in the configuration.

In your App.config you could have the following

<system.serviceModel>
   <client configSource="Config\servicemodel-client-config.xml" />
</system.serviceModel>	

Note: Obviously the name of the file us upto you.

or we could place the service code directly in the App.config, it should look like this (if in an external config file)

<?xml version="1.0" encoding="utf-8"?>
<client>
   <endpoint name="RemoteServer.RemoteService"
      address="net.tcp://localhost:8000/RemoteService"
      binding="netTcpBinding"
      contract="RemoteInterfaces.IRemoteService">
      <identity>
         <servicePrincipalName value=""/>
      </identity>
   </endpoint>
</client>

Note: If placed within the App.config, wrap the client element in a system.serviceModel element

and now we can change our ChannelFactory in the Main method to look like this

var channelFactory = new ChannelFactory<IRemoteService>("*");

The configuration will thus be taken from the configuration file.

Let’s switch from using TCP to using a named pipe

So the previous code and configuration should work correctly using the TCP/IP protocol, but it does rely on a known port to be used. In scenarios where you’re deploying to a machine where you’re not 100% sure the port is available, you could ofcourse offer up several port options.

Another choice (which should also be more performant, although I’ve not tested this) for interprocess communications on the same machine, is to use a named pipe.

For this change the service’s App.config (or external file) on the server to use the following configuration

<services>
   <service name="RemoteServer.RemoteService">
      <endpoint binding="netNamedPipeBinding"
         contract="RemoteInterfaces.IRemoteService">
         <identity>
            <dns value="localhost"/>
         </identity>
       </endpoint>
       <host>
          <baseAddresses>
            <add baseAddress="net.pipe://localhost/RemoteServer/RemoteService"/>
          </baseAddresses>
       </host>
   </service>
</services>

and in the client code we could use

channelFactory = new ChannelFactory<IRemoteService>(
                new NetNamedPipeBinding(),
                new EndpointAddress("net.pipe://localhost/RemoteServer/RemoteService"));

or replacing with configuration we could use replace our client configuration with

<client>
   <endpoint name="RemoteServer.RemoteService"
      address="net.pipe://localhost/RemoteServer/RemoteService"
      binding="netNamedPipeBinding"
      contract="RemoteInterfaces.IRemoteService">
      <identity>
         <servicePrincipalName value=""/>
      </identity>
    </endpoint>
</client>

Debugging

You might at times find issues with your client not finding an endpoint, an ipc name or port etc. How can we check if our server is actually connected to a port or pipe?

For tcp/http protocols, we can use netstat, for example

netstat -a | findstr "8000"

this will list display all connections and listening ports (-a switch) and pipe these through the findstr application to display only those with 8000 in the output. Hence if we’re running a server off of port 8000 it should be listed and we’ll know that the server is (at least) running.

For ipc/pipe, the simplest way is via Powershell by running the following

[System.IO.Directory]::GetFiles("\\.\\pipe\\")

this will list all pipes, which might be a little over the top.

An alternative to the above is use the sysinternals PipeList executable.

Whilst we could use the following for old style remoting code (to find a named pipe)

[System.IO.Directory]::GetFiles("\\.\\pipe\\") | findstr "RemoteService"

unfortunately this does not work for WCF named pipes as these are converted to GUID’s. See Named Pipes in WCF are named but not by you (and how to find the actual windows object name).

Debugger Attributes

There’s several debugging types of attributes I use fairly regularily, such as DebuggerStepThrough and DebuggerDisplay, but I decided to take a look at some of the other, similar, attributes to see if I was missing anything, here’s what I found out.

Introduction

At the time of writing these are the debugging attributes I found

  • DebuggerStepThrough
  • DebuggerDisplay
  • DebuggerNonUserCode
  • DebuggerHidden
  • DebuggerBrowsable
  • DebuggerTypeProxy
  • DebuggerStepperBoundary

Before I get into the specific attributes, I will be listing the attribute targets that the attribute may be applied to, when it says an attribute may be set on a method, this also includes the setter/getter (methods) on a property. But not the property itself, this requires the AttributeTargets.Property target to be set.

DebuggerStepThrough

References

DebuggerStepThroughAttribute Class

Usage

  • Class
  • Struct
  • Constructor
  • Method

Synopsis

Let’s start with the one I used a lot in the past (on simple properties, i.e. equivalent of auto-properties). Placing a DebuggerStepThrough on any of the usage targets, will inform the debugger (in Visual Studio, not tested in Xamarin Studio as yet) to simply step through (or in debugging terms, step over) the code. In other words the debugger will not enter a method call.

This is especially useful for situations where, maybe you have simple code, such as properties which just return or set a value and this will save you stepping into this property setters or getters during a debugging session.

Example

public class MyClass
{
   private int counter;

   [DebuggerStepThrough]
   public int Increment()
   {
      return counter++;
   }
}

As stated in the usage, you can also apply this to the class itself to stop the debugger stepping into any code in the class. Useful if the class is full of methods etc. which you don’t need to step into.

DebuggerDisplay

Next up, is the DebuggerDisplayAttribute.

References
DebuggerDisplayAttribute Class

Usage

  • Assembly
  • Class
  • Struct
  • Enum
  • Property
  • Field
  • Delegate

Synopsis

In situations where you’re debugging and you place the mouse pointer over the an instance of MyClass (as defined previously) you’ll see the popup say something like

{MatrixTests.MyClass}

next to the variable name. This is fine if all you want is the type name or if you want to drill into the instance to view fields or properties but if you’ve got many fields or properties, it might be nicer if the important one(s) are displayed instead of the type name.

Before we delve into DebuggerDisplay, if your class implements a ToString override method then this will normally be displayed by the debugger. If you’re using this for something else, then it will not fulfill the requirements for displaying something different when the instance is hovered over. But if this ToString has everything you need then there’s no need for a DebuggerDisplay attribute.

Example

Let’s start by seeing the ToString and DebuggerDisplay that would be equivalent

public override string ToString()
{
   return $"Counter = {counter}";
}

// equivalent to 

[DebuggerDisplay("Counter = {counter}")]
public class MyClass
{
   // code
}

Both of the above will show debugger popup of “Counter = 0” (obviously 0 is replaced with the current counter value).

As you can see within the DebuggerDisplayAttribute, we can include text and properties/fields we just need to enclose them in {}. We can also use methods, within the DebuggerDisplay. Let’s assume we have a private method which creates the debugger output

[DebuggerDisplay("{DebuggerString()}")]
public class MyClass
{
   private string DebuggerString()
   {
      return $"Counter = {counter}";
   }
   // other code
}

As stated previously these all show a debugger display of “Counter = 0” – they also display quotes around the text. We can remove these by specifying nq (nq == no quotes), as per

[DebuggerDisplay("{DebuggerString(), nq}")]

So now the output display is Counter = 0 i.e. without quotes.

You can, ofcourse, extend format to display more fields/properties as per C# 6.0 string interpolation. i.e. if we have a matrix class with two properties, Rows and Columns and want to display these in the debugger display we can use

[DebuggerDisplay("Rows = {Rows}, Columns = {Columns}")]

We can also extend this syntax to use basic expressions, for example

[DebuggerDisplay("Counter = {counter + 10}")]

the above code will evaluate the counter field and then add 10 (as I’m sure you guessed).

Gotcha’s

Just remember that whatever you place in the DebuggerDisplay will be executed when you view it. So if you’re calling a remote service or database, be ready for the performance hit etc.

DebuggerNonUserCode

References

DebuggerNonUserCodeAttribute Class
Using the DebuggerNonUserCode Attribute in Visual Studio 2015
Change Debugger behavior with Attributes

Usage

  • Class
  • Struct
  • Constructor
  • Method
  • Property

Synopsis

This is very similar to DebuggerStepThrough, but as you can see from the usage, also allows us to apply this attribute to a property as a whole.

Examples

Used in the same way as DebuggerStepThrough, see those examples.

DebuggerHidden

References

DebuggerHiddenAttribute Class
Using the DebuggerNonUserCode Attribute in Visual Studio 2015
Change Debugger behavior with Attributes

Usage

  • Constructor
  • Method
  • Property

Synopsis

This is very similar to DebuggerStepThrough and DebuggerNonUserCode, but as you can see from the usage it’s somewhat restricted on what it can be applied to.

Examples

Used in the same way as DebuggerStepThrough, see those examples.

DebuggerBrowsable

References

DebuggerBrowsableAttribute Class

Usage

  • Property
  • Field

Synopsis

If you are viewing an instance of the MyClass (shown previously) within the popup debug window (displayed when you hover over the instance variable during a Visual Studio debugging session), you will see a + sign to the left of the class, meaning you can view the fields/properties in this class, but in some situations you might want to reduce the fields/properties (or what might be seen as noise). This is especially useful in situations where maybe you have lots of fields or properties which are maybe of limited usefulness in a debugging scenario, or maybe pre auto properties, you might wish to “hide” all fields. Then simply mark the field or property with

[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int counter;

Now when you view the instance of MyClass, no + will appear as I’ve stipulated never display this field as browseable.

The other options for DebuggerBrowsableState are

  • DebuggerBrowsableState.Collapsed
  • DebuggerBrowsableState.RootHidden

as per Microsoft documentation…

Collapsed shows the element as collapsed whilst RootHidden does not display the root element; display the child elements if the element is a collection of array items.

Examples

// never show the field in the debugger popup
// wtahc or auto windows
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private int counter;

Basically RootHidden used on an array property (for example)

public int[] Counters
{
   //
}

will not display Counters, but will displace the array of elements.

DebuggerTypeProxy

References

Using DebuggerTypeProxy Attribute

Usage

  • Assembly
  • Class
  • Struct

Synopsis

When we looked at the DebuggerDisplay we found we could reference fields/properties within the class and even use a limited set of expressions. But in some scenarios, such as the one where we added a DebuggerString to the class, it might be preferable to extract the debugger methods/properties etc. to ensure the readability and maintainability of the original class.

Examples

Let’s start by changing the MyClass code to this

[DebuggerTypeProxy(typeof(MyClassDebuggerProxy))]
public class MyClass
{
   private int counter;

   public int Counter => counter;

   public int Increment()
   {
      return counter++;
   }
}

I’ve added a property Counter, to allow us to use the counter in our proxy

Now create a simple proxy that looks like this

public class MyClassDebuggerProxy
{
}

If you now try to view the fields on an instance of MyClass the debugger will use the MyClassDebuggerProxy and in this instance there are no fields/properties and therefore nothing will be displayed (well they will if you expand Raw View but not at the top level in the debugger). So in this form, it’s a simple way to hide everything from the debugger – if that is required. Let’s be honest that’s not usually the intention, so let’s add some properties to the proxy and use the MyClass.Counter property.

public class MyClassDebuggerProxy
{
   private MyClass _instance;

   public MyClassDebuggerProxy(MyClass instance)
   {
      _instance = instance;
   }

   public int DebuggerCounter {  get { return _instance.Counter; } }
}

Now when you debug an instance of MyClass, the debugger will display the property DebuggerCounter from the proxy class. The _instance field will not be displayed. This example is a little pointless, but unlike the limited expression capability of DebuggerDisplay, the full capabilities of .NET can be used to add more data to the debugger, or change debugger displayed data.

Note: If you want to display something other than the type for the instance of MyClass, then you’ll still need to apply a DebuggerDisplay attribute to the MyClass object, not to the proxy as this will be ignored.

DebuggerStepperBoundary

References

DebuggerStepperBoundaryAttribute Class

Usage

  • Constructor
  • Method

Synopsis

This is a slightly odd concept (well it is to me at the moment). Using this attribute on a method (say our Increment method in MyClass) will in essence tell the debugger to switch from stepping mode to run mode. In other words, if you have a breakpoint on a call to myClass.Increment then press F10 or F11 (to step over or step in to the Increment method) the debugger will see the DebuggerStepperBoundary and instead do the equivalent of F5 (or run). From this perspective the use of such an attribute seems fairly limited, however the Microsoft documentation (shown in the references above) states…

“When context switches are made on a thread, the next user-supplied code module stepped into may not relate to the code that was in the process of being debugged. To avoid this debugging experience, use the DebuggerStepperBoundaryAttribute to escape from stepping through code to running code.”

Covariance and contravariance

Before we begin, let’s define the simplest of classes/hierarchies for our test types…

The following will be used in the subsequent examples

class Base { }
class Derived : Base { }

With that out of the way, let’s look at what covariance and contravariance mean in the context of a programming language (in this case C#).

The covariant and contravariant described, below, can be used on interfaces or delegates only.

Invariant

Actually we’re not going straight into covariance and contravariance, let’s instead look at what an invariant generic type might look like (as we’ll be building on this in the examples). Invariant is what our “normal” generics or delegates might look like.

Here’s a fairly standard use of a generic

interface IProcessor<T> 
{
}

class Processor<T> : IProcessor<T>
{        
}

If we try to convert an IProcessor<Derived> to an IProcessor<Base> or vice versa, we’ll get a compile time error, i.e. here’s the code that we might be hoping to write

Now if we wanted to do the following

IProcessor<Derived> d = new Processor<Derived>();
IProcessor<Base> b = d;

// or

IProcessor<Base> b = new Processor<Base>();
IProcessor<Derived> d = b;

So, in the above we’re creating a Processor with the generic type Derived (in the first instance) and we might have a method that expects an IProcessor. In our example we simulate this with the assignment of d to b. This will fail to compile. Likewise the opposite is where we try to assign a IProcessor to an IProcessor, again this will fail to compile. At this point the IProcessor/Processor are invariant.

Obviously with the derivation of Base/Derived, this would probably be seen as a valid conversion, but not for invariant types.

With this in mind let’s explore covariance and contravariance.

Covariance

Covariance is defined as enabling us to “use a more derived type than originally specified” or to put it another way. If we have an IList<Derived> we can assign this to a variable of type IList<Base>.

Using the code

IProcessor<Derived> d = new Processor<Derived>();
IProcessor<Base> b = d;

we’ve already established, this will not compile. If we add the out keyword to the interface though, this will fix the issue and make the Processor covariant.

Here’s the changes we need to make

interface IProcessor<out T> 
{
}

No changes need to be made on the implementation. Now our assignment from a derived type to a base type will succeed.

Contravariance

As you might expect, if covariance allows us to assign a derived type to a base type, contravariance allows us to “use a more generic (less derived) type than originally specified”.

In other words, what if we wanted to do something like

IProcessor<Base> b = new Processor<Base>();
IProcessor<Derived> d = b;

Ignore the fact that b cannot possibly be the same type in this example (i.e. Derived)

Again, you may have guessed, if we used an out keyword for covariance and contravariance is (sort of) the opposite, then the opposite of out will be the in keyword, hence we change the interface only to

interface IProcessor<in T>
{
}

Now our code will compile.

What if we want to extend a covariant/contravariant interface?

As noted, the in/out keywords are used on interfaces or delegates, if we wanted to extend an interface that supports one of these keywords, then we would apply the keyword to the extended interfaces, i.e.

interface IProcessor<out T>
{
}

interface IExtendedProcessor<out T> : IProcessor<T>
{
}

obviously we must keep the interface the same variance as the base interface (or not mark it as in/out. We apply the keyword as above.

References

Covariance and Contravariance in GenericsCovariance and Contravariance FAQ
in (Generic Modifier) (C# Reference)
out (Generic Modifier) (C# Reference)

Fun with Expression objects

Expressions are very useful in many situation. For example, you have a method which you pass a lambda expression to and the method can then determine the name of the property the lambda is using or the method name etc. Or maybe you’ve used them in the past in view model implementations pre-nameof. They’re also used a lot in mocking frameworks, to make the arrange steps nice and terse.

For example

Expressions.NameOf(x => x.Property);

In the above example the lambda expression is the x => x.Property and the NameOf method determines the name of the property, i.e. it returns the string “Property” in this case.

Note: This example is a replacement for the nameof operator for pre C# 6 code bases.

Let’s look at some implementations of such expression code.

InstanceOf

So you have code in the format

Expressions.InstanceOf(() => s.Clone());

In this example Expressions is a static class and InstanceOf should extract the instance s from the expression s.Clone(). Obviously we might also need to use the same code of a property, i.e. find the instance of the object with the property.

public static object InstanceOf<TRet>(Expression<Func<TRet>> funcExpression)
{
   var method = funcExpression.Body as MethodCallExpression;
   // if not a methood, try to get the body (possibly it's a property)
   var memberExpression = method == null ? 
      funcExpression.Body as MemberExpression : 
      method.Object as MemberExpression;

   if(memberExpression == null)
      throw new Exception("Unable to determine expression type, expected () => vm.Property or () => vm.DoSomething()");

   // find top level member expression
   while (memberExpression.Expression is MemberExpression)
      memberExpression = (MemberExpression)memberExpression.Expression;

   var constantExpression = memberExpression.Expression as ConstantExpression;
   if (constantExpression == null)
      throw new Exception("Cannot determine constant expression");

   var fieldInfo = memberExpression.Member as FieldInfo;
   if (fieldInfo == null)
      throw new Exception("Cannot determine fieldinfo object");

   return fieldInfo.GetValue(constantExpression.Value);
}

NameOf

As this was mentioned earlier, let’s look at the code for a simple nameof replacement using Expressions. This implementation only works with properties

public static string NameOf<T>(Expression<Func<T>> propertyExpression) 
{
   if (propertyExpression == null)
      throw new ArgumentNullException("propertyExpression");

   MemberExpression property = null;

   // it's possible to end up with conversions, as the expressions are trying 
   // to convert to the same underlying type
   if (propertyExpression.Body.NodeType == ExpressionType.Convert)
   {
      var convert = propertyExpression.Body as UnaryExpression;
      if (convert != null)
      {
         property = convert.Operand as MemberExpression;
      }
   }

   if (property == null)
   {
      property = propertyExpression.Body as MemberExpression;
   }
   if (property == null)
      throw new Exception(
         "propertyExpression cannot be null and should be passed in the format x => x.PropertyName");

   return property.Member.Name;
}

Deploying our .NET 4.0 StackService service to IIS 6

Unfortunately the server I’m writing a ServiceStack service for is not only restricted to .NET 4.0 but also running IIS 6.0. I also need to deploy the service as a virtual directory off of the Default Web Site.

The first thing we want to do is publish/copy the files that make up our service to the IIS server.

Here’s the steps I took to get this working, obviously they may differ depending upon what access you have to the web server (and whether you deploy direct) etc.

  • From your ASP.NET/ServiceStack application, select the web service project and right mouse click.
  • Select Publish
  • Select Custom and set a profile name, mines “Files”, press OK
  • I’m going to copy the files across to the server myself, so for Publish Method, select File System and then enter a location to write your files to, click the next button
  • Leave the Configuration as Release
  • Press the Publish button

At this point the file location you selected will have the files required for the service.

Now if not already done as part of the publish steps, copy the files to the location you want to deploy them on your IIS 6.0 server. For example mine are in a folder named TestStack. Now we need to setup IIS to expose the service.

  • Open Internet Information Services (IIS) Manager or run %SystemRoot%\system32\inetsrv\iis.msc to open it
  • Expand the local computer node in the left hand tree view
  • Expand Web Sites
  • Right mouse click on the Default Web Site and select New | Virtual Directory
  • Press the Next button and enter an alias, i.e. TestStack in my case
  • Press Next and browse from IIS or enter the folder location of your service (you want the root, not the bin folder) in your browser and press next
  • Ensure Read and Run scripts (such as ASP) are checked and press Next
  • Click Finish

On the properties, Documents tab, uncheck the Enable default content page

Not sure the above is a requirement to get things working, but just happened to be something I set

On the Virtual Directory tab ensure the Execute Permissions is set to Scripts and Executables

On the ASP.NET page, ensure the ASP.NET version is 4.0.xxx

Now the virtual folder you be setup. If you’ve not got your service selected in the IIS Default Web Sites node, then select it and right mouse click, then select browse to see if all is working, or open your preferred browser and enter

http://<hostname>/StackService/metadata

If you are getting a 404 The page cannot be found error, then this might help

See Can’t get ServiceStack to work in IIS6 with HTTPS

The exact steps I took are listed below

  • Select the virtual directory in IIS, right mouse click and load the properties
  • From the Virtual Directory tab, press the Configuration button
  • Press Insert
  • From file explorer locate aspnet_isapi.dll for .NET 4.0, for example mine is located in %windir%\Microsoft.NET\Framework\v4.0.30319
  • Once located enter %windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll (replacing %windir% with you actual location) in the Executable textbox
  • Uncheck the Verify that file exists checkbox, then press OK
  • Press OK again and again until the properties dialog is closed

Now if you refresh or reload the URL for the virtual folder or again select Browse from IIS, the meta data from ServiceStack should be displayed.

Whilst this may be a fairly specific case, i.e. deployed to .NET 4.0 on IIS 6.0, I thought it might still be a useful post anyway.

.NET 4.0 compatible ServiceStack service

In my last post I outlined the creation of a ServiceStack web service, pretty much as per the current documentation on the ServiceStack website.

I’m now going to create a bare minimum service from scratch (i.e. not using the ServiceStack project templates). The reason for this is that I want to deploy a service to an old server box which doesn’t support .NET greater than 4.0. Out of the box the templates don’t work with older versions of .NET.

This post will concentrate on a .NET 4.0 compatible ServiceStack, but the same steps can be applied to a bare minimum .NET 4.6 service as well – obviously just change the .NET framework to suit.

We’ll recreate the Hello World implementation as per the ServiceStack templates in this example.

Note: I’m not aiming to create a “best practices” example of code, this literally will be the bare minimum set of code and projects to implement the demo Hello World service.

  • Create a ASP.NET Empty Web Application, setting the .NET framework to .NET 4 – my project is named TestStack
  • Using NuGet, install the ServiceStack packages – use the 4.0.24 versions. This version is required because of a PCL issue with subsequent versions supporting .NET 4.0 (see ServiceStack NuGet update 4.0.22 to 4.0.31 caused errors on deployment)
  • Add a C# class, named AppHost and include the following code
    using Funq;
    using ServiceStack;
    
    public class AppHost : AppHostBase
    {
       public AppHost()
          : base("TestStack", 
               typeof(MyServices).Assembly) 
       { 
       }
    
       public override void Configure(Container container)
       {
       }
    }
    
  • Now add another Class named MyServices and add the following code
    using ServiceStack;
    
    public class MyServices : Service
    {
       public object Any(Hello request)
       {
          return new HelloResponse 
          { 
             Result = "Hello, {0}!".Fmt(request.Name) 
          };
       }
    }
    
  • Add another Class name Hello and add the following code
    using ServiceStack;
    
    [Route("/hello/{Name}")]
    public class Hello : IReturn<HelloResponse>
    {
       public string Name { get; set; }
    }
    
  • Now add the last class, which is named HelloResponse and add the following code
    public class HelloResponse
    {
       public string Result { get; set; }
    }
    
  • Now add a Global Application Class, keep it named as Global and in the code behind, remove the existing class and methids and replace with the following
    public class Global : HttpApplication
    {
       protected void Application_Start(object sender, EventArgs e)
       {
          new AppHost().Init();
        }
    }
    
  • Finally we need to alter the Web.config to look like this
    <configuration>
      <system.web>
          <compilation debug="true" targetFramework="4.0" />
          <httpHandlers>
            <add path="*" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" />
          </httpHandlers>
          <pages controlRenderingCompatibilityVersion="4.0" />
        </system.web>
    
      <system.webServer>
        <modules runAllManagedModulesForAllRequests="true" />
        <validation validateIntegratedModeConfiguration="false" />
        <urlCompression doStaticCompression="true" doDynamicCompression="false" />
        <handlers>
          <add path="*" name="ServiceStack.Factory" type="ServiceStack.HttpHandlerFactory, ServiceStack" verb="*" preCondition="integratedMode" resourceType="Unspecified" allowPathInfo="true" />
        </handlers>
      </system.webServer>
    
    </configuration>
    

Run the application via Visual Studio and you should see the metadata page showing the Hello operation. To double check the operation works simply change the URL in your preferred browser to

http://localhost:49810/Hello/World

Obviously change the port to the one supplied by iisexpress.

Implementing a client and services with ServiceStack

ServiceStack, is a lightweight framework for writing web services.

Getting Started

Let’s just create a “default” service and client first.

See Create your first WebService for information on creating your first service. I’ll replicate some of the steps here also…

  • Using Visual Studio, Tools | Extensions and Updated, search for ServiceStack templates and install (if not already installed)
  • Create a new ServiceStack ASP.NET Empty project (target .NET 4.6)
  • Build and run

By default this will create a service which accepts a Hello object and returns a HelloResponse (for reference, here’s those classes)

public class HelloResponse
{
   public string Result { get; set; }
}

[Route("/hello/{Name}")]
public class Hello : IReturn<HelloResponse>
{
   public string Name { get; set; }
}

Note: The Hello class “implements” IReturn (which actually is just a marker interface, i.e. no methods) to give our client the ability to pass Hello objects (and hence have type safety etc.) to the service and inform the client what response to expect.

We can test the service using our web browser, for example my server is running on the localhost on port 50251, so typing the URL http://localhost:50251/Hello/Bob (note: the Route attribute defines the “route” to the specific method etc. hence you can see how this maps to the URL we used) will result in the Hello class being run with the argument Bob as the Name. The response will be displayed in the browser, along the lines of Result Hello, Bob!. This is the same result we’ll be expecting from our client app.

But how did we get the result “Hello, World!” from the server? This is where the MyService implementation in the generated server code comes in. When the server’s AppHost starts up it looks for services. These are then used to intercept/generate calls and responses. See the code below (copied from the generated code)

public class MyServices : Service
{
   public object Any(Hello request)
   {
      return new HelloResponse 
      { 
         Result = "Hello, {0}!".Fmt(request.Name) 
      };
   }
}

Let’s create a client app.

  • Create a Console application
  • From the Package Manager Console, run Install-Package ServiceStack.Client
  • Copy the Hello and HelloResponse classes from the service to the client
  • In the Main method add the following
    var client = new JsonServiceClient("http://localhost:50251/");
    var resp = client.GetAsync(new Hello { Name = "Bob" })
       .Success(tsk =>
       {
          Console.WriteLine(tsk.Result);
       })
       .Error(e =>
       {
          Console.WriteLine(e.Message);
       });
    
    Console.ReadLine();
    

For the client Api we could have called the service using

var resp = client.GetAsync<HelloResponse>("/hello/World");

if preferred, and this will do away for the need for the Hello class in the client.