Best way to check if server is reachable in .NET? - c#

I have created a timeclock application in C# that connects to a web service on our server in order to clock employees in/out. The application resides in the system tray and clocks users out if they shut down/suspend their machines or if they are idle for more than three hours to which it clocks them out at the time of last activity.
My issue arises that when a user brings his machine back up from a sleep state (which fires the SystemEvents.PowerModeChanged event), the application attempts to clock the employee back in but the network connection isn't fully initialized at that time and the web-service call times out.
An obvious solution, albeit it a hack, would be to put a delay on the clock in but this wouldn't necessarily fix the problem across the board. What I am looking to do is a sort of "relentless" clock in where it will wait until it can see the server until it actually attempts to clock in.
What is the best method to determine if a connection to a web service can be made?

The best way is going to be to actually try to make the connection and catch the errors. You can ping the machine, but that will only tell you if the machine is running and on the network, which doesn't necessarily reflect on whether the webservice is running and available.

When handling the event, put your connection code into a method that will loop through until success, catching errors and retrying.
Even a delay wouldn't be perfect as depending on the individual systems and other applications running it can take varying times for the network connection to be re-established.

Implement a queue where you post messages and have a thread periodically try to flush the in-memory queue to the web service.

if the problem is latency in re-establishing the network service, Ping is the solution; it's like ringing the doorbell to see if anyone is home
if ping succeeds, then try calling the web service, catching exceptions appropriately (I think both SocketException and SoapException can occur depending on readiness/responsiveness)

Ping can be disabled although the web service port is open. I wouldn't use this method...

Related

SignalR Persistent connection starts timing out "poll" requests from clients and does not recover after restart

I have a weird problem with SignalR persistent connection. It runs within a mono-service written on c# and uses long polling transport. The application runs on a Ubuntu VM inside KVM. The communication between the application and HTML/js clients is mostly normal, but at some point for some reason every newly created connection behaves the following way : the connection is established and OnConnected method gets called, however, when client issues "poll" request, it times out. In 100% cases when the application enters this state, restarting it does not help : "poll" requests from clients still get timed out. The only thing that helps out is rebooting the entire VM. Is there anyone, who has ever experienced something like that? Does SignalR persist any connection data to the filesystem, which could be a reason why, after the application is restarted, it still times out long polling requests ?
Stupid me! The problem had to do with database access which was happening during authorization of SignalR connection. The DB access layer was poorly designed, and the DB would become locked from time to time. The authentication procedure would then wait for DB lock to be released and eventually - time out. As a piece of advice for everyone reading this anecdote : in PersistentConnection case be sure that no IO-heavy stuff is happening inside AuthorizeRequest method! Or if you cannot avoid that, it should be very carefully designed, or else you are asking for timeouts.

How to write a continuously listening server as a service

I am writing one server which will listen for the client connections continuously. It doesn't need any user interactions. So, I am trying to make it as a service. I installed it successfully, but it didn't run successfully except for showing error 1053. I found that the start/stop method should return within 30 seconds. As far as I am concerned that means my server should halt its action and return within 30 seconds. I cant imply this constraint on the server because the client may connect at any time. Can anybody show me a way to install this server as a service?
Note 1: I am using windows platform, c# language and VS 2010.
Note 2: Other ideas are also welcomed.
Without seeing your code, and going on just what you are saying here I would say you should implement threading.
Right now your application starts running and just blocks until a client connects. That isn't best practice, or for a Windows Service it's even impossible because of the 30 sec. limit.
What you should do is start the service and initialize everything (so it will return within 30 sec.) and then start a different listening thread. What also might be a good idea is to start another thread when a client connects. In that case you can handle multiple clients instead of just one.
Of course I have no idea of what transport layer or such you are using, but check out this example based on TCP: http://www.switchonthecode.com/tutorials/csharp-tutorial-simple-threaded-tcp-server

WCF communication between 2 servers crashes after IIS7 process recycle

I am kind of stumped with this one, and was hoping I could find some answers here.
Basically, I have an ASP.NET application that is running across 2 servers. Server A has all of the business logic/data access exposed as web services, and Server B has the website which talks to those services (via WCF, with net.tcp binding).
The problem occurs a few seconds after a recycle of my app pool is initiated by IIS on Server A. The recycle happens after the allotted time (using the default of 29 hours set in IIS).
In the server log (of Server A):
A worker process with process id of
'####' serving application pool
'AppPoolName' has requested a recycle
because the worker process reached its
allowed processing time limit.
I believe that this is normal behavior. The problem is that a few seconds later, I get this exception on Server B:
This channel can no longer be used to
send messages as the output session
was auto-closed due to a
server-initiated shutdown. Either
disable auto-close by setting the
DispatchRuntime.AutomaticInputSessionShutdown
to false, or consider modifying the
shutdown protocol with the remote
server.
This doesn't happen on every recycle; I assume that it happens when someone is hitting the site with a request WHILE the recycle happens.
Furthermore, my application is down until I intervene; this exception continues to occur every time a subsequent request is made to the page. I intervene by editting the web.config (by adding a space or something benign to the end of file) and saving it- I assume that that causes my application to recompile and brings the services back up. I also have experimented with running a batch file that does this for me every time the exception happens ;)
Now, I could barely find any information on this exception, and I've been looking for a while. Most of the information I did find pertains to WCF settings that I am not using.
I already read up on "DispatchRuntime.AutomaticInputSessionShutdown" and I don't think it pertains to this situation. This particular property refers to the service shutting down automatically in response to behavior on the client side, which is not what is happening here. Here, the service is shutdown because of IIS.
I did read this which went through some sort of work around to bring the service back up automatically, but I am really looking to understand what is going on here, not to hack around it!
I have started playing around with the settings in IIS7, specifically turning on/off Overlapped Recycling and increasing the process startup/shutdown times. I am wondering whether it is safe to turn off recycling completely (I believe if I put 0 for the recycling time interval?) But again, I want to know what's going on!
Anyway, if you need more information, let me know. Thanks in advance!
This is probably related to how you open and close WCF connections.
If you open a proxy when your app starts and then continue to use this, a break in the connection, which is caused by a restart on the server side. Results in a error on the client side, since the server that the proxy was talking to is no longer there.
When you restart the client side (changing the web.config) new proxies are created against a server that is running.
The way to fix this is to make sure that you close a WCF connection after you use it.
http://www.codeguru.com/csharp/.net/net_wcf/article.php/c15941/
You should also make sure that you're using the correct SessionMode for your Web Service. I remember having similar trouble with some of my Services until I sorted out the correct mode. This is especially true when you're mixing this with any other authentication mode that is not "None".
This link might have some pointer.
http://msdn.microsoft.com/en-us/library/ms731193.aspx
My suggestion is to simply stop using IIS to host your services. Unless there is something you really need from IIS, I would recommend just writing a standard Windows Service to host your WCF endpoints.
If you can't do that, then by all means turn off recycling. AppPool recycling is mainly there because web developers write crappy code. I know that sounds rather blunt, but if you have enough sense to write code that doesn't leak then there is no reason to have IIS constantly restart your program.

