Error on getting device info using DeviceManager - c#

I'm trying to get device info using DeviceManager class in C# and i get the folowing error:
The runtime has encountered a fatal error. The address of the error was at 0x7170f7fc, on thread 0x1448. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.
Here is my code:
// Create a DeviceManager instance
var deviceManager = new DeviceManager();
// Loop through the list of devices and add the name to the listbox
for (int i = 0; i <= deviceManager.DeviceInfos.Count; i++)
{
// Add the device only if it's a scanner
if (deviceManager.DeviceInfos[i].Type != WiaDeviceType.ScannerDeviceType)
{
continue;
}
// Add the Scanner device to the listbox (the entire DeviceInfos object)
listBox1.Items.Add(new Scanner(deviceManager.DeviceInfos[i]));
}
It started happening after i found a solution online to change the WIA service logon
Services -> Windows Image Acquisition (WIA) right click -> Properties -> Log On tab -> select local System Account and Allow service to interact with desktop.
I tried it, didnt work, so I turned back to "This account" with Local Service user.

Related

Issues with using Managed WiFi (NativeWiFi API)

I am trying to create and connect to a WLAN profile using Native WiFi (https://managedwifi.codeplex.com/). I am able to view all the Network BSS List and their parameters. However, when I am trying to create/overwrite a WLAN profile, I get the below mentioned error message (Error#1):
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in ManagedWifi.dll.
Additional information: The network connection profile is corrupted
However, when I created a profile normally from "Network and Sharing Center" of the Windows 7 control panel and then tried to connect using the ManagedWiFi, I get another error message(Error#2):
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Type 'NativeWifi.Wlan+WlanReasonCode' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
I noticed that this error occurs even if I try to connect/disconnect to a WLAN profile from the "Network and Sharing Center", with the windows application running in the background.
Here is the sample code that I am using:
Dim profileName As String = GlobalVariables.ssidname ' Provides the selected SSID name from the Network BSS List
Dim hexval As String = StringToHex(GlobalVariables.ssidname) ' Function to get the hexadecimal value for a provided string
Dim key As String = TextBox1.Text ' Security key from the textbook provided
Dim profileXml As String = String.Format("<?xml version=""1.0""?><WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><MSM><security><authEncryption><authentication>open</authentication><encryption>WEP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>networkKey</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>", 'GlobalVariables.ssidname, hexval, TextBox1.Text)
wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, True) 'Error#1 occurs here
wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName) 'Error#2 occurs here
From the forum "Type Native Wifi.Wlan + WlanReasonCode cannot be marshaled error", the issue (Error#2) seems to be within the WlanAPI.cs, where there is a line of code that checks for the size of the return code. This is the line:
int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanReasonCode));
if (notifyData.dataSize >= expectedSize)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
Changing the above code to the below seems to fix the issue.
//int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanReasonCode));
if (notifyData.dataSize >= 0)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
However, I am not sure on how to add this fix to my solution. I installed the ManagedWiFi from the NuGet Package Manager. Hence, not sure how to change the WlanApi.cs file. Any help regarding the above mentioned two issues are much appreciated.
The issue (Error#1) is now resolved. The profilexml file format was different for me. Here is the profilexml after I changed it.
Dim profileXml As String = String.Format("<?xml version=""1.0""?><WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey></security></MSM></WLANProfile>", GlobalVariables.ssidname, hexval, TextBox1.Text)
Also the second issue (Error#2) was resolved when I uninstalled ManagedWiFi package from my solution and added the whole ManagedWiFi project to the solution. Then I made the change in WlanApi.cs as mentioned in SimpleWiFi Or Type Native Wifi.Wlan + WlanReasonCode cannot be marshaled error.
I had a simpler task (read the SSID of the connected network), which was throwing the same error.
I solved it by switching to using SimpleWiFi entirely and ignore the ManagedWifi package.
Glancing at the source code, it looks like SW is a fixed reimplementation of some of the functionality in MW.

Windows Phone 8.1 - Receive files with OBEX

i have successfully implemented a library for sending files over Bluetooth via Obex Object Push Profile on Windows Phone 8.1 app (C#).
Anyway, I need to implement also the opposite direction (receive files via OPP) but I'm not able to find a way to override the already existing OPP system service.
The problem is that when a file is sent from a device to my windows phone application, the system service 'catch' it first (and the message "DeviceX is sharing a file with you, receive content?" is shown).
If i try to use RfcommConnectionTrigger and register a background task triggered by an incoming ObexObjectPush request, an exception raises: "The process cannot access the file because it is being used by another process. (Exception from HRESULT: 0x80070020)". I imagine that the other process is the system service.
Anyone knows out to solve this?
I report the code for the background task registration below:
string taskName = RfcommServiceId.ObexObjectPush.AsString();
if (BackgroundTaskRegistration.AllTasks.Values.SingleOrDefault(x => x.Name == taskName) == null)
{
RfcommConnectionTrigger trigger = new RfcommConnectionTrigger
{
};
trigger.InboundConnection.LocalServiceId = RfcommServiceId.ObexObjectPush;//OPPprovider.ServiceId;
BackgroundTaskBuilder builder = new BackgroundTaskBuilder
{
Name = taskName,
TaskEntryPoint = "WP_OPPServerBackgroundTask.OppTask",
};
builder.SetTrigger(trigger);
builder.Register();
}
Thanks in advance for any hint on this topic
Lorenzo

UWP: BluetoothDevice.FromBluetoothAddressAsync throws 0x80070002 exception on non-discoverable & unpaired BT device

I'm trying to pair from a Universal Windows C# app to a Bluetooth - Serial converter, without user interaction.
Development is in Visual Studio 2015 under Windows 10 Pro, but app is intended to run in any Windows 10 based device with a Bluetooth adapter.
For security reasons, BT-serial converter isn't discoverable and is protected by a pin, so I'm not able to perform any enumeration procedure to detect and pair it.
My application only knows BT address (MAC) and PIN's device (Also it knows friendly Bluetooth name, but I never used it).
Previously I'd been able to perform this task under Windows Mobile 6 Pocket PC, using Windows Mobile SDK and C++, but unfortunately code isn't portable to Universal Windows Platform.
Playing with MS samples for Universal Windows(https://github.com/Microsoft/Windows-universal-samples) I achieved to write a code that achieves to pair device, creating from strings some objects that in source sample are derived from enumeration process.
But it only works if device is visible. This is the code:
using System;
using Windows.UI.Xaml.Controls;
using Windows.Networking;
using Windows.Devices.Enumeration;
using Windows.Devices.Bluetooth;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace UWPBTTest
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
DoPairing();
}
async public void DoPairing()
{
UInt64 targetMAC = 32217180653; //target MAC in decimal, this number corresponds to my device (00:07:80:4b:29:ed)
BluetoothDevice btDev = await BluetoothDevice.FromBluetoothAddressAsync(targetMAC); //We create target BT device object, here app throws 0x80070002 exception
DeviceInformation infDev = btDev.DeviceInformation; //We need this aux object to perform pairing
DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ProvidePin; //Only confirm pairing, we'll provide PIN from app
DevicePairingProtectionLevel protectionLevel = Windows.Devices.Enumeration.DevicePairingProtectionLevel.Encryption; //Encrypted connection
DeviceInformationCustomPairing customPairing = infDev.Pairing.Custom; //Our app takes control of pairing, not OS
customPairing.PairingRequested += PairingRequestedHandler; //Our pairing request handler
DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel); //launc pairing
customPairing.PairingRequested -= PairingRequestedHandler;
if ((result.Status == DevicePairingResultStatus.Paired) || (result.Status == DevicePairingResultStatus.AlreadyPaired))
{
//success, now we are able to open a socket
}
else
{
//pairing failed
}
}
//Adapted from https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/DeviceEnumerationAndPairing , scenario 9
private async void PairingRequestedHandler(
DeviceInformationCustomPairing sender,
DevicePairingRequestedEventArgs args)
{
switch (args.PairingKind)
{
case DevicePairingKinds.ConfirmOnly:
// Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile
// If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation.
args.Accept();
break;
case DevicePairingKinds.ProvidePin:
// As function must be asyn, we simulate a delay of 1 second on GetPinAsync
var collectPinDeferral = args.GetDeferral();
string pin = "1234"; //BT converter pin, currently is "1234" for testing purposes
args.Accept(pin);
collectPinDeferral.Complete();
break;
}
}
}
}
This prototype app uses a blank form, as all data are hardcoded.
Also in Package.appxmanifest -> Capabilities, I checked all fields to discard any permission lack.
Currently this code only can perform pairing operation if BT-serial converter is visible.
If BT device isn't visible, BluetoothDevice.FromBluetoothAddressAsync throws an exception (Resource not found: 0x80070002), instead of creating the BluetoothDevice object.
Is as if Windows "needed" to know something of BT device in order to perform operation, I suspect that when I call FromBluetoothAddressAsync, OS internally lists all devices in system (this includes detected BT devices in range) looking for and item with given address.
I've been looking for other methods to perform mac-based pairing against hidden bt devices, but without success (maybe some type of "pre-pairing"? I didn't find anything)
Thanks.

