Skip to content

Instantly share code, notes, and snippets.

@ionoy
Created May 9, 2014 07:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ionoy/a67606e5b6bbbefafebf to your computer and use it in GitHub Desktop.
Save ionoy/a67606e5b6bbbefafebf to your computer and use it in GitHub Desktop.
using System;
using System.Linq;
using System.Reflection;
using System.ServiceModel;
using LinFu.DynamicProxy;
namespace UAV.Communication
{
public static class CommunicationHelpers
{
private static T GetProxy<T>() where T : new()
{
var type = typeof (T);
if(type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).Any(m => !m.IsVirtual || m.IsFinal))
throw new InvalidOperationException("All public methods of type " + type.Name + " should be virtual.");
var proxyFactory = new ProxyFactory();
var uavControl = new T();
var loggingInterceptor = new LoggingInterceptor(uavControl);
return proxyFactory.CreateProxy<T>(loggingInterceptor);
}
public static ServiceHost CreateHost<T>(string hostSuffix = "") where T : new()
{
var proxy = GetProxy<T>();
var host = new ServiceHost(proxy, new[] {new Uri("net.pipe://localhost")});
host.Description.Behaviors.Find<ServiceBehaviorAttribute>().InstanceContextMode = InstanceContextMode.Single;
host.AddServiceEndpoint(typeof(IUAVControl), new NetNamedPipeBinding(), "UavPipe" + hostSuffix);
return host;
}
public static IUAVControl CreateClient(string hostSuffix = "")
{
var pipeFactory = new ChannelFactory<IUAVControl>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/UavPipe" + hostSuffix));
var uavControl = pipeFactory.CreateChannel();
((IClientChannel)uavControl).Open();
return uavControl;
}
public static void Disconnect(IUAVControl uavControl)
{
((IClientChannel)uavControl).Abort();
((IClientChannel)uavControl).Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment