Unknown exception at declaration and initalisation of a Class - c#

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

Related

Instantiating a .NET class with a reference to a dll causes FileNotFoundException

I've added as reference PDFSharp classes for a project. When I tried to use a method in a class that includes PDFSharp libraries I get a FileNotFoundException that states I'm missing the referenced (PDFSharp) file (while I can assure you the dll file is there).
So I've tried adding and readding and changing the dll version, but still without success. So I switched to PDFClown, a similar purpose library, but the error is the same: FileNotFoundException at runtime.
The exception is thrown even before the method is executed.
Calling method (where the exception is thrown):
//method call: here the debugger stops at the breakpoint
ReportUtils.CreateFile(tempDirectoryPath ecc);
Called method:
using org.pdfclown.documents;
using org.pdfclown.documents.contents.composition;
using org.pdfclown.documents.contents.fonts;
using clownFiles = org.pdfclown.files;
class ReportUtils
{
public static void CreateFile(/*parameters*/)
{
//the debugger never enter here: the exception is thrown before
string filename = Settings.ReportFileName + String.Format("{0:yyyyMMddHHmmssffff}", DateTime.Now);
//ecc
}
//...
Why is this exception showing up? Am I doing something wrong adding the references?
I could reproduce your issue by setting the option Copy Local on my library to false. Please, make sure this boolean is set to true..

Assembly Location Changes in Runtime

I'm running coded ui automation and defined a method attribute called [ExternalDataSource()] to read a document (csv, xml...) and parse the data into some dictionaries. I'll copy it here so you can have a better insight:
[System.AttributeUsage(System.AttributeTargets.Method)]
public class ExternalDataSource : System.Attribute
{
public ExternalDataSource(string filename)
{
DirectoryInfo di = new DirectoryInfo(Assembly.GetExecutingAssembly().Location);
string file = Path.Combine(Path.GetDirectoryName(di.FullName), filename);
try
{
code
}
catch (Exception)
{
throw new UITestException("Cannot load data source document");
}
}
}
In it I try to access Assembly.GetExecutingAssembly().Location to get a file that is copied to the TestResult/Out folder. I assigned this attribute to only one TestMethod() in the whole application and while debugging, I found out that the application enters the attribute's c'tor twice. Both times the Location is different. Once it's from the bin/Debug folder, the other time it's from the TestResults/Out folder. Two questions:
Why does the debugger enter that attribute twice if I call it only once in my application?
Why does the location of the same assembly change?
Well it seems nobody had an answer, but while debugging a run from the command line using mstest.exe with the vs2012 JIT Debugger i found out a strange thing:
When putting a System.Diagnostics.Debugger.Break() in the class where this attribute is the jitter was called from MSTest.exe but when this breakpoint was in the testmethod decorated with this attribute, QTAgent32.exe was called. I had implemented a singleton class to handle my parameters, and while it was populated in ExternalDataSource in this attribute by MSTest, when entering QTAgent32 (the test) it was empty.
The solution that worked for me was just to initialize that Singleton with the data on [TestInitialize()].
Hope this helps somebody.

"The invocation of the constructor on type 'TestWPF.MainWindow' that matches the specified binding constraints threw an exception."- how to fix this?

I'm working with WPF. When I'm trying to declare SQLiteConnection in the code, the problem arises-
The invocation of the constructor on type 'TestWPF.MainWindow' that matches the specified binding constraints threw an exception.
InnerException: Make sure that the file is a valid .NET Framework assembly.
can anyone tell me, how to fix it?
If you click on View Detail... from the exception window you can look at the InnerException. Expand that node and you will see exactly what went wrong.
In my specific case, I was getting this because I had a few of my referencing assemblies mismatched between x64 and x86. Apparently I was binding to something that needed to be loaded by the runtime.
I mention this here as a reminder to check your build configurations if you've looked everywhere else!
I fixed the problem by adding the below content in app.config,
<configuration> <startup useLegacyV2RuntimeActivationPolicy="true" /> </configuration>
I found this via a community addition by user FCAA below the article "
Troubleshooting Exceptions: System.IO.FileLoadException" on MSDN.
I got the same error and, after wasting about 2 hours with it, found that it is my SQL Server service that's not running. Not sure if this can ever help someone, but it did solve my problem to just start the service.
The mentioned exeption is quite generic and you can receive it, for instance, when code fails in the constructor. I had a case of an IO exception that showed up with a similar text. Stepping into the code may provide hints to fix this that may not be obvious otherwise.
I got it in when I specified the FrameworkPropertyMetadata of a DependencyProperty with a default value
the defaultValue was
new AdressRecord { Name = "<new>", Adress = "?" }
i replaced with
default(AddressRecord)
and vs2015 ate it
public static readonly DependencyProperty AdressRecordsProperty =
DependencyProperty.Register("AdressRecords",
typeof(ObservableCollection<AdressRecord>),
typeof(PageViewModel),
new FrameworkPropertyMetadata(
default(AdressRecord),//This noes not work: new AdressRecord { Name = "<new>", Adress = "?" },
OnAdressRecordsChanged));
I ran into this issue and it was caused because my startup application was built as any CPU but I was referencing a project that was built as x64. Setting the startup to build x64 resolved the issue.
In VS2015 I was able to see the specific code causing this problem once I turned on 'Enable Just My Code' in the Debugging Options under Tools -> Options.
I had this error in another part of code which has to do with my application resources.
This was fixed after explicitly setting the ResourcePath folder in my App.config file
I had the same problem. i could make it work by renaming the name of App1.config to App.config. I tried all other methods but the solution for me was to change the default name (for me it was App1.config) of the config file to App.config. I shared this because someone may get help by this small modification.
My problem was about the interface. I fixed it by deleting the Betternet folder that is located at C:\ProgramData.
Hidden Items/Folders must be shown in order to be able to view the folder.
With Visual Studio it will sometimes not show anything in the exception details or even have them, running the diagnostic tool however can easily pinpoint what is wrong.
Try Adding "Integreted Security = True" in Connection String.
It worked for me.
In my case it happened in a code-first WPF project. The cause was model changes after restoring a backup, and the error was not being handled appropriately. "The model backing the 'MyDataContext' context has changed since the database was created." Update-Database sorted it out.
I had to change the target .Net framework from 4.5.2 to 4.
my issue was regular System.IndexOutOfRangeException error in my own code,
but received this weird error because my code was called inside:
public MainWindow()
{
InitializeComponent();
// my code with error
}
same issue, if call it inside:
private void Window_Initialized(object sender, EventArgs e)
{
// my code with error
}
Fixed, if I call my code inside:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// my code with error
}
Then i get correct error message for IndexOutOfRangeException in my code.

