Type initialization exception - c#

I created imageHolder class:
public class ImageHolder : Image<Bgr, Byte>
{
private String imagePath;
public ImageHolder(String path):base(path)
{
this.imagePath = path;
}
public String imgPathProperty
{
get
{ return imagePath; }
set
{ imagePath = value; }
}
}
I create instance of the class and initialize it,like this:
private ImageHolder originalImageHolder;
originalImageHolder = new ImageHolder(openFileDialog.FileName);
In runtime i get this exception:
The type initializer for 'Emgu.CV.CvInvoke' threw an exception.
Here is Solution Explorer window:
Any idea why i get this exception and how can i fix it?
Thank you in advance.

The TypeInitializationException (the exception that you are seeing) is thrown whenever a static constructor throws an exception, or whenever you attempt to access a class where the static constructor threw an exception - its InnerException property is the property that contains the detail of the exception that was actualy thrown - this is the exception that you need to investigate.
In this case from your screenshot the problem appears to be that the DLL "opencv_core240.dll" could not be found. This could be for a number of reasons
The DLL couldn't be found
One of the dependencies of the DLL could not be found
The DLL was in the incorrect image format (32 bit as opposed to 64 bit)
I'd suggest that you take a look at this question to see if any of the suggestions on there help you.

Checking this field did the trick for me. Under Project→ Properties→ Build (Main/Startup project)

I solved the problem by reinstalling MSVCRT 9.0 SP1 x86

Related

How do I debug a "DependencyProperty.UnserValue" exception in my WPF/MVVM application?

I have a C#/.Net/WPF/MVVM application.
The application runs fine when running through VS 2015.
When I run the application standalone (on a different machine),
I get the following exception at startup:
An unhandled exception of type "System.InvalidOperationException"
occurred in WindowsBase.dll
Additional information "{DependencyProperty.UnserValue} is not a valid
value for property "TopLevelItemTemplateKey"
What is really going on?
How do I debug this?
Thanks
Are you returning directly your value on the get of your Dependency? The good manner would be to test if the variable is null before returning it here an example with an ObservableCollection:
public ObservableCollection<YourObject> _ocYourObject;
public ObservableCollection<YourObject> ocYourObject{
get {
if (_ocYourObject == null) {
_ocYourObject = new ObservableCollection<YourObject>();
}
return _ocYourObject;
}
set {
if (_ocYourObject!= value) {
_ocYourObject= value;
PropertyChanged(this, new PropertyChangedEventArgs(nameof(ocYourObject)));
}
}
}

An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll. Value cannot be null

I know this has been asked before, but I don't fully understand the answers given as I'm very new to programming.
I've tried adding a null check before the line of code, however, I'm not sure what to do with a "Directory" once it's been checked, if that makes any sense?
public class Config
{
public Config()
{
_random = new Random(DateTime.Now.Millisecond);
_dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,
AppDomain.CurrentDomain.RelativeSearchPath,
"TradeAgent",
"Configs");
if (!Directory.Exists(_dir))
{
Directory.CreateDirectory(_dir);
}
}
The error is being thrown on the "_dir = Path.Combine" line.
Can someone break this down for me like I'm 5?
EDIT: I just noticed below this a bit it says:
private string _dir = null;
No idea how to fix this, but maybe that's the problem?
EDIT2: When changing private string _dir = null; to something else like "abc" instead of "null", I no longer get the nullpoint error, although obviously I get a new error saying "the name abc does not exist in the current context".
Again, I don't know how to fix this, but it does seem that _dir is the problem.

System.Runtime.InteropServices.SEHException in UnityEngine.dll

I am importing unity3D project for windows phone 8. and adding few lines of code which interact the c# code to the event changing handler of Object(SphereScript) in unity3D.
var sphereScript = UnityEngine.Object.FindObjectOfType<SphereScript>();
sphereScript.SphereStateChanged += sphereScript_SphereStateChanged;
sphereScript_SphereStateChanged(sphereScript.IsSphereMoving);
The project compiled fine with no errors but when it runs on phone it gives an error on line
UnityEngine.Object.FindObjectOfType<SphereScript>();
An exception of type 'System.Runtime.InteropServices.SEHException' occurred in UnityEngine.DLL but was not handled in user code. i don't know why this error occurs. but first time when i started the project it asked me to locate the file name UnityEngineObject.cs. Where can i find this file or how can i solve the problem. Thanks.
Url for complete code http://docs.unity3d.com/Manual/wp8-unity-interaction.html
Exception details:
System.Runtime.InteropServices.SEHException was unhandled by user code
HResult=-2147467259
Message=External component has thrown an exception.
Source=UnityEngine
ErrorCode=-2147467259
StackTrace:
at UnityEngine.Internal.$Calli.Invoke38(Int32 arg0, IntPtr method)
at UnityEngine.Object.FindObjectsOfType(Type type)
at UnityEngine.Object.FindObjectOfType(Type type)
at UnityEngine.Object.FindObjectOfType[T]()
at UnityXamlInteractionExample.MainPage.Unity_Loaded()
InnerException:
in Unity 5x i had equal the problem.
So try this:
In script SphereScript.cs:
re-write this:
public event Action<bool> SphereStateChanged;
to this:
public static event Action<bool> SphereStateChanged = delegate { };
next, in Visual Studio after build project un-comment these parts of code:
UnityApp.SetLoadedCallback(() => { Dispatcher.BeginInvoke(Unity_Loaded); });
private void Unity_Loaded() { }
now insert into private void Unity_Loaded() this:
ShareScript.SphereStateChanged += SphereStateChanged;
and finally add this:
void SphereStateChanged(bool currentSpehreState)
{
Dispatcher.BeginInvoke(() =>
{
SphereStateTextBlock.Text = currentSpehreState ? "Spehre is moving" : "Sphere is stopped";
});
}
Good luck, bye :)

