Object Reference Error when Debugging Webpage - c#

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.

Related

Why is the Url value in C# WebBrowser always null?

I am trying to load a local HTML file into an instance of C# WebBrowser (WinForms).
This is what I am doing:
string url = #"file:///C:MyHtml/hello.html";
myWebbrowser.Url = new Uri(url, UriKind.Absolute);
object test = myWebbrowser.Url; // breakpoint here
The path above is correct; if I copy it and paste into an external browser, the file is immediately opened. But the instance of WebBrowser does not want to react. I set a breakpoint in the last line of the snippet, and what I get there is that myWebbrowser.Url is null (the test variable). The control remains correspondingly empty.
myWebbrowser.AllowNavigation is explicitly set to true. I have also tried all possible versions of slashes and backslashes; the result is always the same. The version of the webbrowser seems to be 11 (myWebbrowser.Version = "{11.0.18362.1139}"). I am working in Windows 10, VS 2019.
What can be wrong in this setup?
The path above is correct; if I copy it and paste into an external browser, the file is immediately opened. But the instance of WebBrowser does not want to react. I set a breakpoint in the last line of the snippet, and what I get there is that myWebbrowser.Url is null.
I was able to replicate this exact issue, it's because the property of the Url doesn't get actually set until the document has actually finished loading.
To resolve this issue, you must handle the DocumentCompleted event. You can do so for example:
string url = #"file:///C:MyHtml/hello.html";
myWebbrowser.DocumentCompleted += MyWebbrowser_DocumentCompleted;
myWebbrowser.Url = new Uri(url, UriKind.Absolute);
Create a new routine to handle the DocumentCompleted event:
private void MyWebbrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
string test = myWebbrowser.Url.ToString();
}
You can also get the Url from the WebBrowserDocumentCompletedEventArgs:
string testUrl = e.Url.ToString();
I am not sure exactly why when setting the Url and then checking it, it is null, I haven't found anything to explain why. My only guess is that it may be an invalid Url and or path, if navigation succeeds then that property is set.
Edit: upon looking at the source for WebBrowserDocumentCompleted, it does seem the Url property is only set in the DocumentCompleted, you can see more there.
Please note: you must register the DocumentCompleted event first before setting the Url property as when you do, it will navigate first and you will not receive the DocumentCompleted event.
I was able to find out why it did not want to function, at least I hope so. The "hello.html" file contained calls to jquery and THREE.js, while WebBroser seems not to support the latter. Therefore I did not see any content in the control. After I threw out THREE.js and inserted most simple HTML code, it worked just OK! Now I am busy trying to bring WebBrowser to support THREE.js (there exists a skeptical opinion about this, though).

"source()" not executing

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.

Missing datagrid boundcolumn in production

Using visual studio and C#, I recently added a new bound column to a data grid and modified the stored procedure to pull the extra field. When I debug it - it shows up fine and displays the data as I expect. When I publish the website and copy the files to the web server, the column is no longer there. It's a pretty straight forward setup. I know the file is being copied etc. What am I missing?
In addition to the comments added above, make sure your added field exists on Production Database.
If it throws an exception that your code swallows up, you would never know.
Example:
private bool SomeMethod(string cmdText) {
bool result = false;
try {
result = Query(cmdText);
} Catch (Exception) {
// Error occurred
}
}
If you had the code above and had an error, you would never know.

Failed to perform action on hidden control exception

