How to check the availability of a net.tcp WCF service - c#

My WCF server needs to go up and down on a regular basis, the client sometimes uses the server, but if it is down the client just ignore it.
So each time I need to use the server services I check the connection state and if it's not open I open it.
The problem is that if I attempt to open while the server is down there is a delay which hits performance.
My question is, is there a way to do some kind of myClient.CanOpen()? so I'd know if there is any point to open the connection to the server.

There is an implementation of WS-Discovery that would allow you to listen for up/down announcements for your service. This is also a very convenient form of service address resolution because it utilizes UDP multicast messages to find the service, rather than configuring one set address on the client.
WS-Discovery for WCF
There's also an implementation done by a Microsoft employee:
WS-Discovery Sample Implementation
.NET 4.0 will include this natively. You can read about .NET 4.0's implementation on Jesus Rodriguez's blog. It has a great chart that details the ad-hoc communication that goes on in WS-Disco Using WS-Discovery in WCF 4.0
Another thing you might consider, especially if your messages are largely one-way, is a protocol that works natively disconnected, like MSMQ. I don't know what your design for your application looks like, but MSMQ would allow a client to send a message regardless of the state of the service and the service will get it when it comes back up. This way your client doesn't have to block quite so much trying to get confirmation that a service is up before communicating... it'll just fire and forget.
Hope this helps.

If you are doing a synchronous call expecting a server timeout in an application with a user interface, you should be doing it in another thread. I doubt that the performance hit is due to exception overhead.
Is your performance penalty in CPU load, gui availability or wall clock time?
You could investigate to see if you can create a custom binding on TCP, but with faster timeout.
I assume you know that "IsOneWay=true" is faster than request->response in your case because you wouldn't be expecting a response anyway, but then you are not getting confirmation or return values.
You could also implement a two-way communication that is not request->response.

If you were in a local network it might be possible to broadcast a signal to say that a new server is up. The client would need to listen for the broadcast signal and respond accordingly.

Here's what I'm using and it works like a charm. And btw, the ServiceController class lives in namespace 'System.ServiceProcess'.
try
{
ServiceController sc = new ServiceController("Service Name", "Computer's IP Address");
Console.WriteLine("The service status is currently set to {0}",
sc.Status.ToString());
if ((sc.Status.Equals(ServiceControllerStatus.Stopped)) ||
(sc.Status.Equals(ServiceControllerStatus.StopPending)))
{
Console.WriteLine("Service is Stopped, Ending the application...");
Console.Read();
EndApplication();
}
else
{
Console.WriteLine("Service is Started...");
}
}
catch (Exception)
{
Console.WriteLine("Error Occurred trying to access the Server service...");
Console.Read();
EndApplication();
}

I don't think it's possible doing a server side call to your Client to inform him that you the service has been started ... Best method i can see is having a client method figuring out where or not the service is open and in good condition. Unless I am missing some functionality of WCF ...
There is a good blogpost WCF: Availability of the WCF services if you are interested in a read.

Related

How to implement two way communication with gRpc?

