NullReferenceException during .exe run, but not during debug - c#

During the construction of my Window LoginSystem, a NullReferenceException is being thrown only when running the application through the .exe.
While debugging, everything works perfectly fine however.
Code which calls the LoginSystem window:
LoginSystem ls = new LoginSystem();
ls.Show();
Where I've found the problem to be in my LoginSystem class:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
Login.con = new SqlConnection(ConfigurationManager.ConnectionStrings["thuisDB"].ConnectionString);
...
}
Just in case you're wondering:
public class Login
{
public static SqlConnection con = null;
...
}
Link to stack trace:
HERE
PS: This line (Login.con = new SqlConnection(....) is the first time Login.con gets called, as the only code using that static var are in a class which LoginSystem is supposed to make.
EDIT: This question is NOT about me asking what a NullRef is or how to fix it, it was merely a single event where I didn't know why it was being thrown & didn't know how to debug it.

ConnectionStrings["thuisDB"] will be null if you are running the .exe in a folder where it can't find the configuration file.
Look for something like MyProgram.exe.config and make sure that is in the same folder as your executable file.

Related

Read Settings from Dependent Project in C#

I just want to start by saying that I've done a lot of research but couldn't find an answer, hence the post.
I'm adding user settings functionality to my app which works as a plugin inside a common off the shelf program for architecture (called Autodesk Revit). The main project (let's call it MainProj) has several dependencies including a project that handles logging and usage (let's call it Loggers). I created a Settings file inside the Loggers project with the goal to have users change the logging level from Error to Debug when there are issues so I can ask them to make the change and send me the log.
The issue I'm facing is that when I change the log level directly inside the config file and re-run the command from within Revit, the change doesn't get translated into the log, as if the log level is somehow compiled during design and is never changed.
I actually tried to reproduce the problem in a simpler way and created a little console program and I'm facing the same issue. Below is the code from the Loggers project.
namespace Loggers
{
public static class Logger
{
public static string RunMe()
{
if (Properties.Settings.Default.LogMode == "Debug") { return "DEBUG"; }
else return "NOTHING";
}
}
}
I then changed the LogMode property from Debug to anything else in the config file but the console kept on returning DEBUG.
static void Main(string[] args)
{
Console.WriteLine(Logger.RunMe());
Console.Read();
}
I also tried changing the setting from user to application and editing its value in the config file and re-running the command but the outcome was the same.
Any help would be very much appreciated. I've been stuck on this for a while. Thank you.
Thanks to #BurnsBA, the link you shared had comments saying that the user.config lives in a different folder and it's not created until the user changes a setting. This made me understand that there wasn't a point in manually editing the app.config and expect the settings to work.
I then did some testing by creating a simple form with a checkbox linked to the Property I wanted to change and the user.config file gets created straight after I call the Save() method on the Properties.
private void btnOK_Click(object sender, EventArgs e)
{
if (chkDebugMode.Checked == true)
Loggers.Properties.Settings.Default.LogMode = "Debug";
else Loggers.Properties.Settings.Default.LogMode = "Error";
Loggers.Properties.Settings.Default.Save();
Close();
}

Executing NUnit tests through a Windows Form application with NUnit Engine

I'm trying to execute NUnit tests through a Windows Form application with NUnit Engine, but I don't understand how to set the path for the DLL where my tests are (I have already included the DLL in the references). When I click a button, I want the tests to start; however, NUnit opens and then immediately closes without doing anything. Here's what I have:
namespace ATF.GUI
{
public partial class ATF_Main : Form
{
TestPackage package;
ITestEngine engine;
public ATF_Main()
{
InitializeComponent();
}
private void ATF_Main_Load(object sender, EventArgs e)
{
string path = Assembly.GetExecutingAssembly().Location;
package = new TestPackage(path);
package.AddSetting("Working Directory", Environment.CurrentDirectory);
// Prepare the engine
engine = TestEngineActivator.CreateInstance();
}
private void btnStartTests_Click(object sender, EventArgs e)
{
using (ITestRunner runner = engine.GetRunner(package))
{
// Execute the tests
XmlNode result = runner.Run(null, TestFilter.Empty);
}
}
I never got a real answer to this but I figured it out myself.
private void ATF_Main_Load(object sender, EventArgs e)
{
// Add reference to tests DLL and load it here by name
Assembly testAssembly = Assembly.Load("Program.Tests");
package = new TestPackage(testAssembly.Location);
package.AddSetting("Working Directory", Environment.CurrentDirectory);
}
You could also add the assembly locations to a List if you have multiple test assemblies.
You are setting the test assembly to be your gui assembly. Since it has no tests, NUnit finds nothing to do. I imagine it returns an error in the result.
Somehow, your application has to be given the path of the test assembly. This can be through a command-line or a dialog of some kind. You can look at the code for nunit3-console or nunit-gui to see how it is done.
Your idea of using a referenced assembly seems a bit odd for a packaged application. Your users will need to have the source and rebuild it each time, referencing the desired test assembly. Do you really want that?
In case you do, you will need to find some way to get at that reference. Hard to do if there is nothing constant that will always be in it.

Unknown exception at declaration and initalisation of a Class

The main Problem is completely different, please skip to the Edit
I have an exception of an unknown type which doesn't even get thrown properly. Following Code provides the Context:
MMDataAccess.InitDemoDB();
MMDataAccess.InitInternalDB();
MMDataAccess.InitMaintDB();
try
{
SQLiteToDBLib sqltdbl = new SQLiteToDBLib();
sqltdbl.WriteToSQLite();
}
catch(Exception ex)
{
string message = ex.Message;
}
These are the very first lines of my first Activity in my app. The first 3 lines belong to my very own implementation of an in-memory database and are behaving nicely. The problem rises with the next two lines inside the try-block. The declaration and initalistation of the sqltdbl variable never happens. The constructor of SQLiteToDBLib looks like this:
public SQLiteToDBLib()
{
msc = new MSConnection();
}
The MSConnection class doesn't even have a constructor (except for the default one of course).
As you can see i've tried to catch any exceptions, but without success. everything i can figure out is, that a exception is thrown because of the debugger going into the catch section while ignoring everything that has to do with "ex". Without breakpoints everything seems fine. Just without the call to WriteToSQLite which should create a .sqlite file on the external Memory.
What can I do to resolve this error? Is there anything i can catch except the default Exception?
Edit:
After some testing with commented code something interresting happened. I could step into commented code. Well not exactly the commented code, but the code that was there before my changes. Visual Studio somehow shows me the things, that are changed in the file, but is compiling the old code. Up to now i tried to rebuild, clean and build the project in various combinations, unload and reload the project, Restart Visual Studio and restart Windows. Nothing has changed so far. I Will now proceed to create a new .cs File With the exact same Code. I'm working with VS 2013 Community
add static constructor to your SQLiteToDBLib class and perform all static objects initialization in it:
static SQLiteToDBLib()
{
// initialize static members here
}
If this doesn't give you a clue, try enabling CLRE exceptions-break in visual-studio:
DEBUG
Exceptions
Check the 'Common Language Runtime Exceptions' option (under the 'Thrown' column)
Press OK
Restart your app and try again

SpicIE Hostinstance null

I've been working on an IE9 plugin using the .net4 version of SpicIE. On my development machine, everything works great. While testing on a deployment machine, I keep getting a NullReferenceException when attempting HostInstance.BrowserRef.Navigate(URL). I added some logging and it is being reported as null on both machines, but it works without issue on the dev machine. I know at one time it worked on the deployment one and have no idea what might have broken it.
Relevant code follows:
From the plugin base:
public class KB_Toolbar : SpicIE.Host
{
...
public static KB_Toolbar HostInstance;
public KB_Toolbar() : base()
{
HostInstance = this;
}
public static void OpenURL(string URL)
{
if (HostInstance != null)
HostInstance.BrowserRef.Navigate(URL);
}
}
From the toolbar class:
private void MenuClick(object sender, EventArgs e)
{
var URL = vURL[(int)((ToolStripDropDownItem)sender).Tag];
KB_Toolbar.OpenURL(URL);
}
If I leave the HostInstance != null check there, it does not execute the next line on either machine. If I remove it, it executes with no problem on the dev, and throws a NRE on the deployment. I've tried a number of cheap hacks to work around it with no luck. I can't for the life of me figure out what is going on here, especially that it DOES work on the dev machine WHILE supposedly being null.
Any assistance would be greatly appreciated!
Solved it. The answer was a missing /codebase switch in the regasm command.

uncatchable exception from unreachable code

I run into a very strange problem in my C# 2.0 WinForms app and I'm not even sure if its worth asking SO, because the problem occurs in a strange setup and I don't think that you could reproduce it without my sources, but I'm totally out of ideas.
I have a Form with a TreeView on the left and an ListView on the right. The TreeView shows all available files and subfolders from a specific folder(which contains documents i need for my app). If a Folder is selected the ListView shows all files and subfolders from the selected folder. At startup I populate the TreeView form the folder and after that I select the first TreeNode by code(in my case it's an folder). After that the Content of the TreeView looks like this:
-folder
-file1
-file2
Selecting the folder triggers the AfterSelecedEvent of the TreeView. Because a folder was selected I populate the ListView using the following methode:
private void fillOverview(FAFolder folder)
{
lv_overview.Items.Clear();
ListViewItem item;
foreach (FAFile file in folder.sortedContent)
{
if (file is FAFolder)
{
item = new ListViewItem(file.Name, "Folder"); //exception got thrown here
}
else
{
item = new ListViewItem(file.Name, file.Name);
}
item.Tag = file;
lv_overview.Items.Add(item);
}
}
As you can see there is no subfolder, so the line item = new ListViewItem(file.Name, "Folder"); should never be touched in this setup, but every now and then a NullReferenceException got thrown. If I wrap this line with try/catch the exception got thrown inside the catch block. I tried checking everything if it's null or not, but ther were no nullreferences. Or if I add a MessageBox right before this line the exceptions got still thrown and no MessageBoxpops up. This brings me to the conclusion that the execption stacktrace is wrong and/or this exceptions comes from an other Thread or something like that.
I'm a very optimistic person and I know how clever the SO community can be, but I don't think that anybody can point out what the problem is. So what i'm actuallly looking for are hints and advices how i could find and debug the cause of this strange behavior.
EDIT:
internal abstract class FAFile
{
internal string Name;
internal readonly FAFolder Parent;
internal FAFile(FAFolder parent)
{
this.Parent = parent;
}
}
internal sealed class FAFolder : FAFile
{
internal readonly IDictionary<string, FAFile> Content = new Dictionary<string, FAFile>();
internal FAFolder(FAFolder parent, string name) : base(parent)
{
this.Name = name;
}
}
internal sealed class FADocument : FAFile
{
public readonly string Path;
public FADocument(FAFolder parent, string path): base(parent)
{
this.Path = path;
this.Name = System.IO.Path.GetFileNameWithoutExtension(path);
}
}
Have you tried an null check on folder.sortedContent ?
Usually ReSharper will prompt me that something like that should have a null check.
If you want to be sure, add the following line to your code, above the foreach loop:
if (folder.sortedContent == null) throw new Exception("It was null, dangit!");
On the line you mention:
item = new ListViewItem(file.Name, "Folder")
the only thing that can cause a NullReferenceException is if file is null (unless the exception is being thrown from within the ListViewItem constructor itself).
You don't provide the code for folder.sortedContent so I can't tell - but is it possible that one of the elements in this collection might be null under certain circumstances?
If the ListViewItem constructor is throwing the exception then you will need to use Reflector to look at the code, or download the reference source.
A co-worker of mine just found the answer(probably). I use a Thread to load the ImageList to the ListView from the HDD and this thread sometimes freezes and if i assign a ImageKey it fails. That's no answer why the exception is uncatchable or why it's thrown at this (unreachable) line. But i strongly belive that this is the cause of the problem.
That line is not unreachable. Because FAFolder derives from FAFile, it is possible that 'file is FAFolder' will return true.
However, that would imply that file is not null, unless it is being changed by another thread.
Edit: file can't be changed by another thread as it's a local reference. Can you provide a stack trace for the exception? This one has me intrigued now.
I just cannot help wondering is the FAFolder contain a '.' or a '..' for parent and subdirectory? and the sorting breaks as a result?
This answer will be edited accordingly if this turns out to be untrue?
Hope this helps,
Best regards,
Tom.
Is this exception reproducible on demand?
Can you show the the stack trace of the exception?
What other threads are running when the exception is thrown?
In general, there are two ways to debug this type of stuff. The first way is so-called "scientific" debugging:
Devise a theory to explain observed behaviour.
Devise an experiment to test the theory.
Run the experiment and observe the results.
The second way is by stripping-down the actual code piece by piece until the exception is no longer triggered. Then you have a significant clue for further investigation.
This brings me to the conclusion that the execption stacktrace is wrong....
It's usually easier to start by assuming that the problem is in your own code.

Categories