Publish/Subscribe Pattern in C# WCF - c#

How to register client on server to listen some change? I want to notify my client and send some data when something changed on my server. Also, I use NetTcpBinding. I tried many examples, but I can't get method from server to register in. I don't have any config file.
Thanks in advance.
There is example of registering client on server.
ChannelFactory<ITrending> factory = new ChannelFactory<ITrending>(
new NetTcpBinding(), new EndpointAddress(#"net.tcp://localhost:6000/ITrending"));
proxy = factory.CreateChannel();

You can use the CallBack functionality in WCF services , it can be used for sending the changes in any entity or object value. In this case, Client must act as a server and server as a Client to receive the updates based on the method in the Client which is receiving the changes.
More detailed explanation : http://www.dotnetcurry.com/wcf/721/push-data-wcf-callback-service

Related

SOAP Action mismatch trying to implement ONVIF server

I am trying to implement a C# WCF server to the ONVIF specifications at http://www.onvif.org/onvif/ver20/ptz/wsdl/ptz.wsdl. I have generated the contract code using
SvcUtil.exe http://www.onvif.org/onvif/ver20/ptz/wsdl/ptz.wsdl http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl
which generates Device and PTZ interfaces. I then created an implementation of the generated interfaces and expose that using a ServiceHost like this:
serviceHost = new ServiceHost(typeof(OnvifImpl), baseUri);
serviceHost.AddServiceEndpoint(typeof(Device), new WSHttpBinding(), "device_service");
serviceHost.AddServiceEndpoint(typeof(PTZ), new WSHttpBinding(), "ptz");
When I point Onvif Device Manager 2.2.250 (https://sourceforge.net/projects/onvifdm/) at my server, I get an exception in my server "The SOAP action specified on the message, '', does not match the HTTP SOAP Action, 'http://www.onvif.org/ver10/device/wsdl/GetScopes'.". Wireshark shows that the request does not have any SOAP header. However, as far as I can tell, the client was developed against the same WSDL files.
I am afraid I am completely new to ONVIF, SOAP, Web services and WCF, so I have no idea where the problem may be. I have seen various suggestions to modify the client, but that is not an option.
The answer is to use a custom binding to remove WS-Addressing. This is what the client code does, so I do the same to match. I am not entirely sure whether this is a "solution" or a "workaround" but it get the two talking.
var binding = new CustomBinding(new BindingElement[] {
new TextMessageEncodingBindingElement(MessageVersion.Soap12, Encoding.UTF8),
new HttpTransportBindingElement(),
});
serviceHost.AddServiceEndpoint(typeof(Device), binding, "device_service");
serviceHost.AddServiceEndpoint(typeof(PTZ), binding, "ptz");
The key difference is using MessageVersion.Soap12 instead of MessageVersion.Soap12WSAddressing10 which is the default.

How to send updates from server to clients?

I am building a c#/wpf project.
It's architecture is this:
A console application which will be on a virtual machine (or my home computer) that will be the server side.
A wpf application that will be the client app.
Now my problem is this - I want the server to be able to send changes to the clients. If for example I have a change for client ABC, I want the server to know how to call a service on the clients computer.
The problem is, that I don't know how the server will call the clients.
A small example in case I didn't explain it well:
The server is on computer 1, and there are two clients, on computers 2 and 3.
Client 2 has a Toyota car and client 3 has a BMW car.
The server on computer 1 wants to tell client 2 that it has a new car, an Avenger.
How do I keep track and call services on the clients?
I thought of saving their ip address (from calling ipconfig from the cmd) in the DB - but isn't that based on the WI-FI/network they are connected to?
Thanks for any help!
You could try implementing SignalR. It is a great library that uses web sockets to push data to clients.
Edit:
SignalR can help you solve your problem by allowing you to set up Hubs on your console app (server) that WPF application (clients) can connect to. When the clients start up you will register them with a specified Hub. When something changes on the server, you can push from the server Hub to the client. The client will receive the information from the server and allow you to handle it as you see fit.
Rough mockup of some code:
namepsace Server{}
public class YourHub : Hub {
public void SomeHubMethod(string userName) {
//clientMethodToCall is a method in the WPF application that
//will be called. Client needs to be registered to hub first.
Clients.User(userName).clientMethodToCall("This is a test.");
//One issue you may face is mapping client connections.
//There are a couple different ways/methodologies to do this.
//Just figure what will work best for you.
}
}
}
namespace Client{
public class HubService{
public IHubProxy CreateHubProxy(){
var hubConnection = new HubConnection("http://serverAddress:serverPort/");
IHubProxy yourHubProxy = hubConnection.CreateHubProxy("YourHub");
return yourHubProxy;
}
}
}
Then in your WPF window:
var hubService = new HubService();
var yourHubProxy = hubService.CreateHubProxy();
yourHubProxy.Start().Wait();
yourHubProxy.On("clientMethodToCall", () => DoSometingWithServerData());
You need to create some kind of subscription model for the clients to the server to handle a Publish-Subscribe channel (see http://www.enterpriseintegrationpatterns.com/patterns/messaging/PublishSubscribeChannel.html). The basic architecture is this:
Client sends a request to the messaging channel to register itself as a subscriber to a certain kind of message/event/etc.
Server sends messages to the channel to be delivered to subscribers to that message.
There are many ways to handle this. You could use some of the Azure services (like Event hub, or Topic) if you don't want to reinvent the wheel here. You could also have your server application track all of these things (updates to IP addresses, updates to subscription interest, making sure that messages don't get sent more than once; taking care of message durability [making sure messages get delivered even if the client is offline when the message gets created]).
In general, whatever solution you choose is plagued with a common problem - clients hide behind firewalls and have dynamic IP addresses. This makes it difficult (I've heard of technologies claiming to overcome this but haven't seen any in action) for a server to push to a client.
In reality, the client talks and the server listens and response. However, you can use this approach to simulate a push by;
1. polling (the client periodically asks for information)
2. long polling (the client asks for information and the server holds onto the request until information arrives or a timeout occurs)
3. sockets (the client requests server connection that is used for bi-directional communication for a period of time).
Knowing those terms, your next choice is to write your own or use a third-party service (azure, amazon, other) to deliver messages for you. I personally like long polling because it is easy to implement. In my application, I have the following setup.
A web API server on Azure with and endpoint that listens for message requests
A simple loop inside the server code that checks the database for new messages every 100ms.
A client that calls the API, handling the response.
As mentioned, there are many ways to do this. In your particular case, one way would be as follows.
Client A calls server API to listen for message
Server holds onto call, waiting for new message entry in database
Client B calls server API to post new message
Server saves message to database
Server instance from step 2 sees new message
Server returns message to Client A.
Also, the message doesn't have to be stored in a database - it just depends on your needs.
Sounds like you want to track users à la https://www.simple-talk.com/dotnet/asp.net/tracking-online-users-with-signalr/ , but in a desktop app in the sense of http://www.codeproject.com/Articles/804770/Implementing-SignalR-in-Desktop-Applications or damienbod.wordpress.com/2013/11/20/signalr-a-complete-wpf-client-using-mvvm/ .

How to make client automatically detect if WCF service is down or lost connection

I've looked at a bunch of threads like Detect if wcf service is activated but these solutions require the client to proactively detect if the WCF service is running. But what if I am in the middle of a transaction and the WCF service goes down or the connection is lost for some reason? In my testing there is no exception thrown; either nothing happens at all or that twirly circle thing just keeps going round and round. I want the client to detect if the service/connection is lost and gracefully tell the user it's down. I have timeouts set in my code:
NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
binding.OpenTimeout = TimeSpan.FromSeconds(15);
binding.SendTimeout = TimeSpan.FromSeconds(3000);
binding.ReaderQuotas.MaxStringContentLength = int.MaxValue;
this._engineChannel = new DuplexChannelFactory<IEngineApi>(this, binding, new EndpointAddress("net.pipe://localhost/Engine"));
But if I am in the middle of a transaction nothing actually happens; these timeouts don't seem to affect anything.
You can use one of the two approaches:
1
The two things I do are a telnet check to make sure the WCF process
has the socket open.
telnet host 8080 The second thing I do is always add an IsAlive method
to my WCF contract so that there is a simple method to call to check
that the service host is operating correctly.
public bool IsAlive() {
return true; }
Source: Pinging WCF Services
2
Use the Discovery/Announcement feature introduced in WCF 4.0
Discovery depends on the User Datagram Protocol (UDP). UDP is a connectionless protocol, and there is no direct connection required between the client and server. The client usages UDP to broadcast finding requests for any endpoint supporting a specified contract type. The discovery endpoints that support this contract will receive the request. The implementation of the discovery endpoint responds back to the client with the address of the service endpoints. Once the client determines the services, it invokes the service to set up call.
Simple usage example: http://www.codeproject.com/Articles/469549/WCF-Discovery

How to use a duplex wcf service to distribute messages to all clients?

I am building a simple duplex wcf service. In this service clients send messages to the server and the server distributes the message to all connected clients. However, despite the fact that I defined the ServiceBehavior attribute as
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)], only the client who sent the message receives it back from the server, while the other clients do not. I verified that there is just one instance of the server running.
What did I do wrong? I looked at other similar questions on the web, and they all say that I should define InstanceContextMode = InstanceContextMode.Single, which I already did.
Do you have a callback Contract. So that server will reply back to client.
Check the below tutorial for Implementing Callback Contract
Click here
Also check the below Project Event Notification server. This project is doing similar things what you want.
CodeProject Link
Feel free to ask me if you need any more clarification
You need to maintain the clistList as shown in the code snippet.
List<IMessageServiceCallback> clientList = new List<IMessageServiceCallback>();
public void Register()
{
IMessageServiceCallback callback = OperationContext.Current.GetCallbackChannel<IMessageServiceCallback>();
clientList.add(callback);
}
When you want to broadcast this message. You can iterate through the list and call the callback function to send message to clients.

Pass client id/information from a .NET client to a web socket service

Is there a way to pass client information (such as an Id, username or other contextual information) from the client as part of making a websocket connection from a .net client(console,silverlight etc)?
This is how I'm making the connection to the socket service.
using (WebSocket socket = new WebSocket(#"ws://"+Environment.MachineName+":4502/commandserver"))
{
socket.OnClose += socket_OnClose;
socket.OnData += socket_OnData;
socket.OnOpen += socket_OnOpen;
socket.Open();
}
The ctor has an overload that accepts an "origin" and a "protocol", not sure if this can be used for passing any client information. If not is there an API call I can make to pass in the client information as part of making the connection?
EDIT: I'm using the microsoft library for this and the sample service code adds the service object into a collection in it's ctor to keep track of client sessions. Hence I need a way to pass in some client data to the service object as part of the initial client connection so that I can use this to identify clients and send messages to specific clients (based on an ID for example) from the service.

Categories

Resources