Using Wifi Direct API in legacy mode disconnects every 2 minutes - c#

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

Related

Reference Client (UA.-.NETStandard-master) is BadNotConnected

I have a question that I already asked on the GitHub forum. Unfortunately I didn't get an answer there and I hope that you can help me here. If I do get an answer in the GitHub forum, I'll name it here. My GitHubPost can be found under the following link:
https://github.com/OPCFoundation/UA-.NETStandard/issues/1139
I will still copy the post from the GitHub forum here if the link no longer works at some point.
I downloaded the OPC UA standard project from github (https://github.com/OPCFoundation/UA-.NETStandard).
I would like to use the Reference Client there to access a Beckhoff PLC (server).
To do this, I opened the project in VS2017 and set the Reference Client as the startup project. Then I started the project with F5.
The following window opened:
Reference_Client
If I now specify the IP address and the port of my PLC (as shown above) and then click on "Connect",
the client sometimes establishes a connection to the PLC and sometimes I get the following error message:
Error_Message
In about 80% of the cases there is this error message and the client does not connect to the server.
In about 20% of the cases a connection to the server is established and I can read and write variables from the server.
I didn't change the program and it seems completely arbitrary when the connection can be established and when not.
Has anyone ever had a similar problem?
Many thanks in advance.
UPDATE 1: More detailed error message
The following screenshot shows the details of the error message. I have estimated some parts of the storage path.
Detailed_Error_Message
Please add the exception details to your post, it would be helpful to see at which place the ServiceResultException is triggered.
Thanks again for the many answers. I have been able to narrow down the cause of the problem now. I found the tip in the Github forum that you should comment out all security mechanisms:
You modify your code private static void CheckCertificateDomain(ConfiguredEndpoint endpoint) to return true always, and add AutoAcceptUntrustedCertificates true into config of the client.
This is just for developing and troubleshooting of course.
Source: Github tip
I did exactly that and then tried to connect again. I no longer receive an error message, but the operating window for OPC UA crashes. VS2017 itself does not crash, only the operating window in which the IP address can be entered and the connection can be established. When I record the network traffic with Wireshark during the crash, it can be seen that the connection (although the operating window has crashed) was successful. Data is exchanged between the client (VS2017) and the server (Beckhoff PLC).
My new approach is now to no longer use this operating window, but to write a new program. I would like to continue using the library I have used so far. The received and sent variables should then be displayed via the console.
Since this no longer has anything to do with my original question, I will make a new post for questions about this program if necessary and then add the link here.

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

Reading from stream failed - mysql_native_password error

I have been facing the following error intermittently.
Authentication to host '127.0.0.1' for user 'root' using method 'mysql_native_password' failed with message: Reading from the stream has failed.
It shots up any time and I am at my wits end. I also posted a bug on MySQL bugs and solutions are not proving to be effective in any way.I hope you guys can help me out.
Here is the link to MySQL Bug for details: Never seems to go away!
Some more detail: I have a client-server system but this bug occurs on the server system(where MySQL database is installed) when a local running app on the server system tries to run a query.
I had already opened a question here but since has been dead. Just a caveat I thought that skip-name-resolve solved the issue but it seems to just have lowered the frequency. Hope someone would help me out this time around.
EDIT: The MySQL guys say that in a client server setup server may close a connection if it is unused for a long time. However, this is not what I am facing as I create a new connection everytime I want to execute a query. I made this point clear in the last comment on the MySQL Bugs.
Guys I tried this: "SslMode=None" in the connection string, but if you need SSL then read this:
http://www.voidcn.com/article/p-phfoefri-bpr.html
here is a sample connection string that works:
connectionString="Server=192.168.10.5;Database=mydata;Uid=root;Pwd=****;SslMode=None"
Hope this helps
I've been getting this error, quite frequently with Amazon's MySQL RDS instances. And most multi-AZ instances.
It would be interesting to compare notes to see if others mostly get this issue with RDS also?
Amazon is known to rely heavily on "fast" DNS changes to switch over stuff with things like ELBs. I wonder if the same thing is happening with RDS? Or some other internal AWS switching is messing up the idle connections in the pool.
This would explain why the Oracle devs can't reproduce it and don't see it as much of an issue.
Anyway I've had to just deal with it and add retry logic when opening a connection.
This issue is caused by Ssl.
Solution 1: SSL is not required. Since it is caused by SSL, we can turn off SSL by appending "SslMode=None" to the connection string.
Solution 2: SSL is required, server identity is important and needs to be verified. The server needs a internet connection to do the cert verification. Please note the crypto API doesn't update CTL for every process. The CTL is maintained at operating system level. Once you connect the server to connect and make an SSL database connection to the server, the CTL will be updated automatically. Then you may disconnect the internet connection. Note again the CTL has its expiration date and after that the Windows needs to update it again. This will occur probably after several months.
Solution 3: SSL is required but the server identity is not important. Typically SSL is only used to encrypt the network transport in this case. We can turn off CTL update:
Press Win+R to open the "Run" dialog
Type "gpedit.msc" (without quotes) and press Enter
In the "Local Group Policy Editor", expand "Computer Configuration", expand "Administrative Templates", expand "System", expand "Internet Communication Management", and then click "Internet Communication settings".
In the details panel, double-click "Turn off Automatic Root Certificates Update", clickEnabled, then click OK. This change will be effective immediatelly without restart.
http://www.voidcn.com/article/p-phfoefri-bpr.html
unfortunately, this error occurs if the application and mysql are on the same computer, if you move it to a different computer it is fine.
I tried many ways but for now there is no other solution. bug has been reported many times by others https://bugs.mysql.com/bug.php?id=76597
I had the exact same problem performing the upgrade on a windows form application. The solution I found was to change the server, because that one was in trouble. On the server that was presenting the similar situation you described had installed WordPress with MYSQL 5.6.34, on the other I did a clean install with MYSQL version 5.6.26.
I don't know if it has to do with the environment variables used. I believe it has nothing to do with Connection Timeout, if it is a property that is used only with the open connection. This error occurred in a shared environment as well as in a local installation with Maria DB. Another problem I found was that one of the selection commands that retrieved the data was having a problem in its formation not respecting the blanks:
SELECT COLUNA1, COLUNA2 FROM TABLE;
I made the change to SELECT COLUMN1, COLUMN2 FROM TABLE;
I am still testing on this solution I presented, and as of the time of posting there were no more errors.
I was getting the error
Authentication to host 'localhost' for user 'root' using method 'mysql_native_password' failed with message: Reading from the stream
I solved it when I put SslMode=None in my connection string.
However, I checked that the message is different from you
Check my connection
connection.ConnectionString = "server=myadressserver;userid=myuser;password=mypassword;database=test;SslMode=None";

What could explain this behavior in UDP multicast via WinRT?

Here is the scenario: I have 5 apps which all share a common DLL which contains P2P networking functionality that I wrote. One of these apps works perfectly every single time, but the others experience the following problem:
On a multicast broadcast our x86 based tablet can send and receive packets fine, but my x64 computer and ARM tablet can only send packets. The only difference is that they use different ports. I thought that must be it, and tried switching the other apps to use the same ports as the working app as a test, but that was a no-go. Here is the relevant portion of code that handles setting up the broadcasting system.
public async Task<bool> Startup() {
if (P2PNetwork.LocalUser == null || this._listenSocket != null)
return false;
ConnectionProfile connection = null;
//See note 1 below
bool gotConnection = TryGetValidNetworkConnection(out connection);
if(!gotConnection)
return false;
this._heartbeatTimer = ThreadPoolTimer.CreatePeriodicTimer(DoHeartbeat, TimeSpan.FromSeconds(10));
var socket = new DatagramSocket();
var stream = await socket.GetOutputStreamAsync(LANBroadcasting.MULTICAST_GROUP_ADDRESS, P2PNetwork.NetworkGroup.SendPort);
this._outStreamWriter = new DataWriter(stream);
this._listenSocket = new DatagramSocket();
this._listenSocket.MessageReceived += OnMessageReceived;
await this._listenSocket.BindServiceNameAsync(P2PNetwork.NetworkGroup.ReceivePort, connection.NetworkAdapter);
this._listenSocket.JoinMulticastGroup(LANBroadcasting.MULTICAST_GROUP_ADDRESS);
DoHeartbeat(HeartbeatFlags.Ping);
return true;
}
NOTE 1: These symptoms were happening before for all 5 applications. At that time I was using the BindServiceNameAsync without any arguments. After extensive research I found a page that suggested that that approach was not good, and that the Windows 8.1 method that takes a connection profile worked more reliably. I checked the profile multiple times and I get the wireless LAN profile, which is correct for both.
In this case (non-working) the tablet's send port is 50011 and its receive port is 50010. The multicast address is ff02::fb (I've tried IPv4 as well, no change) The PC in this case is the reverse of that. I confirmed that the packets are sending via Wireshark.
I also see this line of output via netstat -a on the PC (which is failing to receive)
UDP [::]:50011 *.*
Despite all this looking correct, my PC simply does not get the OnMessageReceived method called (except for the one app which mysteriously works). What should I be looking for that can cause this odd behavior? I tried changing the ports on the working application to see if it would fail but it didn't. I also tried running the app on a different tablet to see if it was just this PC, but I got the same results on the other tablet. Could the app be failing to join the multicast group? How would I know since the method returns void?
After a few days of banging my head against the wall, I finally got the answer. If you experience this problem, go to your Windows Firewall Settings and check what kind of network you are connected to. In my case, the Wi-Fi was a Guest / Public network. Apparently this means that it is considered "Internet" by the Windows Runtime and not "Private Network". In Package.appxmanifest I had the "Private Network (Client and Server)" options selected, but only "Internet (Client)" (which provides outbound access only) and not "Internet (Client and Server)" on all but the one application that was working for some reason.
On a side note: this doesn't explain why the one x86 tablet was still able to receive for all apps. I can only assume this is some kind of driver flaw.
This should really trigger some kind of warning message because this simple setting is way too easy to overlook.

