"Incompatible Address" creating BluetoothListener - c#

I'm trying to use Bluetooth on Windows 7. It's a Dell laptop with integrated bluetooth and the Dell drivers, and I'm using the 32feet library in a C# project in VS2012.
I've simplified things to this function, called at program start;
public static void Test()
{
Guid service = new Guid("{7A51FDC2-FDDF-4c9b-AFFC-98BCD91BF93B}");
BluetoothListener bl = new BluetoothListener(service);
bl.Start();
BluetoothClient bc = bl.AcceptBluetoothClient();
}
When I create the listener, I get the error "An address incompatible with the requested protocol was used."
The stack trace downstream from this call is;
at System.Net.Sockets.Socket..ctor(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType)
at InTheHand.Net.Bluetooth.Msft.WindowsBluetoothListener.CreateSocket()
at InTheHand.Net.Bluetooth.Msft.WindowsBluetoothListener.Construct(Guid service)
at InTheHand.Net.Sockets.BluetoothListener..ctor(BluetoothFactory factory, Guid service)
at InTheHand.Net.Sockets.BluetoothListener..ctor(Guid service)
The BluetoothRadio.IsSupported property returns TRUE.
I've done a bit of Googling around and not found very much of relevance. Can anyone suggest where to go from here?

After spending a fair chunk of time on this, and trying to get the commercial alternative Wireless Communication Library to work I went back to basics and tried using Bluetooth to stream audio from my phone, use a Bluetooth mouse etc- previously I'd confirmed I could see devices and pair with them and assumed this meant all was well but hadn't had a need to actually use those devices.
Turned out that although detection and pairing worked, nothing else did. Tried another Windows 7 machine and the devices did work. Tried reinstalling drivers, the only thing that actually solved it was to get a new HD (since I didn't want to trash my system if it proved unnecessary) and do a fresh install of Windows 7.
So I don't know the root cause, but if anyone else finds this for the same reason it may save a few days :)

Related

UnauthorizedAccessException when trying to open serial port in C#

I'm using .NET 4.5.2. In one of my ViewModels, I need to access serial port COM8, which is connected to my device, a sensor that provides a continuous stream of data. I can access and send commands to the serial port via Tera Term, Windows Command Prompt, and a LabView application, so the port is not occupied by another process - I know that is usually the case with these posts, but I'm very sure that is not the case here. I've tried sending a command to the port via C# using the Process() class, but that does not work, so it seems to be something with C#.
I saw this post: Force a COM port to close, but that does not seem to be the issue either.
Other things I've tried:
Uninstalling the COM8 device via Device Manager.
Running the application in "Release" mode via Visual Studio.
Running Visual Studio in Administrator mode.
Switching to .NET 4.5.2.
And a few other things that I'm not recalling right now. Any advice about this situation would be appreciated! I'm happy to provide any more information you may need.
Code to open the port:
if (port == null)
{
port = new SerialPort(location, baudRate);
port.ReadBufferSize = 16384;
}
if (!port.IsOpen)
{
port.Open();
}
Update:
If I copy the above code into the startup method, it works fine. It just doesn't seem to work where it is in my ViewModel. I thought it was a threading issue, but I was able to call the code in the main thread and it did not work. Hopefully this will get me closer to a solution!
Update 2:
The code above also works fine in the codebehind of my login method, but in no other codebehind. Super confused right now.

SerialPort.GetPortNames() returns incorrect port names

While c# is not my primary programming language, I'm maintaining such a program for a couple of years now. This program connects to a device on a serial port and works from Windows XP up to 8.1. One specific "feature" is that it uses .NET Framework 2.0.
With some users upgrading to Windows 10 we've got complains that the program cannot detect/open the COM port of the device. We have confirmed this on our own test systems with clean Win10 installation.
It turns out that the function SerialPort.GetPortNames() returns incorrect port names and adds 'strange' characters after the port name.
For example:
COM3吀
COM3䡢
COM3゠
Etc. When I refresh the list, every time another character (or two) shows up after the number.
The test code is super straightforward:
string[] portNames = System.IO.Ports.SerialPort.GetPortNames();
log("Available ports:");
foreach (string PortAvailable in portNames)
{
log(PortAvailable);
}
Where the log function mearly adds a line to a standard TextBox on the form:
txtLog.Text += Msg + Environment.NewLine;
This works in every other Windows version.
I've checked the registry and all looks fine there also.
Does anybody has an idea about this?
I'm suspecting that .NET Framework 2.0 is not 100% compatible anymore, although you can enable it in the Windows features and it seems that the program itself runs fine (besides my serial port problem). I'm a bit scared to upgrade to a newer .NET, let alone that we've VisualStudio 2008 for c# (max=.NET 3.5). Note that the program still needs to run on Windows XP also (POS version is still maintained by Microsoft).
ADDED:
I've "upgraded" a test program to .NET 3.5, and still having exactly the same issue.
Next step is to install a new VisualStudio (it appears that it is free nowadays?? Should I check for privacy settings in Studio also? ;-).
ADDED 2:
Installed VisualStudio 2015 and made multiple builds with different .NET framework versions. v2.0 and 3.5 still adding the strange character. But in v4.0 and up this issue seems te be solved! Now to get the original program compiled and working for the newer Framework.
But I find this issue really strange and would expect that this would hit more .NET functions and more programs.
I've seen the strange characters too. My solution is using Regular Expressions to filter out the number portion of the comm port name.
Dim ports As New Devices.Ports
For Each s As String In ports.SerialPortNames
s = Regex.Replace(s, "\D*(\d+)\D*", "$1")
Debug.WriteLine(s)
Next
I've had this exact same problem with USB CDC serial devices, handled by the new rewritten Windows 10 usbser.sys driver.
The garbage characters are often digits, so removing non-digits isn't a reliable way to work around it. For my solution, look at my last post on this thread here:
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a78b4668-ebb6-46aa-9985-ec41667abdde/ioportsserialportgetportnames-registrykeygetvalue-corruption-with-usbsersys-driver-on-windows?forum=netfxbcl
..there is code there that'll go through the registry, find usbser ports, and return their unmangled names. Beware that it doesn't return all serial ports, just ones provided by that driver. The code works on Windows XP through to 10.
The underlying problem is that the usbser.sys driver creates a registry entry, and on .NET (at least up to 3.5) the GetPortNames() function tries to read those registry keys and gets corrupted data. I've reported this to Microsoft, both via that forum (assuming they read it) and using the built-in Windows 10 beta error reporting tool. Maybe one day there will be a fix.
As you say the program works after enabling the windows feature:
.NET 2.0,3.0,3.5 isn't enabled by default on Windows 8/8.1/10. The files aren't stored on the install media/wim.
It can be enabled with the DISM command from windows update or a local source.
DISM /Online /Enable-Feature /FeatureName:NetFx3 /All
check this out: http://forums.radioreference.com/uniden-tech-support/317887-windows-10-uniden-usb-driver-5.html
For a work around to fix the Win 10 serial port not working caused by strange characters after the port name.
Go in to the Registry with regedit.exe.
Navigate to "HKEY_LOCAL_MACHINE\HARDWARE\DEVICEMAP\SERIALC OMM"
Make note of the comm port name.
Append a "0" or any character to the comm port name.
Change the comm port name back to what it was in step 3.
It worked for me.
Baldur
string[] ports = SerialPort.GetPortNames();
for (int i = 0; i<ports.Length;i++)
{
string mystr = ports[i];
if (((mystr[mystr.Length-1]) >= 0x30) & ((mystr[mystr.Length-1]) <= 0x39))
{
}
else
{
mystr = mystr.Remove(mystr.Length-1);
}
ports[i] = mystr;
}

32Feet.Net connecting to Bluetooth speakers

So I am trying to connect a bluetooth speakers from a script. I am using 32feet.net and I have successfully found the device but it doesn't work when I try to pair and connect to it.
This is the code im using to pair to device, this always fails not sure why:
private static void connected(BluetoothDeviceInfo[] dev)
{
// dev[foundIndex];
bool paired=false;
paired = BluetoothSecurity.PairRequest(dev[foundIndex].DeviceAddress, "1166");
if (paired)
Console.WriteLine("Passed, Device is connected.");
else
Console.WriteLine("Failed....");
}
Here is the code called after connected to actually connect to the device: bc is my bluetooth client var.
bc.BeginConnect(devInfo[foundIndex].DeviceAddress, BluetoothService.SerialPort, new AsyncCallback(Connect), devInfo[foundIndex]);
private static void Connect(IAsyncResult result)
{
if (result.IsCompleted)
{
Console.Write("Connected... ");
}
}
Any help would be appreciated. I am new to 32feet.net so i dont know much about this, i tried following code online to get where im at.
Try BluetoothDeviceInfo.SetServiceState. That will ask Windows to connect to the audio service on the device -- hopefully that'll do the job.
See https://32feet.codeplex.com/wikipage?title=Connecting%20to%20Bluetooth%20Services
Sometimes we don’t want our application to itself send data to/from a remote service but we want instead the local operating system to do so. This is the case for keyboard/mouse/etc with HID, networking with DUN/NAP/PAN/etc, Headset/Handsfree etc.
and then
The short answer in this case is to use BluetoothDeviceInfo.SetServiceState. This is the API equivalent to manually checking the respective checkbox on the “Services” tab of the Device dialog in Bluetooth Control panel.
Also, in these days of Secure Simple Pairing, using PairRequest is fine only if all peer devices will use old style PIN code authentication, otherwise instantiate a BluetoothWin32Authentication and then do the connect (here indirectly via SetServiceState) and handle the authentication in the authentication callback.

How can I connect to a Server Side USB (HID) Device from within an ASP.NET Application?

I'm trying to write my own controller for a USB device instead of using the SDK that comes with the product (I feel the sdk is sub-par).
The USB Device is plugged into the SAME SERVER that this application is running on.
So I decided to head over to Nuget and grab the HidLibrary
PM> Install-Package hidlibrary
and I proceeded to follow the example found on GitHub.
First I went into my control panel to verify the VendorID and the ProductID
And I dropped it into my code.
Then I set a breakpoint on the line that grabs the device, but unfortunately it always comes back null.
using HidLibrary;
public class MyController : ApiController
{
private const int VendorId = 0x0BC7;
private const int ProductId = 0x0001;
private static HidDevice _device;
// POST api/<controller>
public string Post(CommandModel command)
{
_device = HidDevices.Enumerate(VendorId, ProductId).FirstOrDefault();
if (_device != null)
{
// getting here means the device exists
}
else
{
// ending up here means the device doesn't exist
throw new Exception("device not connected");
}
return null;
}
I'm hoping it's something silly, and not some deal-breaking permissions issue regarding connecting to a USB device directly from an IIS worker.
Despite your hopes to be something silly, it is not. You have some deal-breaking permission issues. If you will browse Mike O'Brien's code from GitHub of the Hid Library you will see that it calls Win32 API functions located in: kernel32.dll, setupapi.dll, user32.dll, hid.dll (Native.cs).
The enumeration itself it's done through setupapi.dll functions. It browse all the installed devices and filters what it's need it.
So... I think it's a security issue to execute kernel32.dll code directly from a web-app in IIS with anonymous authentication, don't you?
If you really need to communicate with that HID (who knows maybe it's a temperature sensor, or something else) I would do a separate Windows service and the IIS hosted web app would communication through WCF with this service. This service would like a proxy.
Put the same code in a console application and run it. That will help you verify if it's your code or environment.
If it's environment, try using Process Monitor to see if there are any hidden access errors. Also try enumerating all devices, not just looking for the one device you're after, just to see if you can do it in ASP.NET.
#Chase, unless this is an experiment - it is best not to attempt connecting to a device from IIS process. [It's a Pandora's box if you start down this path].
Best way to do this is to have another (WCF) service as proxy to the device and expose just what you need out of the service, hook it up with your app. Feel free to ask for an example if you think that would help.
I +1 #garzanti.

check internet connection in linux using mono?

is there any way to check internet connection status in linux using mono
If it's desktop app, you could query NetworkManager (which is the network connection manager on most Linux desktops) over d-bus, using the NDesk.DBus library.
See Banshee for an example: http://git.gnome.org/cgit/banshee/tree/src/Core/Banshee.Services/Banshee.Networking/NetworkManager.cs
Apart from what Michael already suggested for a desktop application, you can also do something like:
foreach (NetworkInterface ni in NetworkInformation.GetAllNetworkInterfaces ()) {
// Check that any or all of:
// -ni.OperationalStatus == OperationalStatus.Up
// -that ni.NetworkInterfaceType is ethernet or wireless80211
// -ni.GetIPProperties() has a gateway and a DNS server
// ...
}
No matter what you end up using, it won't be reliable.
I see it all the time with Windows Vista and 7 at home. I use a home network, so my computers are always "connected." However, they are not always connected to the Internet.
That said, I would recommend checking the network interfaces as Gonzalo said. It is your best bet.
I would not rely on NetworkManager being present. I hate that thing and turn it off whenever I can. It is huge, ungainly, has an ugly name, relies on junk like HAL and DBUS. Early versions permanently put me off because they didn't work unless you were logged in to a GUI. It also collected bug work-arounds for wifi that were completely ridiculous in an open-source operating system that should have just fixed the original bugs. That led to other wifi managers and the command-line not being able to work properly and people being told to use NetworkManager, only because no one ever bothered to fix the actual bug!
You could try to open your connection as it is needed. If that fails display an error message.
Alternatively, if you really need a general check (e.g. at application start) you could try to make HTTP requests to one or more omnipresent websites like google.com. (Or what ever protocol you mean by "internet").
Check out HttpWebRequest.

Categories

Resources