Error in property accessor - c#-4.0

We recently placed an MVC application in production that sometimes gives us unhandled errors that we cannot reproduce in our development environment. The web app keeps crashing on the same line but the inner exception gives different error messages. The line where it crashes is when a particular property is accessed (property accessor). But the inner exception gives us the following different errors:
Unable to cast object of type 'System.Int32' to type 'System.String'.
Index was outside the bounds of the array.
There is already an open DataReader associated with this Command which must be closed first.
We have a large number of users so I'm assuming that this has to do with concurrency or some type of thread problem? Can someone guide me in the right direction on how to find the problem?
By the way, it crashes always when accessing the same property. Sometimes it works other times it fails.
Here is the code for the accessor:
public string DepartementSelectionne
{
get
{
if (string.IsNullOrEmpty(m_departementSelectionne) == true)
if (ListeDepartements.FirstOrDefault() != null)
m_departementSelectionne = ListeDepartements.First().CodeDepartement;
return m_departementSelectionne;
}
set
{
m_departementSelectionne = value;
}
}
Thanks!

Related

SwiftUI. Access to properties from background

This problem is driving me crazy.
In principle the code below works correctly.
The authenticator that is called is a class defined in its own module (Authenticator.swift).
The code below is a method of the viewModel that conforms ObservableObject protocol.
The observed properties self.error and self.goToHomeView are properties published from the viewModel.
The authenticator method authenticates with FaceID. If authentication succeeds, error is nil, then the observed variable goToHomeView is set to true to switch to the Home view.
If error is not nil, then self.error is assigned which is of type LocalizedError and that triggers an alert in the view.
The problem is that an annoying warning appears all the time saying: "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.”
I would like to know if anyone knows a technically valid way to modify values from the main thread from a secondary thread running in background.
Task {
await authenticator.authenticate { error in
if let error = error {
self.error = error
} else {
self.goToHomeView = true
}
}
}

Azure Search - Error

When trying to index documents we are getting this error:
{"Token PropertyName in state ArrayStart would result in an invalid JSON object. Path 'value[0]'."}
Our code for indexing using the .NET library is :
using (var indexClient = new SearchIndexClient(searchServiceName, indexName, new SearchCredentials(apiKey)))
{
indexClient.Documents.Index(IndexBatch.Create(IndexAction.Create(documents.Select(doc => IndexAction.Create(doc)))));
}
Does anyone know why this error occurs?
The issue is because of an extra call to IndexAction.Create. If you change your indexing code to this, it will work:
indexClient.Documents.Index(IndexBatch.Create(documents.Select(doc => IndexAction.Create(doc))));
The compiler didn't catch this because IndexBatch.Create has a params argument that can take any number of IndexAction<T> for any type T. In this case, T was a collection, which is not supported (documents must be objects, not collections).
The programming model for creating batches and actions is changing substantially in the 1.0.0-preview release of the SDK. It will be more type-safe so that mistakes like this are more likely to be caught at compile-time.

Mongoose idGetter error: Cannot set property '_id' of null