How do you deal with transport-level errors in SqlConnection?

Every now and then in a high volume .NET application, you might see this exception when you try to execute a query:
System.Data.SqlClient.SqlException: A transport-level error has
occurred when sending the request to the server.
According to my research, this is something that "just happens" and not much can be done to prevent it. It does not happen as a result of a bad query, and generally cannot be duplicated. It just crops up maybe once every few days in a busy OLTP system when the TCP connection to the database goes bad for some reason.
I am forced to detect this error by parsing the exception message, and then retrying the entire operation from scratch, to include using a new connection. None of that is pretty.
Anybody have any alternate solutions?
I posted an answer on another question on another topic that might have some use here. That answer involved SMB connections, not SQL. However it was identical in that it involved a low-level transport error.
What we found was that in a heavy load situation, it was fairly easy for the remote server to time out connections at the TCP layer simply because the server was busy. Part of the reason was the defaults for how many times TCP will retransmit data on Windows weren't appropriate for our situation.
Take a look at the registry settings for tuning TCP/IP on Windows. In particular you want to look at TcpMaxDataRetransmissions and maybe TcpMaxConnectRetransmissions. These default to 5 and 2 respectively, try upping them a little bit on the client system and duplicate the load situation.
Don't go crazy! TCP doubles the timeout with each successive retransmission, so the timeout behavior for bad connections can go exponential on you if you increase these too much. As I recall upping TcpMaxDataRetransmissions to 6 or 7 solved our problem in the vast majority of cases.
This blog post by Michael Aspengren explains the error message "A transport-level error has occurred when sending the request to the server."
To answer your original question:
A more elegant way to detect this particular error, without parsing the error message, is to inspect the Number property of the SqlException.
(This actually returns the error number from the first SqlError in the Errors collection, but in your case the transport error should be the only one in the collection.)
I had the same problem albeit it was with service requests to a SQL DB.
This is what I had in my service error log:
System.Data.SqlClient.SqlException: A transport-level error has occurred when sending the request to the server. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)
I have a C# test suite that tests a service. The service and DB were both on external servers so I thought that might be the issue. So I deployed the service and DB locally to no avail. The issue continued. The test suite isn't even a hard pressing performance test at all, so I had no idea what was happening. The same test was failing each time, but when I disabled that test, another one would fail continuously.
I tried other methods suggested on the Internet that didn't work either:
Increase the registry values of TcpMaxDataRetransmissions and TcpMaxConnectRetransmissions.
Disable the "Shared Memory" option within SQL Server Configuration Manager under "Client Protocols" and sort TCP/IP to 1st in the list.
This might occur when you are testing scalability with a large number of client connection attempts. To resolve this issue, use the regedit.exe utility to add a new DWORD value named SynAttackProtect to the registry key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\ with value data of 00000000.
My last resort was to use the old age saying "Try and try again". So I have nested try-catch statements to ensure that if the TCP/IP connection is lost in the lower communications protocol that it does't just give up there but tries again. This is now working for me, however it's not a very elegant solution.
use Enterprise Services with transactional components
I have seen this happen in my own environment a number of times. The client application in this case is installed on many machines. Some of those machines happen to be laptops people were leaving the application open disconnecting it and then plugging it back in and attempting to use it. This will then cause the error you have mentioned.
My first point would be to look at the network and ensure that servers aren't on DHCP and renewing IP Addresses causing this error. If that isn't the case then you have to start trawlling through your event logs looking for other network related.
Unfortunately it is as stated above a network error. The main thing you can do is just monitor the connections using a tool like netmon and work back from there.
Good Luck.
You should also check hardware connectivity to the database.
Perhaps this thread will be helpful:
http://channel9.msdn.com/forums/TechOff/234271-Conenction-forcibly-closed-SQL-2005/
I'm using reliability layer around my DB commands (abstracted away in the repository interfaece). Basically that's just code that intercepts any expected exception (DbException and also InvalidOperationException, that happens to get thrown on connectivity issues), logs it, captures statistics and retries everything again.
With that reliability layer present, the service has been able to survive stress-testing gracefully (constant dead-locks, network failures etc). Production is far less hostile than that.
PS: There is more on that here (along with a simple way to define reliability with the interception DSL)
I had the same problem. I asked my network geek friends, and all said what people have replied here: Its the connection between the computer and the database server. In my case it was my Internet Service Provider, or there router that was the problem. After a Router update, the problem went away. But do you have any other drop-outs of internet connection from you're computer or server? I had...
I experienced the transport error this morning in SSMS while connected to SQL 2008 R2 Express.
I was trying to import a CSV with \r\n. I coded my row terminator for 0x0d0x0a. When I changed it to 0x0a, the error stopped. I can change it back and forth and watch it happen/not happen.
BULK INSERT #t1 FROM 'C:\123\Import123.csv' WITH
( FIRSTROW = 1, FIELDTERMINATOR = ',', ROWTERMINATOR = '0x0d0x0a' )
I suspect I am not writing my row terminator correctly because SQL parses one character at a time right while I'm trying to pass two characters.
Anyhow, this error is 4 years old now, but it may provide a bit of information for the next user.
I just wanted to post a fix here that worked for our company on new software we've installed. We were getting the following error since day 1 on the client log file: Server was unable to process request. ---> A transport-level error has occurred when receiving results from the server. (provider: TCP Provider, error: 0 - The semaphore timeout period has expired.) ---> The semaphore timeout period has expired.
What completely fixed the problem was to set up a link aggregate (LAG) on our switch. Our Dell FX1 server has redundant fiber lines coming out of the back of it. We did not realize that the switch they're plugged into needed to have a LAG configured on those two ports. See details here: https://docs.meraki.com/display/MS/Switch+Ports#SwitchPorts-LinkAggregation

Categories