For various reasons, over the years the company I work for have invested considerably into using Windows Communication Foundation (WCF). We are currently in the process of upgrading our main development platform from Visual Studio 2015 to Visual Studio 2022. Sadly, we are discovering that our WCF client and server applications need more work than we expected to upgrade them to Visual Studio 2022 and newer .NET frameworks; they certainly are not as slick as they used to be. We are planning on keeping our existing applications that use WCF as they are but are considering other options for new applications. The main option that seems to be the one being pushed is gRpc, however, from what I have learnt about it so far, for some of the kinds of things we want to do, it would seem to be a very poor substitute. For us some of the key things we value in WCF are:
One way function calls (i.e. a call that so long as we know gets
delivered, we do not need to wait until it completes). I understand
that this is achievable with gRpc.
Full two way communication (i.e.
clients can make calls onto the server, and also the other way
around; the server can make calls onto the clients). I understand
that using “streams” this can be approximated to with gRPC, but not
easily.
To illustrate, consider a simplified scenario involving three application types:
Sound Requester. An application that requests the playing of different sounds at different locations, and also change the sound parameters.
Sound Player. An application that can play requested sounds and change their parameters. It can give notification that a sound has finished.
Sound Handler Proxy. An application that sits between sound requesters and sound players.
Our WCF implementation of this has the Sound Handler Proxy as the WCF server, the Sound Requester and Sound Player applications are clients that connect to the server. This suits us nicely; the proxy does not need to know which players and requesters to connect to, they connect to it (and can do so at any time). The proxy just provides a ‘marshalling’ service. Below is a simplified sequence diagram to illustrate the kind of calls that could be made:
My question is “If implementing this using gRpc, how would we implement the calls on SoundPlayer (e.g. CreateSound, PlaySound etc.)?” If my understanding is correct, since SoundPlayer is a client (not a server), we would need to implement these as streams that come as ‘returns’ from a call from the player to the server. Is there an easier way? (I appreciate that we could make the SoundPlayer a server that the SoundHandlerProxy could connect to as a client – but that would mean the proxy would need to know about all the players it is going to connect to, something we would rather avoid.)
Alternatively, is there something other than gRpc that we could migrate to (preferably, something that is going to be stable for at least the next decade)?
I'm not a .Net expert, so I may get some details wrong. But I think the gist is right.
One-way services aren't all that interesting on-the-wire, as they are still use HTTP request/response. From the One-Way Sample
When the operation is called, the service returns an HTTP status code of 202 before the service operation has executed... The client that called the operation blocks until it receives the 202 response from the service.
So they are more of a stub feature and can be emulated without too much trouble in gRPC. In gRPC, you'd define the method to return google.protobuf.Empty, and on server-side start long-running work in another thread and return immediately.
service Foo {
rpc Bar(BarRequest) returns (google.protobuf.Empty);
}
public class FooService : Foo.FooBase
{
public override Task<Empty> Bar(BarRequest request,
ServerCallContext context)
{
startProcessingInAnotherThread(request);
return Task.FromResult(new Empty {});
}
}
Full two way communication seems to be the same as Duplex Services. These work by configuring the client to know how the server can reach it (its host:port). Then the client sends that information to the server for the server send RPCs back to it in the future. There are definitely security impacts of such a design and you should look into the security model you are using.
This would be emulated in gRPC by the client just sending the server a channel address string and then the server creating a channel to that address.
service SoundHandler {
rpc Connect(ConnectRequest) returns (google.protobuf.Empty);
}
message ConnectRequest {
enum Type {
TYPE_UNKNOWN = 0;
TYPE_SOUND_REQUESTER = 1;
TYPE_SOUND_PLAYER = 2;
};
string channelAddress = 1;
Type type = 2;
}
service SoundPlayer {
rpc CreateSound(CreateSoundRequest) returns (CreateSoundResponse);
// ...
}
service SoundEventReceiver {
rpc SoundFinished(SoundFinishedRequest) returns (SoundFinishedResponse);
}
Then, in the service you'd create a channel to the provided address for callbacks.
public class SoundHandlerService : SoundHandler.SoundHandlerBase
{
public override Task<Empty> Bar(ConnectRequest request,
ServerCallContext context)
{
var channel = GrpcChannel.ForAddress(request.channelAddress);
if (request.type == TYPE_SOUND_PLAYER) {
var channel = GrpcChannel.ForAddress(request.channelAddress);
var client = new SoundPlayer.SoundPlayerClient(channel);
registerSoundPlayer(channel, client);
} // ...
return Task.FromResult(new Empty {});
}
}

C# - WCF Duplex => Fire an event when a client disconnect

