Settings.Designer file and Staticness - c#

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.

Related

c# - hiding a connection in a .dll

I'm new to c#, but I need to change an existing program, by merely changing the connection string. The idea is to redirect the connection to a test database environment. I've found that the code uses a dll to create a connection to the server. I used Jetbrains Dotpeek to look inside the dll, but I could only see methods and functions, but nowhere could I see the connection detail to change it.
What ways are there of encrypting a connection string? Are there special files used generally for this, that I can look for?
To give more elaborate information:
In the normal code in the cs file, there is for example this:
var result = new LibSqlQuery(Db.ABC.ConnectionString, sql);
return result;
and Db is a method in a dll defined as following:
public static class Db
{
private static Dictionary<string, LibDbConnection> _connections = new Dictionary<string, LibDbConnection>();
private static LibDbConnection GetConnection(string connectionName)
{
lock (Db._connections)
{
if (!Db._connections.ContainsKey(connectionName))
Db._connections.Add(connectionName, new LibDbConnection(connectionName));
}
return Db._connections[connectionName];
}
public static LibDbConnection ABC => Db.GetConnection("conABC");
public static LibDbConnection CDE => Db.GetConnection("conCDE");
}
where ABC and CDE are database environments.
I found another config file, which had the connections. This can be closed now. Thank you.

C# Hjson returns null after deserialization

I have a hjson file like this that I want to deserialize and work with:
{
"TestConfig": {
"SecondConfig": {
"ConnectionString": "Integrated Security = true; Data Source = dataPseudo; Initial Catalog = catalogPseudo; Connect Timeout = 180",
"SpecificationPseudo": "pseudo",
"NumberOfHintsPseudo": 300
},
"ThirdConfig": "pseudo"
}... // more hjson coming here.
I load it with the HjsonValue.Load method like this:
private static Foo convertJson()
{
var loadedValue = HjsonValue.Load("hjsonFile.hjson").ToString();
return new JsonSerializer<Foo>().DeserializeFromString(loadedValue);
// another failed method: return JsonConvert.DeserializeObject<Foo>(loadedValue);
// A third failed method: return JsonConvert.DeserializeObject<Dictionary<string, Foo>>(loadedValue);
}
I think my problem is in the 2 c#-coded lines, but can't figure what. Am I deserializing wrong or what seems to be the problem? I suspect that it's because it is a nested json, but can't find a way to deserialize it. Trying to use dictionary as it is a answer in a other stack-question, but it didn't work for me.
Note: The first and second tried return method don't return any errors, but they just return a nullreferenceexception since "SecondConfig" and "ThirdConfig" both are null..
Update (with help from er-sho): removed the "root"-element from the hjson (TestConfig), which solved the problem.
Removing "TestConfig" from the hjson fixed it, since it's root and the class I am working with.

Exception thrown while setting 0.0 decimal value to c# Decimal object

I have this class:
public class PlaylistMessageBindingModel
{
//Other non-important fields
public Decimal Duration { get; set; }
}
I am instantiating an object of this class and read values out of a database with a data reader:
while (innerReader.Read())
{
var playlistMsg = new PlaylistMessageBindingModel();
playlistMsg.Duration = (Decimal)reader["size_time"];
}
But when it hits the .Duration line of code, it throws an Exception:
An exception of type 'System.Exception' occurred in MyDll.dll but was not handled in user code
Additional information: size_time
The value column in the database is decimal(6, 3). I'm guessing it might have to do with the fact that the value coming out of the database is 0.000, but if that is the case, I'm not sure how to deal with that. I'd appreciate any observations.
Have you tried this?
while (innerReader.Read())
{
var playlistMsg = new PlaylistMessageBindingModel();
playlistMsg.Duration = reader.GetDecimal["size_time"];
}
Also very useful SQL Server Data Type Mappings
This is what happens when you stare at your own code for too long...
I failed to notice a subtle difference in my reader objects. Above this section of code, I have instantiated a reader called reader. Further down the code, I instantiated innerReader. So when I was trying to set the duration, I have while (innerReader.Read()) and inside that code block I'm trying playlistMsg.Duration = (Decimal)reader["size_time"]; but it should be (Decimal)innerReader["size_time"]. After changing the code, I got my intended result.

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.

Type initialization exception

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

Categories