I'm starting a Wi-Fi Direct access point service using the UWP APIs. It starts OK. I'm using WiFiDirectConnectionListener to monitor for devices that get connected to the access point using the ConnectionRequested event.
var connectionRequest = args.GetConnectionRequest();
var deviceInformation = connectionRequest.DeviceInformation;
// FromIdAsync needs to be called from the UI thread (in MS example).
var isConnected = RunOnUIThreadAsync(() =>
{
try
{
var device = WiFiDirectDevice.FromIdAsync(deviceInformation.Id).AsTask().Result;
if (device != null)
{
device.ConnectionStatusChanged -= OnDeviceConnectionStatusChanged;
device.ConnectionStatusChanged += OnDeviceConnectionStatusChanged;
return true;
}
return false;
}
catch (Exception e)
{
// This throws an Exception from HRESULT: 0x800705B4.
return false;
}
}).Result;
On some devices that get connected to the access point, an exception is thrown on calling FromIdAsync with
This operation returned because the timeout period expired. (Exception from HRESULT: 0x800705B4).
In turn, the device that tries to the access point will not connect.
It's always the same devices that are unable to connect, while others connect just fine. I've tried with and without UI thread but the result remains the same. Am I using this wrong, or is this a bug in Wi-Fi Direct? If so, is there another way to start a Wi-Fi Direct access point without the UWP APIs? Perhaps that's working better.
The workaround to prevent timeout is to have DHCP activated on the client side. I have had this error when trying to connect devices with fixed IP address to the hotspot.
Related
I am trying to use a Bluetooth serial port for 2 days and I need to wait 20 minutes to 1 hour to have the serial port actually open...
serialPort.Open() failed with this exception (the port exists) :
Exception thrown: 'System.IO.IOException' in System.IO.Ports.dll
Élément introuvable. : 'COM5'
I realized that it could work if I waited so long because I left my computer with a breakpoint during my lunch, and continue the execution after.
I have tried to use different libraries with always the same result.
I have tried different parameters for baud-rate etc...
Of course, the device (an HC-05) is correctly paired and connected, I have tried it with an android app and it works. it also works when the port finally accepts to open.
The Port Name I pass is the good one, the port is actually created when the device is paired and connected (it pops in the device manager)
My windows install is fresh so, no ghost serial ports.
the code is pretty simple :
_serialPort = new SerialPort
{
BaudRate = 115200
PortName = BluetoothPortName;
};
while (!_serialPort.IsOpen) // because I want it to finally succeed!
{
try
{
_serialPort.Open();
}
catch (Exception ex)
{
_serialPort.Close();
Logger.Error(ToString(), $"Failed to open SerialPort : {ex.Message}");
Thread.Sleep(500);
}
}
It was my expectation that, if the endpoint is not available, the UdpClient.Connect() method would throw an exception that I could capture and, say, alter a label's text to say if the program was connected to the server or not. However, despite me having turned off the server that I'm trying to connect to, the method completes with no issue. Is there some way to resolve this issue, or some other method I should be attempting?
My current code (IP address blanked out, but is valid):
UdpClient chatConnection = new UdpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse("xxx.xx.xxx.xxx"), 1000);
// Initialize client/server connection and set status text
try
{
chatConnection.Connect(serverEndPoint);
SL_Status.Text = "Connected";
}
catch (Exception ex)
{
SL_Status.Text = "Not Connected";
MessageBox.Show("Unable to connect to server. See console for logs.");
Console.WriteLine(ex);
}
Since UDP is connectionless checking if client is connected doesn't apply to it.
There is however a workaround that in some cases may work:
answer by Yahia
I'm getting a very strange exception using a UWP StreamSocket, 99.9% of the time this code functions as expected and the communication with the device works properly, however I get the following exception every once in a while.
The exception message:
The operation failed because an invalid combination of workqueue ID and flags was specified. (Exception from HRESULT: 0xC00D36FF)
Sample code for the issue:
using (StreamSocket analyzerSocket = new StreamSocket())
{
HostName hostName = new HostName(host);
// Set NoDelay to false so that the Nagle algorithm is not disabled
analyzerSocket.Control.NoDelay = false;
try
{
// Connect to the server
await analyzerSocket.ConnectAsync(hostName, port.ToString()).AsTask(new CancellationTokenSource(_timeout).Token);
}
catch (Exception e)
{
var x = e;
}
}
Screenshot of exception in code:
The Stack Trace:
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at Analyzer.<SendMessageAsync>d__120.MoveNext() in zzz.cs:line 779
I've tried my GoogleFu and I was able to find issues with MediaPlayer or Linux kernels but nothing seemed to relate to this issue with StreamSockets.
While I can trap this error and work around the issue I would like to know what's going on in case it's a symptom of a bigger issue.
Thanks in advance.
Edit 1
I thought this might be related to http://referencesource.microsoft.com/#mscorlib/system/runtime/compilerservices/TaskAwaiter.cs,be57b6bc41e5c7e4 based on the code comment of "// And throw an exception if the task is faulted or canceled.".
However I still get this expcetion when I am not using the ".AsTask(new CancellationTokenSource(timeout.Value).Token)"
Edit 2
When I have this in a loop, to constantly send messages to our device, the messages are being received until this exception occurs. Once the exception occurs and I tell it to continue and try again, the exception re-occurs over and over in the loop and the device stops receiving messages.
Edit 3
So I've tried the following, to connect to a different device, with a different instance of the StreamSocket object... and it generates the same error!
using (StreamSocket analyzerSocket = new StreamSocket())
{
HostName hostName = new HostName(host);
// Set NoDelay to false so that the Nagle algorithm is not disabled
analyzerSocket.Control.NoDelay = false;
try
{
// Connect to the server
await analyzerSocket.ConnectAsync(hostName, port.ToString()).AsTask(new CancellationTokenSource(_timeout).Token);
}
catch (Exception e)
{
using (StreamSocket analyzerSocket2 = new StreamSocket())
{
HostName hostName2 = new HostName("xxx.xxx.xxx.xxx");
// Set NoDelay to false so that the Nagle algorithm is not disabled
analyzerSocket.Control.NoDelay = false;
// Connect to the server
await analyzerSocket2.ConnectAsync(hostName2, port.ToString());
}
throw;
}
}
It feels like some sort of cross threading type of issue... I'm grasping at straws right now as I cannot trap and bypass the error as once the error occurs I can no longer talk to the devices and I must exit the application to get it to work again.
Does anyone have any other ideas or confirmation that it looks like cross threading type of issue?
Thanks in advance.
The only way I have found to prevent this issue is to stop using the "StreamSocket" altogether.
I switched my code to use the "System.Net.Sockets" namespace using the Socket object instead and with some modifications to my code I haven't encountered this issue since.
Code sample:
https://msdn.microsoft.com/en-us/library/windows/apps/hh202858%28v=vs.105%29.aspx?f=255&MSPPError=-2147217396
I've read a few sources on this. I followed this accepted answer and am using Managed WiFi API to get the SSID if I am connected via WiFi. Here is my code:
private void setSSID() {
WlanClient wlan = new WlanClient();
Collection<String> connectedSsids = new Collection<string>();
foreach (WlanClient.WlanInterface wlanInterface in wlan.Interfaces) {
Wlan.Dot11Ssid ssid = wlanInterface.CurrentConnection.wlanAssociationAttributes.dot11Ssid;
connectedSsids.Add(new String(Encoding.ASCII.GetChars(ssid.SSID, 0, (int)ssid.SSIDLength)));
}
}
This will get the SSID perfectly if I am connected via WiFi but throws an exception if only connected via Ethernet. The ideal solution:
Enter setSSID() (or something to similar effect)
Check if connected via Ethernet
If so, return null/0/undefined
Else, return the SSID (I have already got a check in if it's even connected to the network or not)
I have looked all over the WMI and the NetworkInformation namespace but neither provide what I am looking for.Looking in WlanApi.cs, the exception is thrown here:
public Wlan.WlanConnectionAttributes CurrentConnection {
get {
int valueSize;
IntPtr valuePtr;
Wlan.WlanOpcodeValueType opcodeValueType;
Wlan.ThrowIfError(
Wlan.WlanQueryInterface(client.clientHandle, info.interfaceGuid, Wlan.WlanIntfOpcode.CurrentConnection, IntPtr.Zero, out valueSize, out valuePtr, out opcodeValueType));
try {
return (Wlan.WlanConnectionAttributes)Marshal.PtrToStructure(valuePtr, typeof(Wlan.WlanConnectionAttributes));
}
finally {
Wlan.WlanFreeMemory(valuePtr);
}
}
}
Also looked at:
Check whether connected to a Wi-Fi network or not C#
You can catch the exception (which you report as Win32Exception), and treat that as the "no WiFi is available" condition.
If you like, you can check the ErrorCode or HResult properties for the exception to make sure it's the error you were expecting in the case of the lack of WiFi, rather than some other more problematic exception. In the latter case, you would probably want to rethrow the exception (at least until you have decided on a good strategy for handling that type of error).
There is also the native wireless LAN API which you could use directly, handling the error codes/results from that instead of dealing with exceptions. But I think in your case, handling the exception that's thrown is simplest, since it otherwise is working just as you want.
My application is working as a client application for a bank server. The application is sending a request and getting a response from the bank. This application is normally working fine, but sometimes
The I/O operation has been aborted because of either a thread exit or
an application request
error with error code as 995 comes through.
public void OnDataReceived(IAsyncResult asyn)
{
BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived",
ref swReceivedLogWriter, strLogPath, 0);
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = theSockId.thisSocket.EndReceive(asyn); //Here error is coming
string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);
}
}
Once this error starts to come for all transactions after that same error begin to appear, so
please help me to sort out this problem. If possible then with some sample code
Regards,
Ashish Khandelwal
995 is an error reported by the IO Completion Port. The error comes since you try to continue read from the socket when it has most likely been closed.
Receiving 0 bytes from EndRecieve means that the socket has been closed, as does most exceptions that EndRecieve will throw.
You need to start dealing with those situations.
Never ever ignore exceptions, they are thrown for a reason.
Update
There is nothing that says that the server does anything wrong. A connection can be lost for a lot of reasons such as idle connection being closed by a switch/router/firewall, shaky network, bad cables etc.
What I'm saying is that you MUST handle disconnections. The proper way of doing so is to dispose the socket and try to connect a new one at certain intervals.
As for the receive callback a more proper way of handling it is something like this (semi pseudo code):
public void OnDataReceived(IAsyncResult asyn)
{
BLCommonFunctions.WriteLogger(0, "In :- OnDataReceived", ref swReceivedLogWriter, strLogPath, 0);
try
{
SocketPacket client = (SocketPacket)asyn.AsyncState;
int bytesReceived = client.thisSocket.EndReceive(asyn); //Here error is coming
if (bytesReceived == 0)
{
HandleDisconnect(client);
return;
}
}
catch (Exception err)
{
HandleDisconnect(client);
}
try
{
string strHEX = BLCommonFunctions.ByteArrToHex(theSockId.dataBuffer);
//do your handling here
}
catch (Exception err)
{
// Your logic threw an exception. handle it accordinhly
}
try
{
client.thisSocket.BeginRecieve(.. all parameters ..);
}
catch (Exception err)
{
HandleDisconnect(client);
}
}
the reason to why I'm using three catch blocks is simply because the logic for the middle one is different from the other two. Exceptions from BeginReceive/EndReceive usually indicates socket disconnection while exceptions from your logic should not stop the socket receiving.
In my case, the request was getting timed out. So all you need to do is to increase the time out while creating the HttpClient.
HttpClient client = new HttpClient();
client.Timeout = TimeSpan.FromMinutes(5);
I had the same issue with RS232 communication. The reason, is that your program executes much faster than the comport (or slow serial communication).
To fix it, I had to check if the IAsyncResult.IsCompleted==true. If not completed, then IAsyncResult.AsyncWaitHandle.WaitOne()
Like this :
Stream s = this.GetStream();
IAsyncResult ar = s.BeginWrite(data, 0, data.Length, SendAsync, state);
if (!ar.IsCompleted)
ar.AsyncWaitHandle.WaitOne();
Most of the time, ar.IsCompleted will be true.
I had this problem. I think that it was caused by the socket getting opened and no data arriving within a short time after the open. I was reading from a serial to ethernet box called a Devicemaster. I changed the Devicemaster port setting from "connect always" to "connect on data" and the problem disappeared. I have great respect for Hans Passant but I do not agree that this is an error code that you can easily solve by scrutinizing code.
In my case the issue was caused by the fact that starting from .NET 5 or 6 you must either call async methods for async stream, or sync methods for sync strem.
So that if I called FlushAsync I must have get context using GetContextAsync
What I do when it happens is Disable the COM port into the Device Manager and Enable it again.
It stop the communications with another program or thread and become free for you.
I hope this works for you. Regards.
I ran into this error while using Entity Framework Core with Azure Sql Server running in Debug mode in Visual Studio. I figured out that it is an exception, but not a problem. EF is written to handle this exception gracefully and complete the work. I had VS set to break on all exceptions, so it did. Once I unchecked the check box in VS to not break on this exception, my C# code, calling EF, using Azure Sql worked every time.