"source()" not executing - c#

I'm trying to code a visual interface for some R scripts using R.NET, C# and Visual Studio. The R scripts work fine when executing them on RStudio. This is the code that gives problems:
StartupParameter rinit;
private void Form1_Load(object sender, EventArgs e)
{
rinit = new StartupParameter();
rinit.Quiet = true;
rinit.RHome = "C:/Program Files/R/R-3.4.0";
rinit.Interactive = true;
REngine engine= REngine.GetInstance();
REngine.SetEnvironmentVariables(#"C:\Program Files\R\R-3.4.0\bin\i386", #"C:\Program Files\R\R-3.4.0");
engine.Evaluate("source('../../rsc/Rscripts/CargarPaquetes.r')");
engine.Evaluate("source('../../rsc/Rscripts/IntroducirDatos.r')");
engine.Evaluate("source('../../rsc/Rscripts/UnirTablas.r')");
engine.Evaluate("PorcentajeEnfermedades<- prop.table(table(TablaTotal$Enfermedad))*100");
var Porcentajes = engine.Evaluate("cbind(Frecuencia=table(TablaEntrenamiento$Enfermedad),Porcentaje=PorcentajeEnfermedades)").AsCharacter().ToArray();
MessageBox.Show(Convert.ToString(Porcentajes[0]));
engine.Dispose();
}
Some code may be unnecessary, I don't understand at all how R.NET works and there isn't much documentation. The program don't stop running and I don't get any exception message, but the MessageBox never appears. When I execute the code step by step I see that the code is only executed from the beggining to engine.Evaluate(#"source('../../rsc/Rscripts/CargarPaquetes.r')");
(included). The rest of the lines are never executed and I can't figure out why.
By the way, if someone could recommend me any good documentation site for R.NET i would be very grateful.
----EDIT----
I created a button and moved all this code to the click event, and now the program stops and show the following error:
RDotNet.EvaluationException: 'Error in library(caret) : there is no package called 'caret'
The script "CargarPaquetes.r" basically loads a set of packages. I moved from R 3.5 to R 3.4, because R.NET gave some problems in the newer version...and now I have to deal with some bad installed packages.
Despite having solved the problem, it would be interesting to find out why the exeption was not called in the Load event.

Related

UIAutomation throws AccessViolationException on Windows 11

The issue:
We have an application written in C# that uses UIAutomation to get the current text (either selected or the word behind the carret) in other applications (Word, OpenOffice, Notepad, etc.).
All is working great on Windows 10, even up to 21H2, last update check done today.
But we had several clients informing us that the application is closing abruptly on Windows 11.
After some debugging I've seen some System.AccessViolationException thrown when trying to use the TextPatternRange.GetText() method:
System.AccessViolationException: 'Attempted to read or write protected memory. This is often an indication that other memory is corrupt.'
What we've tried so far:
Setting uiaccess=true in manifest and signing the app : as mentionned here https://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/350ceab8-436b-4ef1-8512-3fee4b470c0a/problem-with-manifest-and-uiaccess-set-to-true?forum=windowsgeneraldevelopmentissues => no changes (app is in C:\Program Files\
In addition to the above, I did try to set the level to "requireAdministrator" in the manifest, no changes either
As I've seen that it may come from a bug in Windows 11 (https://forum.emclient.com/t/emclient-9-0-1317-0-up-to-9-0-1361-0-password-correction-crashes-the-app/79904), I tried to install the 22H2 Preview release, still no changes.
Reproductible example
In order to be able to isolate the issue (and check it was not something else in our app that was causing the exception) I quickly made the following test (based on : How to get selected text of currently focused window? validated answer)
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
var p = Process.GetProcessesByName("notepad").FirstOrDefault();
var root = AutomationElement.FromHandle(p.MainWindowHandle);
var documentControl = new
PropertyCondition(AutomationElement.ControlTypeProperty,
ControlType.Document);
var textPatternAvailable = new PropertyCondition(AutomationElement.IsTextPatternAvailableProperty, true);
var findControl = new AndCondition(documentControl, textPatternAvailable);
var targetDocument = root.FindFirst(TreeScope.Descendants, findControl);
var textPattern = targetDocument.GetCurrentPattern(TextPattern.Pattern) as TextPattern;
string text = "";
foreach (var selection in textPattern.GetSelection())
{
text += selection.GetText(255);
Console.WriteLine($"Selection: \"{selection.GetText(255)}\"");
}
lblFocusedProcess.Content = p.ProcessName;
lblSelectedText.Content = text;
}
When pressing a button, this method is called and the results displayed in labels.
The method uses UIAutomation to get the notepad process and extract the selected text.
This works well in Windows 10 with latest update, crashes immediately on Windows 11 with the AccessViolationException.
On Windows 10 it works even without the uiaccess=true setting in the manifest.
Questions/Next steps
Do anyone know/has a clue about what can cause this?
Is Windows 11 way more regarding towards UIAutomation?
On my side I'll probably open an issue by Microsoft.
And one track we might follow is getting an EV and sign the app itself and the installer as it'll also enhance the installation process, removing the big red warnings. But as this is an app distributed for free we had not done it as it was working without it.
I'll also continue testing with the reproductible code and update this question should anything new appear.
I posted the same question on MSDN forums and got this answer:
https://learn.microsoft.com/en-us/answers/questions/915789/uiautomation-throws-accessviolationexception-on-wi.html
Using IUIautomation instead of System.Windows.Automation works on Windows 11.
So I'm marking this as solved but if anyone has another idea or knows what happens you're welcome to comment!

Serial Port "SerialPort.GetPortNames" not reading anything

Trying to code up a little serial port communications/control panel in C# with Visual Studio 2022. I'm making it up as a WindowsForm app using .Net Framework 4.8. When launching the code all the other aspects work fine (as far as I can test them without being able to choose and connect to a paired serial port). In the window it creates I'm able to navigate without a problem but the combo box that should have the serial ports listed in it instead remains blank. Debugging and monitoring the value of "ports" also has it responding with either "error CS0103: The name 'ports' does not exist in the current context" or just "null". Another similar program uses the same logic to obtain the ports created with the virtual port emulator software I am using and this works without a worry.
Early Relevant Code Blocks
public partial class Form1 : Form
{
string dataOUT;
string sendWith;
string dataIN;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
string[] ports = SerialPort.GetPortNames();
cBoxCOMPORT.Items.AddRange(ports);
btnOpen.Enabled = true;
btnClose.Enabled = false;
chBxDTR.Checked = false;
serialPort1.DtrEnable = false;
chBxRTS.Checked = false;
serialPort1.RtsEnable = false;
btnSendOut.Enabled = true;
sendWith = "Both";
toolStripComboBox1.Text = "Add to Old Data";
toolStripComboBox2.Text = "Both";
toolStripComboBox3.Text = "BOTTOM";
}
~additional non-relevant functions
}
I'm sure the ports are available as the previous code solution can still find them so I don't think it's a problem with drivers or my virtual comm ports and I've check them on HKEY_LOCAL_MACHINE and they are present. The old solution was made around a week ago so it might be using .NET Framework 4.7.2 instead of 4.8. Regardless I have just copied and adjusted snippets of relevant code across and remade the design layout. There are no compilation errors or warnings either and I am for sure including the "using System.IO.Ports;" line.
I was following a guide provided on YouTube (https://www.youtube.com/watch?v=I6uhMIFTF24) and it worked. I did however have to remake it on a fresh solution and for whatever reason now the same lines of code don't obtain any of the ports made available.
Any help or ideas would be appreciated. No clue where to look or what to fiddle with to get it to find them in this solution.
I think I've found the issue. The Form1 was not triggering the Form1_Load event when launching the program and creating the window Form1 is the main window in the [Design] tab and under its properties the 'Load' box option had no event tied to it. Changed that to be 'Form1_Load' and this now gets that block of code working so it's finding/displaying the COM Ports as well as all the other related set up. Not sure why this wasn't happening by default or if I missed a step creating it. Will add anything else that develops if a similar issue pops up but hopefully that's the end of that.

Object Reference Error when Debugging Webpage

I'm having issues with a piece of code for a website in C# and when I debug it, it opens the site (localhost in Chrome. Every page works except the one I'm debugging, regardless of whether or not that's the page I'm debugging. Whenever I try to open it, it gives me an Object Reference error at the line I've marked below. This happens no matter which browser I use.
Protected void page_load (object sender, EventArgs e)
{
DateTime dteNow = SI.Getsource.DAL.Time.Now.Eastern();
If(!IsPostBack)
{
txtStartDate.SelectDate = dteNow.AddDays(-2)
txtEndDate.SelectedDate = dtenow.AddDays(1)
txtStartDate.Visible = False
txtEndDate.Visible = False
Shipping.DataTable.dt = SI.Getsource.DAL.EquipmentDB.getPrinter();
ddlPrinter.DataSource = dt.Result
ddlPrinter.DataTextField = dt.Result.Columns["Name"] //Error is here
ddlPrinter.DataValueField = dt.Result.Columns["PrinterID"]
ddlPrinter.DataBind();
Try
{
ddlPrinter.SelectedValue = System.Web.Configuration.WebConfigurationManager.AppSettings["DefaultPrinterID"]
}
Catch
}
}
I've tried running it in IE and Firefox. I also tried adding a try-catch for "Name" similar to the one for "Printer" but that didn't do anything. Any suggestions would be greatly appreciated, since this error prevents me from debugging the actual issue.
Edit: I'm using Visual Studio 2015. Also, this only happens when I run the page locally, ie. When debugging.
Set a breakpoint on the line giving you the error, then add dt.Result to the Watch window to examine its value when the execution breaks on this line. It could be that dt.Result is null.
edit: Also, I think you only need to specify the field name for .DataTextField and .DataValueField.
As it turns out, it was an issue with memory. Once I took care of that, it worked.

Console.WriteLine does not show up in Output window

I have put some Console.WriteLine calls in to test, but they aren't appearing in the output box?
public static ArrayList myDeliveries = new ArrayList();
public mainForm(){
InitializeComponent();
}
private void mainForm_Load(object sender, EventArgs e){
if (!File.Exists("../../MealDeliveries.txt")){
MessageBox.Show("File not found!");
return;
}
using (StreamReader sr = new StreamReader("../../MealDeliveries.txt")){
//first line is delivery name
string strDeliveryName = sr.ReadLine();
Console.WriteLine("Test content");
while (strDeliveryName != null){
//other lines
Delivery d = new Delivery(
strDeliveryName,
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine(),
sr.ReadLine()
);
mainForm.myDeliveries.Add(d);
//check for further values
strDeliveryName = sr.ReadLine();
}
}
displayDeliveries();
}
private void displayDeliveries(){
lstDeliveryDetails.Items.Clear();
Console.WriteLine("Test content");
Console.WriteLine(mainForm.myDeliveries.Count);
foreach (Delivery d in mainForm.myDeliveries){
lstDeliveryDetails.Items.Add(d.DeliveryName);
}
}
Can anyone help??
Console outputs to the console window and Winforms applications do not show the console window. You should be able to use System.Diagnostics.Debug.WriteLine to send output to the output window in your IDE.
Edit: In regards to the problem, have you verified your mainForm_Load is actually being called? You could place a breakpoint at the beginning of mainForm_Load to see. If it is not being called, I suspect that mainForm_Load is not hooked up to the Load event.
Also, it is more efficient and generally better to override On{EventName} instead of subscribing to {EventName} from within derived classes (in your case overriding OnLoad instead of Load).
If you intend to use this output in production, then use the Trace class members. This makes the code portable, you can wire up different types of listeners and output to the console window, debug window, log file, or whatever else you like.
If this is just some temporary debugging code that you're using to verify that certain code is being executed or has the correct values, then use the Debug class as Zach suggests.
If you absolutely must use the console, then you can attach a console in the program's Main method.
If you want Console.WriteLine("example text") output to show up in the Debug Output window, temporarily change the Output type of your Application from Console Application to Windows Application.
From menus choose Project + Properties, and navigate to Output type: drop down, change to Windows Application then run your application
Of course you should change it back for building a console application intended to run outside of the IDE.
(tested with Visual Studio 2008 and 2010, expect it should work in latter versions too)
Using Console.WriteLine( "Test" ); is able to write log messages to the Output Window (View Menu --> Output) in Visual Studio for a Windows Forms/WPF project.
However, I encountered a case where it was not working and only System.Diagnostics.Debug.WriteLine( "Test" ); was working. I restarted Visual Studio and Console.WriteLine() started working again. Seems to be a Visual Studio bug.
If you are developing a command line application, you can also use Console.ReadLine() at the end of your code to wait for the 'Enter' keypress before closing the console window so that you can read your output. However, both the Trace and Debug answers posted above are better options.
Try to uncheck the CheckBox “Use Managed Compatibility Mode” in
Tools => Options => Debugging => General
It worked for me.
Try to uncheck the CheckBox “Redirect all Output Window text to the Immediate Window” in
Tools => Options => Debugging => General
I had it checked and everything was written in the Immediate Window and not in the Output Window
When issue happening on Mac VS 2017 (Which I faced).
Go to Project >> "Your Project name" options.
An option window will pop up
Go to RUN >> Default menu option
Tick the "Run on external console" option TRUE and say OK
Run your application code now.
Old Thread, But in VS 2015 Console.WriteLine does not Write to Output Window If "Enable the Visual Studio Hosting Process" does not Checked or its Disabled in Project Properties -> Debug tab

C# Application not run

C# VS 2005.
I have developed an application that run perfectly on my development machine when I install it. However, it doesn't run on any of the clients machines.
I have tested with VMWare with a fresh install of windows, and still the application doesn't run.
I have added logging to try and determine where the application is failing. My previous versions worked, and after a week of development I gave to the client and then experienced this problem.
I have entered logging at the start and end of the constructor and form_load event. The constructor runs ok. However, at the end of the constructor it doesn't run in the form_load event as I have a log statement that should print out.
When the application runs it displays for a few seconds in task manager then fails to load.
I think this could be a very difficult problem to solve. So if anyone has experienced this before or could point me in the right direction to solve this problem.
The code in the form load event.
private void CATDialer_Load(object sender, EventArgs e)
{
my_logger.Info("Start of form load event"); // Doesn't display this.
.
.
}
===== Edit static main ====
[STAThread]
static void Main()
{
Application.SetCompatibleTextRenderingDefault(false);
// Get the language and set this cultureUI in the statusdisplay that will
// change the language for the whole program.
string language = CATWinSIP.Properties.Settings.Default.Language;
if (language == "th-TH")
{
StatusDisplay.StatusDisplay status_display = new StatusDisplay.StatusDisplay(true);
}
else if(language == "en-GB")
{
StatusDisplay.StatusDisplay status_display = new StatusDisplay.StatusDisplay(false);
}
try
{
Application.Run(new CATDialer());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
=== Constructor ===
public CATDialer()
{
//Set the language for all the controls on the form.
//Has to be done before all components are initialized.
//If not Thai language then must be using English.
if (Settings.Default.Language == "th-TH")
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("th-TH");
}
else
{
Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-GB");
}
InitializeComponent();
this.statusDisplay1.BalanceStatus = CATWinSIP_MsgStrings.BalanceStatus;
this.statusDisplay1.RedialHistory = CATWinSIP_MsgStrings.RedialHistory;
this.statusDisplay1.LoginStatus = CATWinSIP_MsgStrings.LoginSuccessful;
// Enable logging
XmlConfigurator.Configure();
logger.Info("CATDialer Constructor(): XmlConfigurator.Configure() Loaded [ OK ]");
// MessageBox.Show("Balance Status: " + this.statusDisplay1.BalanceStatus);
//Short cut menu.
this.SetupShortCutMenu();
this.fill_properties();
logger.Debug("CATDialer Constructor(): Fill properties loaded [ OK ]");
}
--
Hello,
Thanks for all the advice.
I have problem with one of my class libraries I created that used a crypto stream.
I found the answer when I added this to my program.cs
The message box displayed the information for the failed assembly.
Thanks,
try
{
Application.Run(new CATDialer());
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
Have you checked on a different development machine? Are your systems running same version of the .net framework? Is the .net framework installed correctly on the remote system? Have you tested your application in a different environment?
edit: have you tried spamming your log? Wrap the entire thing in a try catch and see what you can capture. Sometimes I found using the messagebox useful for this kind of logging (MessageBox.Show())
You probably need to post a bit more detail about the type of exception that is being thrown to get the most help.
If all the obvious checks such as having the correct framework version pass, the next thing to fail can often be a missing assembly.
If this is the case you may want to troubleshoot assembly loading in your app.
The MS Assembly Binding Log Viewer (fuslogvw) is a valuable piece of kit for this task.
In this sort of scenario I frequently find .NET assembly binding log viewer (Fusion) very useful in finding out what is going on. With fusion you can see which assemblies are being loaded and where they are being loaded from. More importantly for you, it is possible to enable it so that fusion also displays the assemblies that fail to load and where .NET tried to load them from.
Check out the MSDN article on fusion if you think this might help.

Categories