UnauthorizedAccessException when trying to open serial port in C# - 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.

Related

Use a dll containing an ASP.NET server

I wrote an application that use grpc with ASP.NET client/server.
This application is built for watch and inform about some operations.
Because I would to have an application also compatible with linux, I transformed it in a dll, then for Windows I made a little exe that uses it, with an icon in the systray.
It works for Windows, I must test for linux except for a part, I would to get the addresses used by the server after launching... it works if I back the dll in console mode, but with the short "launcher" it's impossible (add by edit) to get the addresses with the code i wrote between balises, BUT you can connect to the server (by example i changed port in config file to verify if it was not an address by default and it works.). My problem is only to retrieve addresses after launch, i need them to add the possibility to receive a mail with addresses to connect, show them in systray..
Yesterday I found this way to get addresses used:
public void Configure(IApplicationBuilder app,...)
{
string ServerAddress = app.ServerFeatures.Get<IServerAddressesFeature().Addresses.FirstOrDefault();
// ---
}
with the short launcher the string is null while it works when I back transform the dll as a program and launch it.
I would to have an easy way, without to make big modifications when I make an app for a system or another, I have chosen what was the more compatible and would to stay in this way if possible. I know i could make an identifier to know on which system I then launch according to the OS, but i hoped to find another way in case I want to make something else with this app.
Edit:
It seems it could be a problem between the fact to launch a systray that launch Kestrel. I'm beginner with Asp .net. I copy/paste contract and constructor to the systray, it seems i have the same problem (i used a different port). I can connect but IApplicationBuilder don't have the list of adresses used.

WMI ManagementOperationObserver doesn't work against remote box

I'm trying to figure out how to do WMI queries against a remote computer asynchronously using C# on .Net 4.5.
I'm using the ManagementObjectSearcher class, and using the Get(ManagementOperationObserver watcher) method; more or less I'm using the example from here https://msdn.microsoft.com/en-US/library/ms257344(v=vs.80).aspx
It doesn't work.
Here's what I know:
When I use wbemtest to connect to the remote computer and execute a query (SELECT * FROM Win32_Service) synchronously it works.
When I set wbemtest to be asynchronous, it also works, so it isn't a configuration issue on my workstation or my target machine, and my credentials work fine.
If I have my C# code connect to my local workstation, performing the same query asynchronously using ManagementOperationObserver also works fine.
When I change my C# code to connect to my remote target machine, it doesn't work. None of the events on the ManagementOperationObserver ever fire, and my application just sits there waiting. I've left it sit there for minutes and nothing happens.
My workstation is part of a domain, and my target remote machine is not, if that matters (since wbemtest works both sync/async I'm not sure it matters).
At this point I don't know what to try next. Does ManagementOperationObserver just not work for remote queries?
Ok, by default, Visual Studio 2013 sets "Prefer 32bit" to true on console applications. My workstation is 64bit; I turned this off, now my remote calls work :/
what's your explanation that in case you are running code as 32b it doesn't work, but under 64b compilation it works fine? For it's quite scary situation.
I am trying myself to get results from async call and still have issue with it: the code get executed, but I don't see the final result.
My code is installing a printer remotely from WMI. In the Win32_Printer, I am using
printer.Put(operationWatcher);
and in the event, setting a bool that I am monitoring.
private void OperationWatcher_ObjectPut(object sender, ObjectPutEventArgs e)
{
if (e.Path.ClassName == "Win32_Printer")
{
printerSuccessfullyPut = true;
Console.WriteLine("should be installed");
}
}
The code got properly executed, but I don't get my printer installed. If I make a sync call
printer.Put();
the printer is installed. Very strange.
Wonder if the issue might have similar background as the one mentioned here (about Start method with ManagementEventWatcher)
http://blogs.microsoft.co.il/sasha/2012/09/20/asynchronous-wmi-queries-stay-away-from-them/

"Incompatible Address" creating BluetoothListener

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

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.

Categories

Resources