I'm trying to let my service knows when one of the clients is disconnected.
I'm using wsDualHttpBinding.
Currently, I'm tried to use this event :
OperationContext.Current.Channel.Closed += new EventHandler((sender, e) => ClientIsDisconnected(sender, e, currentCallbackChannel));
But this event is never fired...
Please help me to know how it'd be done !
Edit :
Thanks to anderhil, I finally replaced wsDualHttpBinding by netTcpBinding (with the appropriate configuration described here : http://msdn.microsoft.com/en-us/library/ff647180.aspx#Step1).
With netTcpBinding, the Closed event fires without any problem... Still don't know why but it works.
The issue you are having is likely becuase of WsDualHttpBinding. In case you have this binding, two connections are created, from client to service and from service to client.
When the application is deployed over the internet it can create some issues with supporting such applications, you need to be sure that people are not behind the firewall or NAT or etc that can prevent your service to connect back to client.
I still don't know why it doesn't work on local machine when testing, but i will try to resolve it and update the answer.
As you told me more details in our chat, from the nature of your application it's better to use NetTcpBinding. In this case it's easier to understand what is happening cause one connection is created, and you will receive the notifications in case of gracefull close or abort of client.
As i told you before, anyway it's better to create some heartbeat mechanism to have things more reliable in case of unexpected computer or router shutdown.
Also, you can find this good cheat sheet on how to select communication between parties that involve WCF:
The Closed event should occur on a graceful disconnect; is that what's happening?
To detect the pure socket disconnect, listen for the Faulted event:
OperationContext.Current.Channel.Faulted += new EventHandler(FaultedHandler);

WCF - Client callback vs. polling for "keep list of subscribers"

I want to create a simple client-server example in WCF. I did some testing with callbacks, and it works fine so far. I played around a little bit with the following interface:
[ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IStringCallback))]
public interface ISubscribeableService
{
[OperationContract]
void ExecuteStringCallBack(string value);
[OperationContract]
ServerInformation Subscribe(ClientInformation c);
[OperationContract]
ServerInformation Unsubscribe(ClientInformation c);
}
Its a simple example. a little bit adjusted. You can ask the server to "execute a string callback" in which case the server reversed the string and calls all subscribed client callbacks.
Now, here comes the question: If I want to implement a system where all clients "register" with the server, and the server can "ask" the clients if they are still alive, would you implement this with callbacks (so instead of this "stringcallback" a kind of TellTheClientThatIAmStillHereCallback). By checking the communication state on the callback I can also "know" if a client is dead. Something similar to this:
Subscribers.ForEach(delegate(IStringCallback callback)
{
if (((ICommunicationObject)callback).State == CommunicationState.Opened)
{
callback.StringCallbackFunction(new string(retVal));
}
else
{
Subscribers.Remove(callback);
}
});
My problem, put in another way:
The server might have 3 clients
Client A dies (I pull the plug of the laptop)
The server dies and comes back online
A new client comes up
So basically, would you use callbacks to verify the "still living state" of clients, or would you use polling and keep track "how long I havent heard of a client"...
You can detect most changes to the connection state via the Closed, Closing, and Faulted events of ICommunicationObject. You can hook them at the same time that you set up the callback. This is definitely better than polling.
IIRC, the Faulted event will only fire after you actually try to use the callback (unsuccessfully). So if the Client just disappears - for example, a hard reboot or power-off - then you won't be notified right away. But do you need to be? And if so, why?
A WCF callback might fail at any time, and you always need to keep this in the back of your mind. Even if both the client and server are fine, you might still end up with a faulted channel due to an exception or a network outage. Or maybe the client went offline sometime between your last poll and your current operation. The point is, as long as you code your callback operations defensively (which is good practice anyway), then hooking the events above is usually enough for most designs. If an error occurs for any reason - including a client failing to respond - the Faulted event will kick in and run your cleanup code.
This is what I would refer to as the passive/lazy approach and requires less coding and network chatter than polling or keep-alive approaches.
If you enable reliable sessions, WCF internally maintains a keep-alive control mechanism. It regularly checks, via hidden infrastructure test messages, if the other end is still there. The time interval of these checks can be influenced via the ReliableSession.InactivityTimeout property. If you set the property to, say, 20 seconds, then the ICommunicationObject.Faulted event will be raised about 20 to 30 (maximum) seconds after a service breakdown has occurred on the other side.
If you want to be sure that client applications always remain "auto-connected", even after temporary service breakdowns, you may want to use a worker thread (from the thread pool) that repeatedly tries to create a new proxy instance on the client side, and calls a session-initiating operation, after the Faulted event has been raised there.
As a second approach, since you are implementing a worker thread mechanism anyway, you might also ignore the Faulted event and let the worker thread loop during the whole lifetime of the client application. You let the thread repeatedly check the proxy state, and try to do its repair work whenever the state is faulted.
Using the first or the second approach, you can implement a service bus architecture (mediator pattern), guaranteeing that all client application instances are constantly ready to receive "spontaneous" service messages whenever the service is running.
Of course, this only works if the reliable session "as such" is configured correctly to begin with (using a session-capable binding, and applying the ServiceContractAttribute.SessionMode, ServiceBehaviorAttribute.InstanceContextMode, OperationContractAttribute.IsInitiating, and OperationContractAttribute.IsTerminating properties in meaningful ways).
I had a similar situation using WCF and callbacks. I did not want to use polling, but I was using a "reilable" protocol, so if a client died, then it would hang the server until it timed out and crashed.
I do not know if this is the most correct or elegant solution, but what I did was create a class in the service to represent the client proxy. Each instance of this class contained a reference to the client proxy, and would execute the callback function whenever the server set the "message" property of the class. By doing this, when a client disconnected, the individual wrapper class would get the timeout excetpion, and remove itself from the server's list of listeners, but the service would not have to wait for it. This doesn't actually answer your question about determining if the client is alive, but it is another way of structuring the service to addrss the issue. If you needed to know when a client died, you would be able to pick up when the client wrapper removed itself from the listener list.
I have not tried to use WCF callbacks over the wire but i have used them for interprocess communication. I was having a problem where call of the calls that were being sent were ending up on the same thread and making the service dead lock when there were calls that were dependant on the same thread.
This may apply to the problem that you are currently have so here is what I had to do to fix the problem.
Put this attribute onto the server and client of the WCF server implemetation class
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WCFServerClass
The ConcurrencyMode.Multiple makes each call process on its own thread which should help you with the server locking up when a client dies until it timesout.
I also made sure to use a Thread Pool on the client side to make sure that there were no threading issues on the client side