C# White UI Automation: can't find SWT window

I'm using White for UI automation and it was working fine until I met an app that was created in Java. In that case I'm unable to find any windows. If I get all Windows from the desktop then I can see the window's name I'm looking for:
List<White.Core.UIItems.WindowItems.Window> windows = new List<White.Core.UIItems.WindowItems.Window>();
windows = White.Core.Desktop.Instance.Windows();
int a = 0;
for (int i = 0; i < windows.Count; i++)
if (windows[i].Name == "HP Service Manager Client") a = i;
This is working, but if I attach the running process and try to get its windows, then I get nothing, the list will be empty:
windows=app.GetWindows();
This is the code that should find the main window:
var processes = Process.GetProcessesByName("ServiceManager");
White.Core.Application app = White.Core.Application.Attach(processes[0]);
White.Core.UIItems.WindowItems.Window main = app.GetWindow(SearchCriteria.ByText("HP Service Manager Client"), InitializeOption.NoCache);
The error I get: Additional information: Couldn't find window with SearchCriteria Name=HP Service Manager Client in process 7396, after waiting for 5000 ms
I can see the Window in VisualUIAVerify and I know that the name of it is correct.
This is the only app which is not working, IE, Firefox, etc. are all working fine, I can always identify the main window, but this time I can't find any windows at all.
I wonder if someone could explain me why it is doing this and help me to resolve this issue (or find a workaround). Many thanks in advance.

