Problems using a DLL with WPF - AccessViolationException - c#

I'm trying to use Microchip's Managed DLL with their MCP2210 Evaluation Kit. I was having success with sing it with a Console Application - I can change what LED is lit via the Potentiometer and I can read the temperature. However, I'm having issues using it under WPF.
I'm using the exact same code to fetch values off of the device, however I'm running across AccessViolationExceptions and now SEHExceptions. Would using a threaded approach to continually poll the device cause memory to corrupt? And how can I avoid doing that?

So I think I figured out the issue. Maybe.
I tried using lock to make sure that only one thread's accessing the device at any one time, and that seems to have cleared up all of the issues thus far. Still need to perform more testing, but it's working so far.

Related

BLE Using WinRT: Access Denied When Executing "GetCharacteristicsForUuidAsync()" for Write Characteristic

Maybe someone can help me out because I have a really tricky situation with Bluetooth LE using WinRT on Windows 10 (like supposed here: Bluetooth Low Energy in .Net (C#)).
I need BLE within a Win32 classic desktop application.
Our code is running in a 32 Bit frame application using the .NET runtime (v4.0.30319, .NET Framework 4.6.2). I was able to manage all the other issues (strong naming some NuGet assemblies (Shiny.BluetoothLE), running BluetoothAdapter.GetRadioAsync() in a 64 Bit COM surrogate DLL when running on 64 Bit Windows) but now I am totally stuck with this and here’s where:
The problem occurrs when executing var result = await gattDeviceService.GetCharacteristicsForUuidAsync(uuid, BluetoothCacheMode.Cached); see here https://learn.microsoft.com/de-de/uwp/api/windows.devices.bluetooth.genericattributeprofile.gattdeviceservice.getcharacteristicsforuuidasync?view=winrt-20348.
When getting the read characteristics, the result.Status is GattCommunicationStatus.Success and the result contains the desired characteristic.
But of course I also need to get the write characteristic and I am ALWAYS getting GattCommunicationStatus.AccessDenied!
Because of that the result contains NO characteristic.
Has anybody a clue why is that? I really need help here because I am kinda lost right now…
I also tried to set AccessPermission via registry like supposed here but no luck at all…
PS: I use Windows 10 SDK Kit Build 20348 and like stated above it is a C# .NET Framework 4.6.2 project and all our assemblies are strong named because of using GAC. If I am missing anything don’t hesitate to contact me.
For anyone who stumbles over the same stupid issue...Here's the solution:
On Windows, using .NET Framework 4.6.1+ and the WinRT libraries inside a Non-UWP application, you can only call ONCE for getting the characteristics, no matter if you call for all at once via gattDeviceService.GetCharacteristicsAsync(BluetoothCacheMode.Uncached) or for a specific one via gattDeviceService.GetCharacteristicsForUuidAsync(uuid, BluetoothCacheMode.Cached).
Any subsequent calls will fail with GattCommunicationStatus.AccessDenied...
So my solution now is to retrieve all characteristics at once and filter them locally.
That did the trick! Anyways, this is so stupid...It wasted a lot of my time now!
As it seems, I also do not need to set any AccessPermission via registry.
PS: I will call out to you, if I stumble over another tricky situation, just to let you guyz know.
I may have found a way to get around the problem.
tl;dr: Dispose both the BluetoothLEDevice and the GattDeviceService you get while connecting! The system thinks it is still in use!
In my case (using Windows 10, but not an UWP application, calling WinRT libs) this happens:
Only the first call gives me the attributes, then "Access Denied".
After some time a single call will give a valid answer again, but it's pretty rare (in one case after 52 seconds, in another 21 seconds).
In this case I will try to make a solution when everytime I'm asking for data, I will build the BLE from ground up (device detection, looking for correct device, getting attributes), get the data and then destroy everything, then do it again everytime I need data from a device.
This feels very wrong and could lead to more problems.
The reasoning behind this that the first time I collect information, everything is accessible.
In fact I did not need a total rebuild! I just needed to dispose both the BluetoothLEDevice and the GattDeviceService from my connection.
I got my device from
BluetoothLEDevice device = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
And my service with
GattDeviceService service = await device.GetGattServicesForUuidAsync(serviceUUID, BluetoothCacheMode.Uncached);
After I disposed them, a new call of connection (from BluetoothLEDevice.FromIdAsync(deviceInfo.Id)) works again!
service.Dispose();
device.Dispose();

Inconsistent behavior from ServicePointManager.SetTcpKeepAlive

I've been trying to get tcp keep alive packets to send using System.Net.Http.HttpClient. As far as I can see the only way to do this is using ServicePointManager.SetTcpKeepAlive(true, X, Y). When testing this in a LinqPad script I have got it working although it's not consistent. For example if I do a manual call to ServicePointManager.FindServicePoint(myUrl) before I call ServicePointManager.SetTcpKeepAlive then it won't work, I assume because of caching, however if it's the first thing that happens it usually works (I'm fairly certain it's still inconsistent here). Note that I am checking whether it works or not using Wireshark.
However when I try to use this in my real UWP application it fails. I've tried setting this as the first App.xaml.cs constructor and just before instantiating the HttpClient and various places in between without any luck.
Am I missing something?
Note that I realise it is possible to use HttpWebRequest directly and set this on it's ServicePoint instance but I'd like to know why this isn't working first before resorting to something like this.
EDIT: I ended up trying to implement this with HttpWebRequest and ServicePoint.SetTcpKeepAlive and while it compiles, it fails when it's called with a Operation is not supported on this platform exception. I guess this means the main problem here might be that UWP just doesn't support sending TCP keep alive packets?
EDIT2: I've created a minimum reproducible example here: https://github.com/csuzw/TcpKeepAliveTest . In this case the HttpWebRequest approach does not fail with the Operation is not support on this platform exception but it doesn't send keep alive packets either. I wonder if the difference is that my real app is a Xamarin.Forms UWP target app, whereas this test app is a straight UWP app. Regardless both approaches used in this test app fail to produce keep alive packets.

Data Updating only with beak point, without changing code. in winform using c#?

I have problem in refreshing data in a Windows Forms application. I have one server (it is also an other client) and one client. My task is to update data in list by clicking on button and server side client is updating properly, but in client it is not updating for the first time.
But by keeping debug point on particular point it is updating on client side also. I understood that this is happening because of Timing issue, so I used Thread.Sleep();.
But still I am facing the same problem.
I am not able to understand why this is happening without changing any code.
Do not ever -EVER- use Thread.Sleep(); This is just something you do when you're trying out stuff but has pretty much no use in production.
That being said, you're experiencing a race condition, which are usually annoying to debug because they depend on server-client communications.
I suggest you take a look at async-await, if you haven't already, and you set your code so you wait (await) for the server to give you the update before updating your UI.
If you're already using async/await I suggest you show us some code so we can at least help you out a little. But with the information currently available, I suggest you look this up and learn a bit from there. It'll help a lot

Ways of isolating cause of unresponsive Winforms GUI

I have a large-ish Winforms application written in C# which is periodically unresponsive. The issue seems to occur once the application has been use for an hour or so. Exact timings are difficult to gather as users often go off to work on something selse, get back to it and find it has become unresponsive.
I think a memory leak can be ruled out as I'm not seeing excessive memory usage (I've asked users to send a screenshot of the task manager and memory usagage is the same as I would see when the application is runnning normally)
Similarly, CPU usage is normal (single digit %)
As I've so far been unable to recreate the issue on mydevelopment PC I am planning on sitting next to one of the affected users and mirror every action the user performs in order to recreate this. (I'll be setting up a laptop to RDP in to my main PC)
Recreating the issue is one thing, but I'll need to find out what is actually going on in the application.
Could anyone tell me if running in debug mode (through visual studio) will be sufficient or will I need to do something different?
I've searched through a few posts and I've seen mention of profiling software, however I'm not sure if this would only help with general performance issues or memory management issues.
Alternatively, if anyone has come across similar freezing issues then do you have any suggestions of the kind of causes for this?
Some technical details: Aplication is C#, compiled against .NET 3.5, winforms GUI. There are a few external libraries (most significant is ComponentFactory Krypton Suite). Data access is to a Microsoft SQL Server 2005 database. The solution contains 39 projects, I'm not sure if that might have something to do with it?
Any suggestions/pointers would be greatly appreciated.
The application is working much more reliably now, freezing issues still occur on occasion but nowhere near as often as before.
The issue appears to be related to the endpoint security (in this case, Cisco Security Agent) present in the environment I'm working in, application has been whitelisted and has has significantly rediced the instances of application hangs. The development system I work on does not have this endpoint security present, so it didn't show up in early stages of testing.
Thanks for all your feedback, I think there are still threading and garbage collection issues that need cleaning up, hopefully this should sort out the last few issues.

C# P/Invoke into ODBC32.dll failing when using multiple threads

UPDATE: The following error was actually due to a simple bug which I missed. The only real message here that tired and stupid is a bad combination.
For reasons to do with some specific features of an ODBC driver we're forced to use, I've been trying to write a small application which directly uses ODBC calls. Since C# 2.0 is what I know most, I've been doing this using P/Invoke calls into ODBC32.dll.
The code I've written initially has been multithreaded. But I've noticed that as soon as I jump threads I'm getting AccessViolationExceptions. For instance, when I generate IntPtr references to an Environment and Connection in one thread and then try to use these in another thread in the generation of a Statement (SQLAllocStmt), it all goes pop.
I'm sure I can work around this, but is there some obvious reason for this? Is the unmanaged memory allocated by the calls into ODBC32.dll somehow bound to a particular thread?
This depends on:
The odbc driver: What is it?
Your code: Are you freeing the memory without realizing it?
Consider:
Whether you really need to do this. Can't you control the behaviour of the driver using the connection string, or using driver-specific commands through a command object?
If you do have to do this, can you isolate it into a single STA thread and use marshalling, or a task queue, to simplify your job?
If you do have to use it from multiple threads, can't you make sure each thread has it's own Connection and Environment?

Categories