I am getting the following error from the Mongoose idGetter function. Can anyone shed some light on what may be causing it?
return this.$__._id = null == this._id
^
TypeError: Cannot set property '_id' of null
at model.idGetter (e:\Users\Christine\test\mvt\node_modules\mongoose\lib\schema.js:98:23)
The error situation involves multiple client requests performing document removes (on different documents in the same collection), on a database being accessed over internet (i.e. slow response time). The failure happens on accessing the id of one of the removed documents. There appears to be a small timing window in which it occurs - everything I've tried to debug it causes the problem to 'go away'.
Outline of the application code:
Details.findOneAndRemove({ _id : remove_id}, afterRemove);
function afterRemove(err, removedDoc){
if (!err && removedDoc){
OtherDetails.find({ _id: some_id}, afterFind);
}
function afterFind(err, foundDoc){
if (!err && foundDoc){
// next line causes exception
if (foundDoc.details_id === removedDoc.id) { // do stuff };
}
}
}
Do you have an id property defined on the document that you have removed?
If not, you should probably want to compare foundDoc.details_id with removedDoc._id
Below is the source code for the idGetter function in the mongoose code base:
function idGetter () {
if (this.$__._id) {
return this.$__._id;
}
return this.$__._id = null == this._id
? null
: String(this._id);
}
As I understand, I think that the idGetter is specifically aimed at ObjectId types, hence that exception.
You could also try to add an id property on the document if it does not yet exist to see if it continues to throw the same exception.
fwiw: it is possible that the problem was related to using 32-bit Node on 64-bit Windows (8.1). After installing 64-bit Node, I could not reproduce the problem.
Unsatisfying level of certainty, but I thought I would share in case anyone else gets a similar problem or can shed light on whether this might really have been the cause.

TypeInitializationException/ArgumentException when referencing initialized variable

I just received an exception when I try to reference a static variable in another class, which is also statically initialized. This worked before, and for some reason it fails now. The only changes I made were resetting Visual Studio (2010) to its default setting, which I can't imagine to be the reason for this. Any other code I added didn't touch any of the affected parts either.
This is my code
WinForms class 'MainForm':
partial class MainForm : Form
{
// ...
private RefClass convMan;
private Dictionary<EnumType, string> LogNames = RefClass.LogNames;
// ...
public MainForm() { .... }
}
Referenced class 'RefClass':
class RefClass
{
// ...
public enum EnumType { TypeOne = 0, TypeTwo = 1, TypeThree = 2 };
public static Dictionary<EnumType, string> LogNames = new Dictionary<EnumType, string>()
{
{ EnumType.TypeOne, "Text0" },
{ EnumType.TypeTwo, "Text1" },
{ EnumTypy.TypeThree, "Text2" }
};
}
The error I get now is (translated from German):
An unhandled exception of type "System.TypeInitializationException" occurred.
Additional information: The type initializer for "RefClass" threw an exception.
which has the InnerException
System.ArgumentException
So, as far as I'm concerned, my static dictionary should be initialized once it gets accessed, thus when my Form class references it. I tried debugging to see if the static dictionary is initialized before it gets referenced in the Form class, which is not the case. Also, when I stop at a breakpoint for the reference line, the variable LogNames is null.
I'm really confused as to why this happens, it all worked before.
I found my error, the exceptions I got were quite misleading though. It was a problem with a different dictionary than the one I referenced. It probably didn't get initialized in the first place because something before that failed (If someone can clear this up, please feel free to do so!). Basically what I did wrong was using a two-directional dictionary and adding a value twice. This should normally produce a normal exception, but since it was done statically it got wrapped into a TypeInitializationException. I had a deeper look into the exact stacktrace of the inner exception and found where the exception originated from. Maybe this helps someone in the future...
I had a simular issue getting the same exception. Found that my static constructor for my utility class was generating the exception. Took some time locating since the description of the exception was misleading.
As #Yeehaw mentioned, it appears that the exception gets wrapped, so the common denominator here I would say is that the class/object is static.

DynamicMethod code unverifiable in .Net 4.0 (found ref 'this' pointer... expected ref '<>f__AnonymousType1`)

Was using this solution to convert anonymous types to dictionaries using reflection.emit. Was working fine until I changed to .Net 4.0 from 3.5.
Now, I'm getting the "System.Security.VerificationException: Operation could destabilize the runtime." error.
Converted the anonymously loaded dynamic method to one hosted in a dynamic assembly, saved it, then ran peverify.exe on it to find out what was wrong.
Got: [IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D][found ref ('this' ptr) 'MyDynamicType'][expected ref '<>f__AnonymousType1`3[System.String,System.Int32,System.Byte]'] Unexpected type on the stac
k.
[IL]: Error: [DynamicAssemblyExample.dll : MyDynamicType::MyMethod][offs
et 0x0000000D] Method is not visible.
2 Error(s) Verifying DynamicAssemblyExample.dll
The code:
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldarg_0);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
Is there a way to derefence the pointer to the actual property? Or do I have to cast it somehow? Any pointers?
Regards!
Sorry guys, made a mistake, since the actual dynamic method creates a delegate type that acts on the instance of the anonymous (or non-anonymous) type, the Ldarg_0 code is looking for a something that is not there in this debug implementation.
So I, changed it to OpCodes.Ldnull.
var attributes = BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy;
foreach (PropertyInfo property in itemType.GetProperties(attributes).Where(info => info.CanRead))
{
// load Dictionary (prepare for call later)
methIL.Emit(OpCodes.Ldloc_0);
// load key, i.e. name of the property
methIL.Emit(OpCodes.Ldstr, property.Name);
// load value of property to stack
methIL.Emit(OpCodes.Ldnull);
//methIL.Emit(OpCodes.Castclass, itemType);
methIL.EmitCall(OpCodes.Callvirt, property.GetGetMethod(), null);
// perform boxing if necessary
if (property.PropertyType.IsValueType)
{
methIL.Emit(OpCodes.Box, property.PropertyType);
}
// stack at this point
// 1. string or null (value)
// 2. string (key)
// 3. dictionary
// ready to call dict.Add(key, value)
methIL.EmitCall(OpCodes.Callvirt, addMethod, null);
}
But I still get a method not visible error after peverifying it. Is it that get methods for properties of anonymous types are not visible via reflection?
Just a suggestion, have you tried to rewrite the code that emits IL to actually write to the dictionary - i.e. no Reflection.Emit ? My bet is that the generated IL is not proper in some way, not the code that accesses the anonymous type.

Resources