I am trying to create a UI test in VS 2010 using IE 9 in IE 8 compatibilty mode however when trying to record an action recording many of the steps fail. Then when I manually code in the missing steps and try to fill in a log in form with a username and password I get an exception that says I have failed to perform an action on hidden control.
The UI Test code:
public void Recordedmethod()
{
BrowserWindow uILogInWindowsInternetWindow = this.UILogInWindowsInternetWindow;
HtmlHyperlink uILogInHyperlink = this.UILogInWindowsInternetWindow.UIHomePageDocument.UILogInHyperlink;
HtmlEdit uIUsernameEdit = this.UILogInWindowsInternetWindow.UILogInDocument1.UIUsernameEdit;
HtmlEdit uIPasswordEdit = this.UILogInWindowsInternetWindow.UILogInDocument1.UIPasswordEdit;
#endregion
// Go to web page 'http://localhost:15856/WebSite1/'
uILogInWindowsInternetWindow.NavigateToUrl(new System.Uri(this.RecordedMethodParams.UILogInWindowsInternetWindowUrl));
// Set flag to allow play back to continue if non-essential actions fail. (For example, if a mouse hover action fails.)
Playback.PlaybackSettings.ContinueOnError = true;
// Mouse hover 'Log In' link at (1, 1)
Mouse.Click(uILogInHyperlink);
// Reset flag to ensure that play back stops if there is an error.
Playback.PlaybackSettings.ContinueOnError = false;
// Type 'test' in 'Username:' text box
uIUsernameEdit.Text = this.RecordedMethodParams.UIUsernameEditText;
// The following element is no longer available: IE web control; Process Id [6320], window handle [3168166]
// Type '********' in 'Password:' text box
uIPasswordEdit.Password = this.RecordedMethodParams.UIPasswordEditPassword;
// The following element is no longer available: IE web control; Process Id [6320], window handle [3168166]
}
This is an issue linked to an Internet Explorer patch that was released in September.
KB2870699
This affects VS2010 and VS2012.
Microsoft released a patch that corrects the issue for VS2012 (and I've confirmed that it fixed the issue for me).
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
Currently the only workaround for VS2010 is to uninstall the patch (KB2870699); however, as with any sort of security patch you'll want to consider carefully whether pulling it is safe to do given your situation.
EDIT: This was not a fun bug for me to deal with. I had just upgraded to VS2012 from VS2010 and all of a sudden I found none of my previously functioning CodedUI tests working. I assumed it was an issue with VS2012 and after banging my head against the wall for the better part of a day I found out it was an issue with a patch. It was just my luck that I upgraded to 2012 at the same time the patch had been installed on my system. Good times!
There is actually an updated for VS 2012 to fix this issue
http://blogs.msdn.com/b/visualstudioalm/archive/2013/09/17/coded-ui-mtm-issues-on-internet-explorer-with-kb2870699.aspx
Hope this helps!
I was having the same problem with my coded ui test. It's an issue with VS-2012 i guess, i tried every update (installing/uninstalling them and everything..) nothing worked.
I tried VS-2013 Ultimate and it worked.
You can use exception handling to capture the error while still not having the test failed.
The test is failing because at the time it performs click action, the control is hidden.
try
{
//your code goes here
}
catch(FailedToPerformActionOnHiddenControlException e)
{
Console.WriteLine(e.Message);
}

Selenium chrome driver click() method not always clicking on elements

I am writing integration tests in c# and when I use the click() method on certain elements inside a dialog box nothing happens and I get no errors. It will click some of the elements inside the dialog but not others. I thought if it wasn't selecting them properly then it would throw and exception but it runs smooth and says test passed even though it never actually clicked the button. The dialog box is an iframe.
I thought maybe it was trying to click a button that wasn't display yet or enabled so I added this before the click() call:
_driver.SwitchTo().Frame(_frameElement);
_wait.Until(d =>
{
var shippingInfoButton = d.FindElement(By.CssSelector("input[title ='Info']"));
return shippingInfoButton.Displayed && shippingInfoButton.Enabled;
});
var infoButton = _driver.FindElement(By.CssSelector("input[title ='Info']"));
ScrollToElement(infoButton);
infoButton.Click();
again this runs with no thrown exceptions so I'm assuming it has found the element and it is both displayed and enabled.
Let me know if you need any more info. Thanks
I can't explain why the selenium driver .click() method won't fire on some elements in the page but not others, but I did find a solution.
Using IJavaScriptExecutor you can click the element using javascript instead and in my case it worked.
Here is the code to run the IJavaScriptExecutor and below is my whole method.
//IJavaScriptExecutor
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", infoButton);
//my whole method for clicking the button and returning the page object
public ShippingMethodDetailsPageObject SelectShippingMethodInfo()
{
_driver.SwitchTo().Frame(_frameElement);
_wait.Until(d =>
{
var shippingInfoButton = d.FindElement(By.CssSelector("input[title='Info']"));
return shippingInfoButton.Displayed && shippingInfoButton.Enabled;
});
var infoButton = _driver.FindElement(By.CssSelector("input[title ='Info']"));
IJavaScriptExecutor js = _driver as IJavaScriptExecutor;
js.ExecuteScript("arguments[0].click();", infoButton);
_driver.SwitchTo().DefaultContent();
return new ShippingMethodDetailsPageObject(_driver, false);
}
I ran into a similar problem. If it's the same problem there's a fault in the ChromeDriver it can't click certain elements because of surrounding divs etc. Bit lame really.
A simple fix is to send the Enter key e.g. element.SendKeys(Keys.Enter). Seems to work across all browsers.
I have some tests that works in Firefox all the times, and in Chrome it drove me mad, because sometimes it passed successfully, and sometimes the ".click" didn't work and it would fail the test.
Took a long time to notice it, but the reason was: I used to sometimes minimize the browser to 80% to be able to see the browser along side my IDE. it appears that the ".click" doesn't work when I did it.
At least for me this was the issue

Categories