How Do I Know the state is "Connecting" by InternetGetConnectedState - c#

I'm creating an application that will connect to WiFi automatically when the connection state is unconnected.
I used the wininet.dll for it and to used its InternetGetConnectedState() method.
However, I've encountered a problem that whenever I connect to WiFi and the Connection State is "Connecting", the InternetGetConnectedState() will return false (meaning, unconnected), and it will try to connect to WiFi again and again...
This is the code:
while (true) {
if (InternetGetConnectedState(out ConState,0))
{
(do something else)
}
else
{
(connect to wifi)
}
}
Is there any other method available to know the state of connection or should i wait using the same method until the state is changed? Any help will be appreciated.

I may have it wrong, but in the reference to the wininet.dll it's stated: "(InternetGetConnectedState) Returns TRUE if there is an active modem or a LAN Internet connection, or FALSE if there is no Internet connection", see source. I think it's possible that this dll is not able to recognize the wifi network. Otherwise, the statement would have included "router" in it's explanation. You can call the GetLastError function to get additional information.

Network List Manager gives all information about network states. You can take a look on its features using this demo code (there is exe in Release folder).

Related

Using Wifi Direct API in legacy mode disconnects every 2 minutes

I've got a problem with my soft ap solution. When i connect a client to the ap the connection gets established and everything works fine. But I've noticed that when i set a ping to the host, it looses connection every 2 minutes and then suddenly regains connection.
This unfortunatly is unnacceptable for my solution.
I found this link: On using the WiFi Direct Api on Windows?
, which describes the same problem, but the answer isn't clear enough and i would like a code example or a more elaborate explanation.
In my solution, I use this class:
https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifidirect.wifidirectadvertisementpublisher?view=winrt-19041
with legacy settings set to "enabled":
https://learn.microsoft.com/en-us/uwp/api/windows.devices.wifidirect.wifidirectlegacysettings.isenabled?view=winrt-19041
On using the WiFi Direct Api on Windows?
I have encountered exactly the same problem because I removed the following line from MS sample :
var wiFiDirectDevice = await WiFiDirectDevice.FromIdAsync(deviceInfo.Id);
It seems that if you don t create the wifiDirectDevice object, Windows will automatically disconnect the client two minutes later (although in the meantime you have been able to exchange some data).
What helped me was to compare my code with the following sample :
https://github.com/gerfen/WiFiDirectLegacyAPCSharp/blob/master/WiFiDirectHotspotManager.cs#L128
Note that I also encountered another problem when I added this line because an exception is triggered depending on the client device configuration ( see the following topic : Wi-Fi Direct UWP timeouts (Exception from HRESULT: 0x800705B4))

'No connection could be made because the target machine actively refused it'