Why Class keeps throwing 'The type initializer for 'MyClass' threw an exception.'

I copied and pasted the methods out of a class from one project and pasted it all into a class in another project. I have searched around and nothing has come up that pertains exactly or close to why in this case it would be throwing the error.
I made sure that the namespace matched the project, and it keeps throwing
{"The type initializer for 'MyClass' threw an exception."}
So then I created another class and left it empty, and when I created an object of it, the page loaded without a problem.
As soon as I add..
private static string strCn = ConfigurationManager.ConnectionStrings["DDB"].ConnectionString;
private static SqlConnection cn = new SqlConnection(strCn);
it threw the error, but if I comment that out and just add a public variable and a private one and a method
public int mynum = 1;
private static int num2 = 2;
it runs fine, but any other time I have used
private static string strCn = ConfigurationManager.ConnectionStrings["DDB"].ConnectionString;
private static SqlConnection cn = new SqlConnection(strCn);
in any of my classes it runs fine. So what would be causing the issue? I even manually entered in the private sqlconnection and strCn it would cause an error. To no avail.
My guess based on the limited is that the line
private static string strCn = ConfigurationManager.ConnectionStrings["DDB"].ConnectionString;
is throwing the exception.
That could happen if there were no connection string named "DDB", so ConnectionStrings["DDB"] returns null, which you then try to dereference with .ConnectionString.
Try moving the initialization of strCn into a static constructor, breaking out the initialization steps, and stepping through in the debugger.
public static
{ // Set a breakpoint here, and see what value is assigned to cfg.
var cfg = ConfigurationManager.ConnectionStrings["DDB"];
strCn = cfg.ConnectionString;
}
If this turns out to be the issue, I suggest you keep the static constructor so that you can verify that the connection string has a correct value and do appropriate error handling if not.
That is because the initialization of the static variables in your class failed.
Read here about the problem and solution.
In fact the problem is that the order of initialization can't always be determined correctly, which means that it is possible that the SqlConnection cn is initialized first, which will cause a NullReferenceException because the strCn isn't filled in yet.
ConnectionStringSettingsCollection.Item(string) returns null if no connection with the given name is found, so
ConfigurationManager.ConnectionStrings["DDB"].ConnectionString;
throws a NullReferenceException.
You need to fix your configuration to ensure the connection string exists.

Settings.Designer file and Staticness

I have a DAL class library that is included in my program as a DLL. The below line is from the DAL to initialize the connection.
DataSet ds = new DataSet("table");
SqlConnection cnn = new SqlConnection(Settings.CMOSQLConn);
When I run this I get the below error:
An unhandled exception of type 'System.StackOverflowException' occurred in CMO.DAL.dll
The below is in the Settings.Designer.cs file and it is where it shows the error on the get call:
[global::System.Configuration.ApplicationScopedSettingAttribute()]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Configuration.SpecialSettingAttribute(global::System.Configuration.SpecialSetting.ConnectionString)]
[global::System.Configuration.DefaultSettingValueAttribute("Data Source=WWCSTAGE;Initial Catalog=CMO;Persist Security Info=True;User ID=CMOWe" +
"bService;Password=ecivreSbeWOMC")]
public static string CMOSQLConn {
get {
return (CMOSQLConn);
}
}
Anyone have any ideas of what to look for? Is it because the connection string is stored in the dll instead of my Main App? I am really stuck on this and will greatly appreciate any help!
EDIT 1
I tried Greg's suggestion below:
public static string CMOSQLConn {
get {
return (Settings.CMOSQLConn);
}
}
And I still get the same error... Any more thoughts? Thanks so far!
EDIT 2
So I followed the suggestion of regenerating the settings file below and now my setting file looks like this -->
public string CMOSQLConn {
get {
return ((string)(this["CMOSQLConn"]));
}
}
Unfortunately this won't compile now as wherever I have this statement -->
SqlConnection cnn = new SqlConnection(Settings.CMOSQLConn);
I now get this error -->
Error 1 An object reference is required for the non-static field, method, or property 'CMO.DAL.Properties.Settings.CMOSQLConn.get' B:\MyDocs\tmpPATRIOT\Projects\VS2008\DisConnectDAL\CMO.DAL\SupportWorker.cs 13 51 CMO.DAL
Is this what I should expect?
Thanks!
This is a classic c# properties mistake. Double check what you're returning in your property-- you're returning the property itself! Name resolution will prefer the local name over an external name. You're getting a stack overflow because you hit infinite recursion when CMOSQLConn.get calls CMOSQLConn.get.
Consider returning Settings.CMOSQLConn. The extra specification should clearly indicate the correct location of your connection string.
EDIT:
Whoops! I didn't notice that you pasted that from your Settings designer file. The infinite recursion is clearly happening, but I'm afraid you'll have to do some more investigation to track down why it's happening in this case.
It appears that your designer file was generated incorrectly (!!!). On VS2008, my settings designer getters look something like:
public bool Foo{
get {
return ((bool)(this["Foo"]));
}
// ...
}
You may need to do something similar. IE:
public string CMOSQLConn
get {
return ((string)(this["CMOSQLConn"]));
}
// ...
}
Try changing your code to this:
public static string CMOSQLConn {
get {
return ((string)(this["CMOSQLConn"]));
}
}
Hmm.. Good point in the comments. I just looked in my VS settings file and copied and pasted without thinking. Something isn't right with your settings file... It shouldn't be creating a static property for the settings.

Categories