Issues with using Managed WiFi (NativeWiFi API) - c#

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.

Related

Error on getting device info using DeviceManager

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.

Terminal Services -: Value does not fall within the expected range

Test driving a remote desktop feature in an app but keep getting a weird error with the server name I'm putting in.
Code:
rdp.Server = txtServer.Text;
rdp.UserName = txtUser.Text;
IMsTscNonScriptable secured = (IMsTscNonScriptable)rdp.GetOcx();
secured.ClearTextPassword = txtPass.Text;
rdp.Connect();
Keep getting the error:
An unhandled exception of type 'System.ArgumentException' occurred in AxInterop.MSTSCLib.dll
Additional information: Value does not fall within the expected range.
On line:
rdp.Server = txtServer.Text;
txtServer.Text is being input as (but with a real address):
123.456.789.10:1234
Anybody else had this issue?
EDIT
The issue is with the port in the address, how can I get around this?
There should be an .AdvancedSettings.RDPPort property where you can set the port. Look at this CodeProject article, specifically page 2 of the comments.

Enumeration values for FaxJob.SetStatus method

Using Windows Fax Service, I am trying to cancel a fax from the Windows Fax Console. According to this worthless documentation I need to pass in a value JC_Delete which appears that it is some enumeration, however, the documentation fails to leave out what it is or how to get it.
I found another MSDN article stating in the last sentence that these JC values are just constants which the user defines. Finally, I found a forum post stating that it's just an enumeration in a C++ header file and the Microsoft guy showed the enumeration consisting of:
JC_UNKNOWN = 0
JC_DELETE = 1
JC_PAUSE = 2
JC_RESUME = 3
JC_RESTART = JC_RESUME
I just tried plugging in numbers, 0 or 1 since the method calls for an int and then I receive an exception
COM error:
the handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))
Here is my bit of code. I am able to get the FaxJob object just fine. It's just calling the SetStatus() method that bombs.
var job = this.getFaxJobsInQueue().Where(j => j.JobId == JobId).Single();
job.SetStatus(1);
Arg!! Found the problem! It was very simple! I forgot to connect to the fax console. Apparently that is what the handle is invalid was indicating. My problem was in the method that returned all the jobs connected and disconnected. Once I had the FaxJob object, I was suppose to connect again. Here is my updated code:
var job = this.getFaxJobsInQueue().Where(j => j.JobId == JobId).Single();
this.objFaxServer.Connect(faxServerConnectionString);
job.SetStatus(1);
this.objFaxServer.Disconnect();

DotNetCharting exception thrown

I am using DotNetCharting version 4.2. I am trying to create a chart, save it to disk and return the path as a string. Here is a simplified version of my code thus far.
Chart aChart = new Chart();
aChart aChart.Title = "Some Title";
aChart aChart.ChartArea.Background = new Background(Color.White);
aChart.TempDirectory = "C:\\temp\\"
aChart.Width = chartWidth;
aChart.Height = chartHeight;
imageName = aChart.FileManager.SaveImage();
I got this from this dotnetCharting support page. It is very straightforward code.
Here is the problem: The code above actually DOES create an image in the appropriate directory. This is NOT a directory permissions issue. When I add my actual data to the aChart, it actually DOES add it and an image is created. However, the SaveImage() method always throws an exception of "Failed to map the path '/'." The SaveImage() method is supposed to return a String, however, it always returns "" and the exception is thrown.
More Info: I am doing this in a WCF Service. Is it possible that since it's in a service the dotNetCharting DLL is having trouble with some internal MapPath?
I just upgraded the DotNetCharting to the latest version (7.0) and now it works fine. I believe that it was an issue with the old version of the DLL. I'll leave this here in case anyone else has this issue.

Refrences break console app from running on other machines

I've made a console application which inserts data into a MySql backend, and reads the serial number from a hard disk
To do this i had to add References to MySql.Data and to System.Managment.
The way im running it is by copying the Debug directory from visual studio (i think this is the problem) and running the .exe file on the other machine.
When i run the application on another machine the stack trace error is:
PhDD >C:\Users\User\File\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object: reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 49
Updated HDD Stats at28/03/2012 18:46:57
Am i correct in thinking this problem is because of the referencing ?
I've checked the methods by recompiling the same code on the other machine and it works, when the references are added through VS.
Can anyone guide me on how to resolve this issue ?
Cheers for reading.
P.S. i tried adding reference paths (by right clicking on the project, selecting options and then choosing Reference Paths and adding the two dll files)
Line 49
bool conversion = int.TryParse(smartData[1].ToString(), out temp);
After adding a fake int value just to make sure conversion isnt the error the new stack trace error is:
PhDD >C:\Users\bborisov\Dropbox\Indexer\WMI\Debug
Your key: 634685018347902535133
Exception getting SMART Object reference not set to an instance of an object.
Exception in main thread: at System.ThrowHelper.ThrowArgumentOutOfRangeExcept
ion()
at System.Collections.Generic.List`1.get_Item(Int32 index)
at WMITest.Menu.Run() in C:\Users\fps700\Music\WMITest\Menu.cs:line 53
Updated HDD Stats at28/03/2012 19:00:24
line 53:
DBHandler.insertData(smartData[0].Trim(),
3, smartData[2], file.getKey());
Put code in to check validity of error situations which may be happening on the client pc but not the development one. You can handle the errors by either throwing an exception or handling it gracefully in a better way.
Here is the code which checks for error situations
if (smartData == null)
throw new Exception("Smart data is null; aborting");
if (smartData.Any() == false)
throw new Exception("Smart data instance is valid but has no elements; aborting");
bool conversion = int.TryParse(smartData[1].ToString(), out temp);

Categories

Resources