Check if windows service has been forcefully shut down or crashed

I have a windows service written in C# .NET framework 3.5 and would like to know the best way to check if previous shutdown of a service was regular.
Upon starting the service, there should be a check if the last shutdown was regular (via stop service button in services management) or if somebody just killed the process (or it crashed for some reason not directly linked to the service itself).
I thought about writing encrypted XML on a hard drive upon starting a service, and then editing it with some values when service is being stopped. In that way, after I start the service again next time, I could check the XML and see if the values were edited in correct way during shutdown, and if they were not I'd know the process was killed or it crashed.
This way seems too unreliable and not a good practice. What do you suggest?
Clarification:
What the service does is it sits on a server and listens to connections from client machines. Once the connection has been established, it communicates to a remote database via web services and determines whether they have right to connect (and therefore use application that is the caller). One of the aspects of protection is concurrency check, and if I have a limit set to 5 work stations, I keep the TcpClient connection alive from windows service to, let's say 5 workstations, and the sixth one cannot connect.
If I kill the service process and restart it, the connections are gone and I have 5 "licensed" apps running on workstations, and now there are 5 free connection slots to be taken by 5 more.
I also cant see anything bad using a file. You could even use this file to log some more information.
Eg. you could attach to the AppDomains Unhanded Exception event and try to log that exception.
Or you could evaluate how log your service has been running/not running (parsing a logfile for that task is a little bit harder).
Of course - this is not an excuse for not using logfiles.
I went with this in the end:
Service used to check up on the connected workstations to see if they're alive, but now I've built in periodical check from all the workstations as well (they connect through a common router dll where I've built in the check). Every 10 seconds the connection is verified, and if there is none, the client will try to reconnect in 15 seconds, which will be successful if there was just a temporary network problem, but will fail if the service was shut down forcefully (since all it's Tcp objects will be lost).
I would suggest to use the EventLog. Add a log event when a service start or stops and read through the event logs to detect anomalies.
Here's a basic sample from CodeProject.
Here's a walkthrough from MSDN how to create/delete/read event logs and entries.
Unless the service is running some sort securiy system that you need to have a "tamper" proof system i dont see why using a file is a bad solution.
Personaly i think a encrpted xml file is overkill, a simple text file should be enough.
I think you are on the right track, I'm not sure why you want to edit the values, just use the file (or a registry key) as a marker to indicate that the service was started and is running. During a graceful shutdown remove the marker. You then just need to look for the existence of the marker to know whether you were shutdown gracefully or crashed.
If you are finding that the file isn't created reliably, then make sure you are closing and flushing and disposing of the file object rather than relying on the garbage collector.
--- EDIT following clarification ---
So the requirement is for a licensing system and not simply to determine if the service was shutdown gracefully. I'm guessing that the desire is for the 'licenses' to be cleared on a graceful shutdown and restored following a crash, the scenarios are interchangeable.
I would probably use a database backing store, with suitable security, to hold the license keys at the server. As each client connects and requests a license they are provided with a key that has to be presented for each communication from the client. The server is obviously verifying that the presented key is valid for the current session. Should the server be gracefully shutdown it can clear the key table, if it crashes then the keys would still be present and can be honoured. That's probably the simplest approach I can think of that's secure.
If there's yet more to the story then let us know.

Web-services calls locks up when network connection lost

I write GUI application on c# for .NET compact framework 1.0 SP3 platform that uses web-services to retrieve data from our server.
When I go far away from access point the connection is lost and next web-service call locks up whole application. Every call surround by try{...}catch{...}, but as far as I can see in logs process never returns from locked web-service call.
What is going on?
What is the timeout of the web service? Have you tried tweaking the timeout?
I would add a Thread.Sleep(5000); in the web service then set the timeout in the client to 2seconds then run with the debugger and make sure that the exception is being caught when it times out. Do this while connected to the network.
Then you'll want to display an error message of some kind if after a certain number of tries the service still times out. Then you'll want to wait for a configurable amount of time before retrying. You'll also want to let the user manually try to reconnect.
Timeout is set to 10 seconds. There is a record in logs that shows three catched exceptions and then web-service call locks up.

Categories

Resources