c# Timer: HTTP connection error after system wake-up - c#

I have a Timer in a C# app (Win7 64). Every 20 min the timer callback gets some data via HTTP. It works well. But if my PC goes to sleep for a few hours, then wakes up, I get an HTTP error saying "can't find the server". The server is running at all times, so it's not the real issue. I suspect the real reason is that as the timer callback misses its "time slot" during the sleep period, it becomes "overdue" and is executed instantly right after the wake-up, without waiting for the PC to re-establish the Internet connection. I can fix the problem by adding a Thread.Sleep(5000) at the beginning of the callback, but it's a bit of a kludge (establishing Internet connection might take longer). My questions:
After a wake-up from sleep mode, does Win indeed need a few seconds to re-establish Internet connection? My connection is DSL, "always online".
Is there a C# system call which would wait until Win establishes the Internet connection (or time out if this doesn't happen within, say, 20 secs)?
EDIT: Just found this: Check Net connection in C#. Not as simple as I hoped, it takes a sequence of checks: any LAN connection, DNS lookup (outside the LAN), ping a server (check a particular server).

1) Yes
2) You may check various connection attributes via WMI for example. See: http://msdn.microsoft.com/en-us/library/windows/desktop/aa394595%28v=vs.85%29.aspx
and
http://msdn.microsoft.com/en-us/library/windows/desktop/aa394216%28v=vs.85%29.aspx
to make sure you have a connection before attempting a query.

I don't think you should bother with WMI and such.
If you cannot access the network, set the timer to fire in a minuts instead of 20. You alrsady have a waiting mechanism in place, reusing it will not seem kludgy.

Related

c# named pipes detect server shutdown

In c# namedpipes have the horrible characteristics to get into loops of full cpu load during connecting (waiting for server), and in my case, also when the server is closing leaving the client alone. And this is my question: Can the client detect a server shutdown (server disconnect) by events?
Currently I run a timer, testing the connection every 2nd second. This works as I can close the connection in the client and dispose the namedpipeclientstram what stops the high cpu load. However it means in worst case there is very high cpu load for up to 2 seconds.
However to avoid any high cpu load at all I´m searching an kind of event system to detect one-sided connection shutdown of the server in the client. Is there any? I have not found anything so far.
It would be also ok to force the client stream not to seek reconnection when
server is closing (at least it looks like this is happening as it resembles very much the cpu state during a wait for the server)
The connection is bidirectional and async.
One more question about named pipes: When the server is up and ready, would it be ok to try to connect as client with a specified timeout of 0? Does this specify at least one trial, immediatly returning if server is not up?
Or does the timeout has be at least as high as network delays or server response times are ?
Thx for help
Stefan

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

Sql connection waits 15 seconds despite 3 seconds timeout in connection string

I have a website using Microsoft SQL 2008 server over local network. Sometimes, SQL server machine is rebooted, and so the website fails to connect to the database. If the machine is up and running, it will respond fast. If it's down, there is no need to wait for 15 seconds. 3 seconds are ok.
I want to display apologizes on the website when the database is not reachable, and want to do it fast. But setting Connection Timeout=3 in connection string seems having no effect. The page spends 22 seconds to wait before throwing SqlException on SqlConnection.Open();.
What's wrong with it? May it be a hidden configuration which overrides the timeout?
Currently, my connection string is
Data Source=...;
Initial Catalog=...;
Integrated Security=True;
Connection Timeout=3
If I set it to ...;ConnectionTimeout=3 (without space),
System.ArgumentException: Keyword not supported: 'connectiontimeout'.
is thrown (strange, MSDN documentation indicates that we can use both strings).
There is a timeout before the networking hardware reports connection timeout to the network drivers, which in turn notifies the programs waiting for network IO. You can verify transport layer timeouts via telnet servername 1433 (assuming your sql server is listening on port 1433).
But 3 seconds is way too short for a process to initialize the network APIs (assuming your web app is in its own application pool), send request and wait for the hardware to timeout. Updating BIOS/firmware/driver probably won't reduce the response time that much.
It would be better to carry out the connection asynchronously. i do not suggest using EndInvoke to end the asynchronous call as unlucky users may still need to wait 3 full seconds to see any response when the database is down. Maybe an Ajax call is better. If you have a lot of users constantly hitting your web site, you may want to cache the result of connectivity checking and update it in a manner meaningful to your users.
The following blog post assisted me in solving this problem:
http://improve.dk/controlling-sqlconnection-timeouts/
ConnectionTimeout without space is the property name when accessing via code, not for the connection string.
Not sure if this is of use, but when I hit this issue in the past, it was because I also needed to set SqlCommand.CommandTimeout. What happened for me is the connection was opened successfully, then DB server went down, then my next command did not timeout as quickly as I expected based on the Connection Timeout, and this was due to the CommandTimeout needing to be set as well.

Socket Connection Error

I am facing a wierd socket connection problem in .net windows application.I am using socket from .net to asynchonously communicate to a legacy intersystems cache database.I have a specific timeout value in the application, when the timeout occurs, user is prompted to stay connected to the application. When I say stay connected, socket is not being reset. I set timeout to 30 mins and say stay connected for first idle time.Then when I navigate the application it works fine.
If with out navigating in the application and say stay connected second time, and navigate in the app I am getting socket "host refused" connection error. This I can assume may be socket is terminated. But the wierd part is if I set the application timeout to 10 mins, then also I am getting socket error second time. When I check the sockets connected property, it is still true. I am not catching exception when I call sockets Send method. But the data is not passed from the socket.I have checked the other .net code. it is fine. This problem also occurs rarely, only 1 in 10 times. Any suggestions will be greatly helpful.
This sounds like a typical issue resulting from firewalls or other TCP settings.
Firewalls might silently disconnect the connection if it is idle more than x seconds.
As the TCP protocol does not generate an event in such a case (similar like just removing the network cable), it is highly recommended to send ping message every x seconds, so that the firewall stays open and that you can be sure to be connected. if the ping is missed, the server disconnects the client.

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

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...

Categories

Resources