Is It possible to use WCF(C#) in that environment ?

I have several "blackbox" that sends data to determinated IP and PORT, I can´t specify anything else (just IP and PORT)...
My server should be listening that PORT and catch information to send to MSMQ...
How can I set a WCF server to listening that PORT?
Thanks!
I would write a normal windows service that listens for the data.
Use the TCPListener or a similar class
Then plug on WCF as a seperate service that your windows service calls to write to the message queue, it's just a matter of configuration.
[ServiceContract]
public interface IDaraWriterService
{
[OperationContract]
public void WriteDataToQueue(WriteDataToQueueMessage theDataEncapsulatedInAMessage)
{
}
}
Your windows service could probably write to the queue directly btw.
See here for more info on the message queue. http://msdn.microsoft.com/en-us/library/ms811053.aspx
If you can control what's pushing data to the IP address/port, then yes, you could use WCF. Unfortunately, without some sort of contract/binding to specify the means by which your "server" and your "client" communicate, WCF won't help you much.
So if you can't control the client code, you'll need to "roll your own" listener. As #Rob Stevenson-Leggett suggested: TcpListener
Edit:
Thanks Randolpho... So, I´ll develope
a Windows Service with the listener
and add the message to MSMQ. And in
the otner hand, I need a module to
read the queue (MSMQ) and add that to
DB... That module could be in WCF?
What you think?
Yep. WCF provides the MsmqIntegrationBinding for communicating on either end with an MSMQ.
Here's a nice tutorial:
http://msdn.microsoft.com/en-us/library/ms789008.aspx

C# Testing active internet connection. Pinging google.com

C# 2008
I am using this code to test for an internet connection. As my application will have to login to a web server. However, if the user internet connection was to fail or cable pulled out. I will have to notify the user.
// Ping www.google.com to check if the user has a internet connection.
public bool PingTest()
{
Ping ping = new Ping();
PingReply pingStatus = ping.Send(IPAddress.Parse("208.69.34.231"));
if (pingStatus.Status == IPStatus.Success)
{
return true;
}
else
{
return false;
}
}
The only way I think I can test for an Internet connection is to ping www.google.com. So I have a used a server timer which I have set for 500 milliseconds and in the lapsed event it will call this ping function. If the ping returns false. Then my app will take appropriate action.
Do you think using google as a way to test an Internet connect is a good thing. If google was to fail, then my app would not function. Is polling 1/2 second to much or too little? Just wondering about my whole idea if it is good or not?
Many thanks,
Why ping Google? The only server you really care about is the web server you want to talk to, right? So ping that instead. That way, you can notify the user if anything is wrong between them and the web server - that's the only thing that matters.
If something goes wrong with the internet which means that the user can only do anything within their own town, you may not be able to reach Google but if you can still reach the web server you're interested in, why report a problem? On the other hand, if the web server goes down but Google doesn't, why would you not want to tell the user that there's a problem?
Likewise, why use a ping? Why not send an HTTP request to a known URL on the web server? After all, if the network is up but the web server process itself is down, surely that's just as bad as the user's network going down.
EDIT: I hadn't noticed in the question that you were repeating this every half second. That's really not pleasant for anyone. Surely once a minute is often enough, isn't it?
Check out this duplicate question which has a good answer that doesn't require ping:
C# - How do I check for a network connection
You could subscribe to the System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged event and only then when it indicates that the network is down do a ping/web request to the server to see if it's available.
I might be missing something but, Why do you need to test that the server is up and the web service running before you need to use it? If you call a method in your web services and you don't get a timely response, then take what ever action you see fit or need?
It just seems over engineering of the design.
[edit]
Thanks for the clarification robUK. You should listen to NET Rocks podcast episode 'Udi Dahan Scales Web Applications!' (date 12/08/2008). They discuss adding a GUID to a request and wait until you get the same GUID in the response. Maybe you could fire it off every second for say 10 attempts and if you don't get a response back (with the GUID attached) after 10 attempts, then take the required action?
Good luck with it..
I have an app that needs to do something similar. We have a bit of a different architecture in place, namely a pub/sub message bus. For those applications interested in hearing "heartbeats" from the various services, we allow them to register their interest with the bus. Every few second or so, each service will publish a health state message that consumers will then receive. If the consumers do not receive a health state message for a certain amount of time, they can take appropriate action until they hear it again.
This setup is much more scalable than polling the server or even worse pinging it. Imagine if you had 100 or 1000 clients all polling or pinging your sever every few seconds. Bad.
you can simply test like this
[DllImport("wininet.dll")]
private extern static bool InternetGetConnectedState(out int conn, int val);
C# full source code
http://net-informations.com/csprj/communications/internet-connection.htm
It'd suggest to put more than 0.5s, because sometimes your lataency can get higher. I sometimes have even 3.5s on DSL.
Better to see if you are on the network than to bother a server pinging it. See Detect Internet V. local lan connection for example. If you are on Windows 7 / Server 2008 R2 you can get an event when connectivity changes, which is going to be much happier for everyone than constant pinging and polling.
Even though I agree with Jon that pinging your webserver might be the best idea I want to throw in another solution that might be used stand alone or together with an initial ping to the service.
These is a built in event on the NetworkChange-class called NetworkAvailabilityChanged that you can use to get the overall status from Windows whether you are online or not. Just add a listener to it and then you will be notified when it changes.
private void MyForm_Load(object sender, EventArgs e)
{
NetworkChange.NetworkAvailabilityChanged += new NetworkAvailabilityChangedEventHandler(NetworkChange_NetworkAvailabilityChanged);
}
private void NetworkChange_NetworkAvailabilityChanged(object sender, NetworkAvailabilityEventArgs e)
{
if (e.IsAvailable)
{
WriteLog("Network is available again, updating items");
timer1_Tick(sender, EventArgs.Empty);
return;
}
WriteLog("Network isn't available at the moment");
}
It's available from .Net 2.0 and onward. More info can be found on MSDN.

Categories