Code Contract : ccrewrite exited with code -1?

I'm new to code contracts. I downloaded the latest build of code contract project (1.4.40314.1) and started to implement it in my project. When i enabled 'Runtume Checking' through Code Contracts Tab in VS2010, i got this Error
Error 1 The command ""C:\Program Files (x86)\Microsoft\Contracts\Bin\ccrewrite" "#Application1ccrewrite.rsp"" exited with code -1.
everytime i build the project. Plz help.
Now it's a major problem for me.
Every project using code contracts is showing same error in VS2010 Errors window and 'Application1ccrewrite.rsp' not found in output window, but it is there.
I tried out everything. I installed both versions (Pro, Std) but the problem persist. Plz help !
I had this problem as well. In my case the problem was that ccrewrite cannot work with files in a network folder but requires the project to be on your local hard disk.
I had this problem. The Assembly name and Default namespace of the class library that causes the problem had the same name as an existing DLL in the destination folder. I had been refactoring my code and whilst the namespaces in the CS files had all be changed to namespace2 the default namespace in the properties file was still namespace1
When I corrected this the files all built successfully...
Sometimes you can get this when your solution path is too long, especially with many projects.
Try moving to c:\temp and building it, it might fix it (although of course, this might not be a solution if you need it in the folder it currently is).
This bug I noticed in earlier CC versions and may now be fixed.
I don't know if you had the same problem as me, but I also saw this error. In my case, I had a method with a switch statement, and depending on the branch taken, different requirements applied:
static ITransaction CreateTransaction(
String transType,
MyType1 parm1,
/* Other params unimportant to this example */
String parm5)
{
switch (transType) {
case Transaction.Type.SOME_TRANSFER:
Contract.Requires<ArgumentNullException>(parm1.Account != null, "Account cannot be null.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm5), "parm5 cannot be null or empty.");
// Create instance
return someInst;
case Transaction.Type.SOME_OTHER_TRANSFER:
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Type), "Type cannot be null or empty.");
Contract.Requires<ArgumentException>(!String.IsNullOrWhiteSpace(parm1.Number), "Number cannot be null or empty.");
// Create instance
return someInst;
/* Other cases */
default:
throw new ApplicationException("Invalid or unknown transaction type provided.");
}
}
This was giving me the error you noted in the Errors List when I tried to build. In the output window, I was getting this:
EXEC : Reference Assembly Generator
warning : Something is wrong with
contract number 1 in the method
'TerraCognita.LoanExpress.Domain.Loan.CreateLoanTransaction'
AsmMeta failed with uncaught
exception: Operation is not valid due
to the current state of the object.
I pushed each branch into a method of its own, making Contract.Requires the first lines of code in each method, and I no longer had a compilation problem. It appears that Contract.Requires must be the first lines of code in a method - which makes sense, since they are intended to be used to define pre-conditions.
Hope this helps.
The solution is to put the pre and pos conditions in the first lines. The ccrewrite does not accept that pre and post conditions are below command lines.

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