This problem prevents connecting to a new network using Simple WiFi (NuGet, GitHub). For whatever reason, a connection point that already has a profile works just fine.
The problem line is accessPoint.Connect(request). When the password is wrong, this works fine. When the password is right, however, an exception gets thrown from System.Private.CoreLib.
After taking a look at other samples on the web, it seems like everything is done correctly. I therefore created a sample application to reproduce the error (WPF, .NET 6.0):
MainWindow.xaml.cs
using SimpleWifi;
using SimpleWifi.Win32;
using System;
using System.Linq;
using System.Windows;
using System.Windows.Media;
namespace SimpleWiFi_Test_Wpf
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
RefreshAndAssignWiFiConnections();
}
private void RefreshAndAssignWiFiConnections()
{
// Refresh WiFi list
// https://stackoverflow.com/a/65024992/4682228
var client = new WlanClient();
foreach (WlanInterface wlanInterface in client.Interfaces)
wlanInterface.Scan();
Wifi wifi = new Wifi();
var accessPoints = wifi.GetAccessPoints()
.OrderByDescending(ap => ap.SignalStrength)
.Where(ap => !string.IsNullOrEmpty(ap.Name))
.Select(ap => ap.Name)
.ToList();
ComboBox_WiFiConnections.ItemsSource = accessPoints;
ComboBox_WiFiConnections.SelectedItem = accessPoints.FirstOrDefault();
}
private void ComboBox_WiFiConnections_DropDownOpened(object sender, EventArgs e)
{
RefreshAndAssignWiFiConnections();
}
private void PasswordBox_WiFiPassword_PasswordChanged(object sender, RoutedEventArgs e)
{
PasswordBox_WiFiPassword.BorderBrush = Brushes.Transparent;
}
private void Button_WiFiLogin_Click(object sender, RoutedEventArgs e)
{
Wifi wifi = new Wifi();
var accessPointName = ComboBox_WiFiConnections.SelectedValue as string;
var accessPoint = wifi.GetAccessPoints().FirstOrDefault(ap => ap.Name == accessPointName);
AuthRequest request = new(accessPoint)
{
Password = PasswordBox_WiFiPassword.Password,
};
try
{
if (request.IsUsernameRequired)
{
// Doesn't reach: username not missing
}
if (request.IsDomainSupported)
{
// Doesn't reach: no domain supported
}
if (accessPoint.Connect(request)) // This call throws the exception
{
// Success!
// ...
}
else
{
// Wrong password
PasswordBox_WiFiPassword.BorderBrush = Brushes.Red;
}
}
catch (Exception ex)
{
// "Value cannot be null. (Parameter 'stream')"
// at System.ThrowHelper.ThrowArgumentNullException(ExceptionArgument argument)
// at System.IO.StreamReader..ctor(Stream stream, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean leaveOpen)
// at SimpleWifi.ProfileFactory.GetTemplate(String name)
// at SimpleWifi.ProfileFactory.Generate(WlanAvailableNetwork network, String password)
// at SimpleWifi.AuthRequest.Process()
// at SimpleWifi.AccessPoint.Connect(AuthRequest request, Boolean overwriteProfile)
// at MecaView.Main.Button_WiFiLogin_Click(Object sender, RoutedEventArgs e) in C: \Users\dlabrecque\Documents\GitHub\MecaView\Prj\Main.xaml.cs:line 669
}
}
}
}
MainWindow.xaml
<StackPanel>
<ComboBox x:Name="ComboBox_WiFiConnections" DropDownOpened="ComboBox_WiFiConnections_DropDownOpened" Width="200"/>
<PasswordBox x:Name="PasswordBox_WiFiPassword" PasswordChanged="PasswordBox_WiFiPassword_PasswordChanged" Width="200"/>
<Button x:Name="Button_WiFiLogin" Click="Button_WiFiLogin_Click" Content="Login" Width="200"/>
</StackPanel>
Anyone know why this exception might be happening? A missing parameter? A bug in the library?
Note: it may be others are getting a problem with the same symptoms; question 1, question 2.
Related
I am trying to call WPF client code from WebBrowser control as given in the example https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.webbrowser.objectforscripting?redirectedfrom=MSDN&view=netframework-4.8#System_Windows_Forms_WebBrowser_ObjectForScripting. The example provided in the link is for Windows forms. I am trying to do similar thing in WPF. However, I am getting following error.
Managed Debugging Assistant 'NonComVisibleBaseClass' : 'A QueryInterface call was made requesting the default IDispatch interface of COM visible managed class 'WpfApp2.MainWindow'. However since this class does not have an explicit default interface and derives from non COM visible class 'System.Windows.Window', the QueryInterface call will fail. This is done to prevent the non COM visible base class from being constrained by the COM versioning rules.'
Is there any way to resolve this? or it just cannot be done in WebBrowser-control and WPF ?
We need to create a separate class and use it for scripting
using System.Windows;
using System.Security.Permissions;
using System.Windows.Controls;
using System;
namespace WpfApp2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public class ObjectForScriptingHelper
{
public void Test()
{
MessageBox.Show("xxxxx");
}
}
public MainWindow()
{
InitializeComponent();
button1.Content = "call script code from client code";
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
//webBrowser1.AllowWebBrowserDrop = false;
//webBrowser1.IsWebBrowserContextMenuEnabled = false;
//webBrowser1.WebBrowserShortcutsEnabled = false;
webBrowser1.ObjectForScripting = new ObjectForScriptingHelper();
// Uncomment the following line when you are finished debugging.
//webBrowser1.ScriptErrorsSuppressed = true;
webBrowser1.Navigate(#"C:\temp\WpfApp2\WpfApp2\HTMLPage1.html");
}
private void Button1_Click_1(object sender, RoutedEventArgs e)
{
webBrowser1.InvokeScript("test",
new String[] { "called from client code" });
}
}
}
I've looked at a lot of other stack overflow posts but none of them really were similar to what I am trying to accomplish. Basically, I am trying to connect to a device running Windows CE through an SSH connection and capture any output that is printed to the terminal. When I connect via ssh using Putty I can see many print statements in the terminal which are used for debugging. I am trying to capture these debugging statements and use them in my wpf application. These debugging statements are not a response to a command, they are just printed to the terminal.
So far I am able to send a command and receive a single response but what I am looking for is to be able to receive a response indefinitely, until the user closes the connection or the application.
I am using Renci.SshNet to send my commands and I was messing around with using a ShellStream but was not able to get it working. Here is what I have so far:
using System;
using System.Threading;
using System.Windows;
using Renci.SshNet;
namespace TestSshConsole
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private SshClient _sshConnection;
private ShellStream _shellStream;
private delegate void UpdateTextCallback(string message);
public MainWindow()
{
InitializeComponent();
}
/// <summary>
/// When the user presses connect, connect to the device
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Button_Click(object sender, RoutedEventArgs e)
{
try
{
// Connect to device
_sshConnection = new SshClient(hostname.Text, int.Parse(port.Text), username.Text, password.Text);
_sshConnection.Connect();
// Create a shell stream
_shellStream = _sshConnection.CreateShellStream("test", 80, 60, 800, 600, 65536);
MessageBox.Show("Connected!");
}
catch (Exception exception)
{
MessageBox.Show($"Error {exception.Message}");
}
}
/// <summary>
/// Start a new thread used to receive SSH data when the window is loaded
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ThreadStart threadStart = new ThreadStart(RecvSshData);
Thread thread = new Thread(threadStart);
thread.IsBackground = true;
thread.Start();
}
/// <summary>
/// Receive SSH data and write it to the textbox
/// </summary>
private void RecvSshData()
{
while (true)
{
try
{
if (_shellStream != null && _shellStream.DataAvailable)
{
string data = _shellStream.Read();
textBox.Dispatcher.Invoke(new UpdateTextCallback(UpdateText), data);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
Thread.Sleep(200);
}
}
/// <summary>
/// Write message to the textbox
/// </summary>
/// <param name="message"></param>
private void UpdateText(string message)
{
textBox.AppendText(message + "\r\n");
}
}
}
From what I have read in other posts it seems like this should work and should capture all of the data but it does not. There could be something I am doing wrong in my implementation or they may even be a better way to do it.
Any input with help or recommendations is appreciated.
I got it working to a certain extent. "StartRecording" begins to record the stream on a separate thread which works and just writes it to the console for now. This is able to receive all of the data that is printed to the terminal on my device.
The only issue that I am having now is that the data stops coming through after about a minute. I'm not sure what is happening yet but I think the ShellStream is disconnecting at some point and I'm not sure why.
private SshClient _sshClient;
private ShellStream _shellStream;
private StreamReader _reader;
private StreamWriter _writer;
public Recorder()
{
try
{
_sshClient = new SshClient(_hostname, _port, _username, _password);
_sshClient.Connect();
_shellStream = _sshClient.CreateShellStream("Terminal", 80, 60, 800, 600, 65536);
_reader = new StreamReader(_shellStream, Encoding.UTF8, true, 1024, true);
_writer = new StreamWriter(_shellStream) { AutoFlush = true };
}
catch (Exception e)
{
// TODO
Console.WriteLine(e);
}
}
/// <summary>
/// Begin recording the output of "routediagnostic on" command
/// </summary>
public void StartRecording()
{
try
{
IsRecording = true;
WriteStream("routediagnostic on");
// Start a background thread that will read in the data from the Pyng terminal
ThreadStart threadStart = ReceiveData;
Thread thread = new Thread(threadStart) {IsBackground = true};
thread.Start();
}
catch (Exception e)
{
// TODO
Console.WriteLine(e);
}
finally
{
IsRecording = false;
}
}
private void ReceiveData()
{
while (true)
{
try
{
if (_reader != null)
{
StringBuilder result = new StringBuilder();
string line;
while ((line = _reader.ReadLine()) != null)
{
result.AppendLine(line);
}
if (!string.IsNullOrEmpty(result.ToString()))
{
// TODO - Parse data at this point
Console.WriteLine(result.ToString());
}
}
}
catch (Exception e)
{
// TODO
Console.WriteLine(e);
}
Thread.Sleep(200);
}
}
private void WriteStream(string cmd)
{
_writer.WriteLine(cmd);
while (_shellStream.Length == 0)
{
Thread.Sleep(500);
}
}
I've had a look at this post but still can't seem to fix this problem: Resolving an ambiguous reference
I'm trying to make a button in WPF that when clicked browses for an excel file and then opens it. However I keep getting the error
'Path' is an ambiguous reference between 'system.windows.shapes.path'
and 'system.io.path'
Below is my code. I've tried explicity using
System.IO.Path.GetFullPath(fileDialog.FileName)
Below is my full code:
using Microsoft.Win32;
using System.Windows;
using System.IO;
using Excel = Microsoft.Office.Interop.Excel;
namespace Fasetto
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new WindowViewModel(this);
}
private void WindowCloseButton_Click(object sender, RoutedEventArgs e)
{
SystemCommands.CloseWindow(this);
}
private void WindowMinimizeButton_Click(object sender, RoutedEventArgs e)
{
SystemCommands.MinimizeWindow(this);
}
private void WindowMaximizeButton_Click_1(object sender, RoutedEventArgs e)
{
SystemCommands.MaximizeWindow(this);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
FileDialog fileDialog = new OpenFileDialog();
fileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";
fileDialog.ShowDialog();
string location = System.IO.Path.GetFullPath(fileDialog.FileName);
}
}
public class Read_From_Excel
{
public void getExcelFile(string filename)
{
Excel.Application xlApp = new Excel.Application();
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename);
}
}
This is the line that fires the error, with the variable 'filename' underlined in red:
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(filename);
I am automating MSWord in a WPF application. Everything working fine, but
a Click on Start -> Microsoft word 2010 attaches a new blank document to my instance which is already created by the Wpf application.How restrict this behaviour ?
public partial class MainWindow : System.Windows.Window
{
Word.Application _oApp;
Word.Document _oDoc;
object oMissing = System.Reflection.Missing.Value; // Missing Value
object oTrue = true;
object oFalse = false;
public MainWindow()
{
InitializeComponent();
}
private void btn_Create_Click(object sender, RoutedEventArgs e)
{
_oApp = new Word.Application();
_oApp.Visible = true;
_oApp.ShowWindowsInTaskbar = false;
((Word.ApplicationEvents4_Event)_oApp).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
}
private void btn_AddDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc = _oApp.Documents.Add(oMissing, oMissing, oMissing);
}
private void btn_RemoveDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc.Close(oFalse, oMissing, oMissing);
}
private void Application_NewDocument(Word.Document doc)
{
MessageBox.Show("New: " + _oApp.ActiveDocument.Name);
}
}
Microsoft listed this as a bug and illustrated a workaround to this problem in the following KB article
BUG: Starting Word Manually Uses Same Instance as Automation -
https://support.microsoft.com/en-us/kb/188546
using System.Windows;
using Word = Microsoft.Office.Interop.Word;
namespace WordAutomationTestApp
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : System.Windows.Window
{
Word.Application _oApp;
Word.Document _oDoc;
object oMissing = System.Reflection.Missing.Value; // Missing Value
object oTrue = true;
object oFalse = false;
public MainWindow()
{
InitializeComponent();
}
private void btn_Create_Click(object sender, RoutedEventArgs e)
{
//To restrict the automation instance sharing with the user's documents.
//Create a temporary app instance and quit the same after the automation instance is created.
//Ref :: Go through the following work around.
//https://support.microsoft.com/en-us/kb/188546
Word.Application temp = new Word.Application(); //Create temporary instance.
_oApp = new Word.Application(); //Create automation instance.
temp.Quit(oFalse,oMissing,oMissing); //Close the temporary instance.
temp = null;
_oApp.Visible = true;
_oApp.ShowWindowsInTaskbar = false;
((Word.ApplicationEvents4_Event)_oApp).NewDocument += new Word.ApplicationEvents4_NewDocumentEventHandler(Application_NewDocument);
}
private void btn_AddDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc = _oApp.Documents.Add(oMissing, oMissing, oMissing);
}
private void btn_RemoveDoc_Click(object sender, RoutedEventArgs e)
{
_oDoc.Close(oFalse, oMissing, oMissing);
}
private void Application_NewDocument(Word.Document doc)
{
MessageBox.Show("New: " + _oApp.ActiveDocument.Name);
}
}
}
My sincere thanks to #Cindy Meister , for his help to solve this problem.
I'm developing a dnn module. And i used codebehind C#. But DNN shows error when I add a the module. Other pages work just fine but the page I add the module to says DotNetNuke error. The error does not have any code and it only displays my logo. Even the admin strip disappears.
What did i do wrong?
using System;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Security;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using System.Web.UI;
using System.Configuration;
//imports
namespace DotNetNuke.Modules.Catagory
{
public partial class View : CatagoryModuleBase, IActionable
{
public bool inEdit = false;
private bool IsValid = true;
#region Event Handlers
override protected void OnInit(EventArgs e)
{
InitializeComponent();
base.OnInit(e);
}
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
private void Page_Load(object sender, System.EventArgs e)
{
try
{
if (IsPostBack)
{
if (Catagory_Table.SelectedRow != null)
{ //There is a selected item, hence edit mode Catagory_Table.SelectedIndex >= 0
this.inEdit = true;
to_edit_mode();
}
else
{
to_add_mode();
}
}
else
{
to_add_mode();
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
protected void Button1_Click(object sender, System.Web.UI.ImageClickEventArgs e)
{
SqlDataSource1.Insert();
}
//the rest if the methods to handle the buttton events....
}
You will want to try to check the Admin/Event Viewer to see what the error is specifically, then you can be better informed on what it will take to fix.