I am working on a 'Smart Device Project' using .Net Framework 3.5. I am trying to connect to some Java SOAP services on a remote server.
In order to do that, I added 'Web References' to my project.
When I try to call my web service I get a WebException 'Unable to connect to the remote server' with the inner exception being 'No connection could be made because the target machine actively refused it'.
I searched quite a lot on the Web and StackOverflow and found a lot of ASP configuration and 'Unavaliable port' answers, but as I have another application using the exact same Service successfully, I can't get why the new one isn't getting through (It did sometimes through my tests so I suppose my client implementation isn't that bad)
I tried to look if there was some connection issue on the port by using some TcpClient:
System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient();
try
{
client.Connect("myServerName", 8087);
MessageBox.Show("Success");
} catch (Exception ex)
{
MessageBox.Show("Failure");
}
finally
{
client.Close();
}
This connection succeed.
Here is a sample on how I call my WebService:
WSServiceExtended srv = new WSServiceExtended();
srv.Proxy = new System.Net.WebProxy();
ServeurWSI wsi = new ServeurWSI();
srv.Url = "http://myServerName:8087/myServerApp/services/myService";
wsr = srv.login(wsi);
The service is called 'Extended' because I overrided the auto-generated one in order to add Cookie managment since I am using the Compact Framework. Following the sample in this thread:
https://social.msdn.microsoft.com/Forums/en-US/34d88228-0b68-4fda-a8cd-58efe6b47958/no-cookies-sessionstate-in-compact-framework?forum=vssmartdevicesvbcs
EDIT:
I made some new tests with the Web references and got it to work.
When I add the Web Reference, I have to put some Url to the Web Service. When I set it with the actual hostname instead of the 'localhost' everything is fine.
But then, since I set it manually to the real address just before the call, it shouldn't matter
srv.Url = "http://myServerName:8087/myServerApp/services/myService";
EDIT2:
I might have forgotten some specifics about my environnement.
The Web Services are exposed on my computer on some Tomcat Server.
The application I am working on is also developped on this computer (That's why I can add Web References by putting 'localhost' in the address)
The application is then deployed on a distant device (Windows CE) that will make calls the Web Services through WIFI (There, localhost wouldn't work then)
I tried calling the Web services from other computers successfully.
I'm beginning to think that there might be some differential between the called Url and the one that is set, otherwise, how would I have a difference in behaviour such as the one described in the first edit?
EDIT3:
Well..Seems like it's not a network issue but a .Net compact framework (usage?) issue...
The Url property of the Web Service implementation is simply ignored and the one in the Reference.cs is used in place.
If someone had some idea on how I could troubleshot this, I would really appreciate it.
That error means that you reached a server and the server said "no way". So you're either hitting the wrong server or the wrong port.
I find the telnet client is useful for testing stuff like this. From the command line, you can do:
telnet [servername] [port]
So something like:
telnet myServerName 8087
If it goes to a blank screen, then it connected successfully. If it does not connect, it'll tell you.
The telnet client is no longer installed by default in Windows 7+, so you'll have to install it. See here for instructions: https://technet.microsoft.com/en-ca/library/cc771275
If the connection does open, you could paste in an actual HTTP request to see what happens. A simple GET would look something like this:
GET /myServerApp/services/myService HTTP/1.1
Host: myServerName:8087
One reason for this error can be that the service binds to only a certain IP address. It could well be that the service only listens on the IP that is assigned to the host name, but not on the localhost IP (127.0.0.1).
For example:
If the host myServerName has the public IP 192.168.0.1, your service can choose to listen on all IPs assigned to the host (sometimes specifying 0.0.0.0), or it can specifically listen on 192.168.0.1 only. In that case you will not be able to connect through 127.0.0.1, because the service simply doesn't listen on that IP.
You can "use" this inverse of this feature to make a service accessible only to local clients, not on the public IP-Address, by listening on 127.0.0.1 only, but not on the public IP. This is sometimes used on Linux for example to make MySQL only accessible on the host itself.
I was starting to forget this post but I finally found the problem that was messing things up and it has nothing to do with programmation.
I was doing the calls while the device was connected to the computer via the 'Windows Mobile Device Center' allowing to access the device from Windows.
While connected, the host provided is ignored and all calls on the specified port are handled by the connected computer.
Disconnecting the device allows to communicate properly...

how to stop trying to connect by namedpipe client to server if the server is not ready or unavailable

I'm now implementing my academic project software using named pipe technologies to connect heterogeneous systems over the network. I used .net framework 4 and C# language. The problem is that the client program will not able to continue if the server is not ready or unavailable. The client named pipe continuously try to connect to the server named pipe until available connectivity.
I want the client program to be able to continue other functions if the server connection is not available within 3 seconds (may be any duration). Like this scenario: When the client program is started, it will try to connect to server. If the server is not available, the client will stop trying to connect to server and run offline by itself.
some code snippet of my problem...
pipeClient.Connect(); <-- this is the problem point,
frmUserprofile.show(); <-- until the connection is available, the program will not execute this line
the solution that I would like to get...
pipeClient.Connect()
if (3 seconds is over && server connection is unavailable) <-- this is what I need
{ pipeClient stops try to connect; }
frmUserprofile.show();
can someone help me to give some practical solution to me...
by the ways, I hope if u can solve this problem with C# language, please give answers with C# but not necessarily
thanks in advance...
If you are using NamedPipeClientStream class, there is Connect(int) method overload, which accepts timeout value:
bool isConnected = false;
try
{
pipeClient.Connect(3000);
isConnected = true;
}
catch(TimeoutException)
{
// failed to connect
}
If you use NamedPipeClientStream for your task there is Connect(Int32) method that takes amount of timeout
http://msdn.microsoft.com/en-us/library/bb355337.aspx
Use the NamedPipeClientStream. It has a connect time out.
See NamedPipeClientStream.Connect

Problem about checking a WCF connection is opened

I have a problem about checking a WCF connection is opened. My WCF Connection is bi-directional. I use State property to check the connection's state at client. My function:
private bool ConnectionIsOpen()
{
if (m_Service != null && (m_Service.State | CommunicationState.Opened) == CommunicationState.Opened)
{
return true;
}
return false;
}
I create a service which is a thread running every 10 seconds to check the connection's state. I use the method ConnectionIsOpen() for checking. Everything is well on running on Windows XP. However there is a problem when running on Windows 7.
When I unplug the network cable to create to disconnect, If running application on Windows XP, checking connection's State is Faulted but if running on Windows 7, checking connection' State is still Opened.
Anyone can help me how to check a connection is openned or not in this case. Thanks.
This will always be true:
(m_Service.State | CommunicationState.Opened) == CommunicationState.Opened
Example, m_Service.State = 0:
0 | CommuncationState.Opened == CommuncationState.Opened
You want to use & (AND) instead.
We ran into a similar problem in our own system; disconnecting the network cable or placing either the client machine or the server in sleep mode does not generate a channel fault.
From what I can tell, it seems that the connection state only indicates the state of the connection after the last call and not the current connection state. The only way to know the current state is to actually call the service.
If your client doesn’t need to call the service that often but must react if the connection is lost one solution is to implement a dummy call on the client side which periodically polls the service. If the connection is unavailable when the dummy call is made you’ll get a channel fault that you can then deal with.
The catch is you can’t simply use the dummy call to guarantee that the next call to the service will work:
public void SomeMethode()
{
if (ConnectionIsOpen())
{
m_Service.Dummy();
// Connection is lost here
m_Service.SomeMethode();
}
}
To get around this problem, we implemented a system that automatically re-executes any failed service calls which generate a channel fault after the connection has been restored.
The best and asured way to confirm the Communication state is Open or not is to call the Faulted event like below :
proxyInstance.InnerChannel.Faulted -= new EventHandler(ProxyChannelFaulted);
But this works only with those bindings that support ReliableMessaging like WsHttpBinding.
For detail refer the link : WCF Proxy Client taking time to create, any cache or singleton solution for it
Thanks,
Jai Kumar
The fact that you are getting completely different results on windows 7 is not surprising. Microsoft completely re-engineered the TCP stack with windows vista, so the functionality is quite different from xp in the core networking functionality.
The first thing that I would do is use wireshark to see what is actually going across the wire. See if your TCP connection actually terminates when you pull the plug. Windows might be doing some kind of connection persistence / buffering in case the connection comes back quickly.

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