PrintServerException - "...name is invalid" even though I can access the path from windows

A line similar to the following threw the above exception:
PrintServer ps = new PrintServer(#"\\prntsrv");
When I use "Run..." on Windows the address above does work and take me to the list of print jobs so why does the line of code not work?
Apparently, the address \\prntsrv was a DNS alias to \\prntserv and the PrintServer constructor was unable to deal with it. To get around this issue I used the following code (I could also use just the code in the catch block instead and it would work, but preferred not to):
try
{
// Create object to monitor the printer queue
PrintServer printServer = new PrintServer(serverPath);
mPrintQueue = printServer.GetPrintQueue(printerName);
}
catch (PrintServerException ex)
{
// If the problem might be creating the server because the name is an alias
if (ex.Message.Contains("printer name is invalid."))
{
string actualServerHostname = "\\\\" + Dns.GetHostEntry(serverPath.TrimStart('\\')).HostName;
// Create object to monitor the printer queue
PrintServer printServer = new PrintServer(actualServerHostname);
mPrintQueue = printServer.GetPrintQueue(printerName);
// Write to log about the use of a different address
}
else
{
throw;
}
}
hey i was facing similar issue, this is what i observed and made following changes, just try and let me know.
This issue was occuring due to windows feature/role "Print and Document service" is missing on the system. This role is required for managing multiple printers or print servers and migrating printers to and from other windows servers.
To add the role Go To Control Panel->Turn windows feature on or off->click on check box "Print and Document Service"->install.
See with network administrator for installing this rule if you unable to add it.
After adding the role you can able to create print server object and get the all the printqueues on respective server.

Categories

Resources