How can I send a data from WCF host to connected client? - wcf

I want to send a data from WCF host (not service proxy) to the connected client with the service.
How can I achieve this?

You'll need to create a Duplex service. See this article for more information: http://msdn.microsoft.com/en-us/library/ms731064.aspx
Here's an example:
[ServiceContract(
SessionMode=SessionMode.Required,
CallbackContract=typeof(INotificationServiceCallback))]
public interface INotificationService
{
[OperationContract(IsOneWay = true)]
void Connect();
}
public interface INotificationServiceCallback
{
[OperationContract(IsOneWay = true)]
void SendNotification(string notification);
}
public class NotificationService : INotificationService
{
public static List<INotificationServiceCallback> Clients =
new List<INotificationServiceCallback>();
public void Connect()
{
Clients.Add(
OperationContext.Current.GetCallbackChannel<ICalculatorDuplexCallback>());
}
}
public class Notifier
{
void HandleReceivedNotification(string notification)
{
foreach (var client in NotificationService.Clients)
{
client.SendNotification(notification);
}
}
}

Related

Delphi - How to consume a WCF Service with netHTTPBindings

I have a WCF Service written in Visual Studio 2015 (c#) that uses web sockets, this means the endpoint is configured with netHTTPBindings. I have a Delphi application that I have currently written in XE and would like to consume the WCF Service, what is the best way for a Delphi application to consume a web socket WCF Service?
// Edit ---------------------------------------------------------------------------
I am now using wsDualHttpBindings, here is some prototype code:
WCF Service interface
[ServiceContract(CallbackContract = typeof(IStatusCallback))]
public interface IStatusService
{
[OperationContract(IsOneWay = true)]
Task StartSendingStatus();
}
[ServiceContract]
public interface IStatusCallback
{
[OperationContract(IsOneWay = true)]
Task SendStatus(string aValue);
}
Implementation
public class StatusService : IStatusService
{
public async Task StartSendingStatus()
{
var callback = OperationContext.Current.GetCallbackChannel<IStatusCallback>();
while (((IChannel)callback).State == CommunicationState.Opened)
{
await callback.SendStatus(GetStatus());
await Task.Delay(1000);
}
}
private string GetStatus()
{
// For now return datetime
string dt = DateTime.UtcNow.ToString();
return Convert.ToString(dt);
}
}
Here is how I consume it in a C# application, I put the result into list box.
public partial class ClientForm : Form
{
private StatusServiceReference.StatusServiceClient StatusService;
private class CallbackHandler : StatusServiceReference.IStatusServiceCallback
{
private ListBox _listbox;
public CallbackHandler(ListBox aListBox)
{
_listbox = aListBox;
}
public void SendStatus(string aValue)
{
_listbox.Items.Add(aValue);
_listbox.SelectedIndex = _listbox.Items.Count - 1;
}
}
public ClientForm()
{
InitializeComponent();
var context = new InstanceContext(new CallbackHandler(StatusListBox));
StatusService = new StatusServiceReference.StatusServiceClient(context);
}
private void StatusBtn_Click(object sender, EventArgs e)
{
StatusService.StartSendingStatus();
}
}
This works fine, I would like to know the best way to do the above client code in Delphi. When I import the WSDL file it does not have the IStatusServiceCallback interface.

WCF Inherit contracts and callback contract

I have a test project that test the Inherit contracts and callback contract.
Update 1 : I updated all of the topic with interfaces implamantations
By reading this article: http://codeidol.com/csharp/wcf/Service-Contracts/Contract-Inheritance/#part-16
This is possibol but when i try it, it fails.
class Program
{
static void Main(string[] args)
{
ServiceHost Service_IServer = new ServiceHost(new ServiceImplemantation(), new Uri(#"net.tcp://localhost:8080/"));
Service_IServer.AddServiceEndpoint(typeof(IService), new NetTcpBinding(), "Service");
Service_IServer.Open();
ServiceHost Service_I_IP = new ServiceHost(new IPImplemantation(), new Uri(#"net.tcp://localhost:8080/"));
Service_I_IP.AddServiceEndpoint(typeof(I_IP), new NetTcpBinding(), "Service");
Service_I_IP.Open();
Console.ReadLine();
}
}
[ServiceContract]
public interface I_IP
{
[OperationContract]
string GetIP();
}
[ServiceContract]
public interface IService : I_IP
{
[OperationContract]
void ImTheServer_Print();
}
//
//
//
//
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class IPImplemantation : I_IP
{
public string GetIP()
{
return "1.2.3.4";
}
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
public class ServiceImplemantation : IPImplemantation, IService
{
public void ImTheServer_Print()
{
Console.WriteLine("ImTheServer_Print");
}
}
The error:
The ChannelDispatcher at 'net.tcp://localhost:8080/Service' with contract(s) '"I_IP"' is unable to open its IChannelListener.
Ensure you decorate it as OneWay.
[OperationContract(IsOneWay = true)]
void GetIP();

WCF Service not Processing MSMQ Message

I have a WCF Windows Service that checks for MSMQ messages.
It picks the messages up ok but the ProcessMSMQMessage event does not seem to get called.
Any ideas why this is? Have I set ProcessMSMQMessage event correctly? Or am I missing something?
My code is below. Thanks.
WCF Service Class...
public partial class MyService : ServiceBase
{
private ServiceHost host;
public MyService()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
string queueName = ConfigurationManager.AppSettings["ProcessMsgQueueName"];
if (!MessageQueue.Exists(queueName))
{
MessageQueue thisQueue = MessageQueue.Create(queueName, true);
thisQueue.SetPermissions("Everyone", MessageQueueAccessRights.ReceiveMessage);
}
try
{
Uri serviceUri = new Uri("msmq.formatname:DIRECT=OS:" + queueName);
// communicate to MSMQ how to transfer and deliver the messages
MsmqIntegrationBinding serviceBinding = new MsmqIntegrationBinding();
serviceBinding.Security.Transport.MsmqAuthenticationMode = MsmqAuthenticationMode.None;
serviceBinding.Security.Transport.MsmqProtectionLevel = System.Net.Security.ProtectionLevel.None;
serviceBinding.SerializationFormat = MsmqMessageSerializationFormat.Binary;
host = new ServiceHost(typeof(MyService.Service1)); // add watcher class name
host.AddServiceEndpoint(typeof(MyService.IService1), serviceBinding, serviceUri);
host.Open();
}
catch (Exception ex)
{
EventLog.WriteEntry("SERVICE" + ex.Message, EventLogEntryType.Error);
}
}
protected override void OnStop()
{
if (host != null)
host.Close();
}
}
IService1 Contract...
[ServiceContract(Namespace = "MyService")]
[ServiceKnownType(typeof(Events.Dashboard_Message))]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void ProcessMSMQMessage(MsmqMessage<Events.Dashboard_Message> msg);
}
Service1 Class...
public class Service1 : IService1
{
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)]
public void ProcessMSMQMessage(MsmqMessage<Events.Dashboard_Message> msg)
{
string msgName = msg.GetType().Name;
// send to eventlog
EventLog.WriteEntry("MyService", msgName);
}
}
Got it working finally.
The issue was in IService1 contract. Needed to add Action = "*".
[OperationContract(IsOneWay = true, Action = "*")]

Attributes on a derived type not being deserialized in a WCF client even though KnownType is used

I have the following types:
public enum MyEnum
{
Value1,
Value2
}
[DataContract]
public class Configuration
{
[DataMember]
public MyEnum MyValue { get; set; }
[DataMember]
public Credentials CredentialValues { get; set; }
}
[DataContract, KnownType(typeof(CustomCredentials))]
public class Credentials
{
}
[DataContract]
public class CustomCredentials : Credentials
{
[DataMember]
public string Property1 { get; set; }
[DataMember]
public string Property2 { get; set; }
}
And on my service interface, I have a function that returns an instance of Configuration with its CredentialValues property set to a fully populated instance of CustomCredentials. I receive no errors from the client or the server, but while the data is being property serialized on the server and received by the client, the properties on CustomCredentials never have a value. What do I need to change here in order to have these properties properly deserialized on the client?
For reference, the connection between client and server is made with a DuplexChannelFactory over a NetTcpBinding using a data/service contract project that is shared by the client and service applications (the service is self-hosted), so there are no service proxy types that could need to be regenerated.
Added this code to the Contracts project along with your DataContracts.
[ServiceContract(Namespace = "http://schemas.platinumray.com/duplex", SessionMode = SessionMode.Required, CallbackContract = typeof(IService1Callback))]
public interface IService1
{
[OperationContract(IsOneWay = true)]
void GetData();
}
public interface IService1Callback
{
[OperationContract(IsOneWay = true)]
void SetData(Configuration config);
}
Created the service.
public class Service1 : IService1
{
public void GetData()
{
var x = new Configuration()
{
MyValue = MyEnum.Value1,
CredentialValues = new CustomCredentials { Property1 = "Something", Property2 = "Something else" }
};
OperationContext.Current.GetCallbackChannel<IService1Callback>().SetData(x);
}
}
class Program
{
static void Main(string[] args)
{
using (ServiceHost host = new ServiceHost( typeof(Service1), new Uri[] { new Uri("net.tcp://localhost:6789") }))
{
host.AddServiceEndpoint(typeof(IService1), new NetTcpBinding(), "Service1");
host.Open();
Console.ReadLine();
host.Close();
}
}
}
Created the client.
public class CallbackHandler : IService1Callback
{
public void SetData(Configuration config)
{
Console.WriteLine(config.CredentialValues.GetType().Name);
Console.WriteLine(((CustomCredentials)config.CredentialValues).Property1);
Console.WriteLine(((CustomCredentials)config.CredentialValues).Property2);
}
}
class Program
{
static void Main(string[] args)
{
// Setup the client
var callbacks = new CallbackHandler();
var endpoint = new EndpointAddress(new Uri("net.tcp://localhost:6789/Service1"));
using (var factory = new DuplexChannelFactory<IService1>(callbacks, new NetTcpBinding(), endpoint))
{
var client = factory.CreateChannel();
client.GetData();
Console.ReadLine();
factory.Close();
}
}
}
Outputs the following as expected:
CustomCredentials
Something
Something else
So this actually worked without modifying any of your data contracts... The same results if I revert to a twoway operation and just return Configuration directly without using the callback.
Also tried making Credentials abstract but could not replicate your problem.
Have I missed something?

WCF shared IClientMessageInspector instance across multiple clients

I'm managing a shared auth cookie when making WCF service calls via this methodology outlined under the header "Centralized cookie management" located here: http://megakemp.com/2009/02/06/managing-shared-cookies-in-wcf/
I've set up a custom IClientMessageInspector, IEndpointBehavior, BehaviorExtensionElement, the works. My endpoint behavior adds a message inspector as follows:
public class MyEndpointBehavior : IEndpointBehavior
{
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
// yuck.. Wish I had an instance of MyClientMessageInspector
// (which has the auth cookie already) so I could just inject that
// instance here instead of creating a new instance
clientRuntime.MessageInspectors.Add(new MyClientMessageInspector());
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
It all works flawlessly, but this solution breaks down when you want to share cookies over multiple clients. Because the ApplyDispatchBehavior() method creates a new instance, any other client wouldn't get that message inspector instance, and thus, the auth ticket.
So then I thought of trying to create a custom constructor where I could inject the instance like so:
MyEndpointBehavior(MyClientMessageInspector msgInspector) { ... }
But, WCF needs parameter-less constructors. Weeding through the internets, WCF has hooks to allow for dependency injection, creating an IInstanceProvider, IServiceBehavior, etc. But I don't think that's what I'm looking for here.
Can anyone help guide me in the right direction?
You need only extend the concept so that you store the cookie outside of the message inspector itself so that all instances of the message inspector share the same storage.
The poor man's way, just to get started, would be to just use a static field instead of an instance field. Obviously if you have multiple threads you'll need to provide concurrency while updating the field. From there you can get even fancier if you extrapolate it out to a cookie container concept and then just make sure you share the same container with all clients. Sharing the container can be done by getting the ChannelParameterCollection for the client channel and adding property to it and then your behavior looks for that property while it's inspecting the mssage and pulling the cookies out of that. That would look a little something like this:
App logic
// Hold onto a static cookie container
public static CookieContainer MyCookieContainer;
// When instantiating the client add the cookie container to the channel parameters
MyClient client = new MyClient();
client.InnerChannel.GetProperty<ChannelParameterCollection>().Add(MyCookieContainer);
Message inspector logic
public void BeforeSendMessage(ref Message, IClientChannel clientChannel)
{
// Find the cookie container for the current channel
CookieContainer cookieContainer = clientChannel.GetProperty<ChannelParameterCollection>().Select(p => p as CookieContainer).Where(cc => cc != null).First();
// ... use the cookie container to set header on outgoing context ...
}
You're correct, IInstanceProvider won't help in your case - it's used for providing service instances only. You don't need a parameterless constructor for your behavior. You need a paramterless constructor for the config element, and this class can use some dependency injection class (see below) to create the appropriate inspector class needed for the behavior.
namespace ConsoleApplication4
{
public class MyEndpointBehavior : IEndpointBehavior
{
IClientMessageInspector inspector;
public MyEndpointBehavior(IClientMessageInspector inspector)
{
this.inspector = inspector;
}
public void AddBindingParameters(ServiceEndpoint endpoint, BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(this.inspector);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
public class MyEndpointBehaviorElement : BehaviorExtensionElement
{
public override Type BehaviorType
{
get { return typeof(MyEndpointBehavior); }
}
protected override object CreateBehavior()
{
return new MyEndpointBehavior(ClientInspectorFactory.GetClientInspector());
}
}
public class MyClientInspector : IClientMessageInspector
{
public MyClientInspector()
{
}
public void AfterReceiveReply(ref Message reply, object correlationState)
{
Console.WriteLine("AfterReceiveReply");
}
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
Console.WriteLine("BeforeSendRequest");
return null;
}
}
public static class ClientInspectorFactory
{
static IClientMessageInspector instance;
public static IClientMessageInspector GetClientInspector()
{
if (instance == null)
{
instance = new MyClientInspector();
}
return instance;
}
}
[ServiceContract]
public interface ITest
{
[OperationContract]
int Add(int x, int y);
}
public class Service : ITest
{
public int Add(int x, int y) { return x + y; }
}
class Program
{
static void Main(string[] args)
{
ServiceHost host = new ServiceHost(typeof(Service));
host.Open();
Console.WriteLine("Host opened");
ChannelFactory<ITest> factory = new ChannelFactory<ITest>("client1");
ITest proxy = factory.CreateChannel();
Console.WriteLine(proxy.Add(3, 4));
((IClientChannel)proxy).Close();
factory.Close();
factory = new ChannelFactory<ITest>("client2");
proxy = factory.CreateChannel();
Console.WriteLine(proxy.Add(5, 8));
((IClientChannel)proxy).Close();
factory.Close();
host.Close();
}
}
}
I liked the answers provided by #carlosfigueira and #drew, but I ultimately came up with a slightly different approach. I opted to configure my IEndpointBehavior PROGRAMMATICALLY, vs via config. Made things much simpler. I changed my endpoint behavior to store my client message inspector as follows:
public class MyEndpointBehavior : IEndpointBehavior
{
private MyClientMessageInspector_myClientMessageInspector;
public MyClientMessageInspector MyClientMessageInspector
{
get
{
if (_myClientMessageInspector == null)
{
_myClientMessageInspector = new MyClientMessageInspector();
}
return _myClientMessageInspector;
}
}
public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
{
}
public void ApplyClientBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime)
{
clientRuntime.MessageInspectors.Add(MyClientMessageInspector);
}
public void ApplyDispatchBehavior(ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.EndpointDispatcher endpointDispatcher)
{
}
public void Validate(ServiceEndpoint endpoint)
{
}
}
Then I simply shared this behavior between clients, as follows:
var behavior = new MyEndpointBehavior();
client1.Endpoint.Behaviors.Add(behavior);
client2.Endpoint.Behaviors.Add(behavior);
Now both clients will share the same auth cookie.