Why is this error happening? Any idea ?!
(I insert data from a form to the database by using a sqldatasource)
I've set the ShowWarningOnFailure="true" and the error window tells me this.
{
serviceResponse: {
success: false,
message: "System.Exception: Sequence contains more than one matching element ---> System.InvalidOperationException: Sequence contains more than one matching element\r\n at System.Linq.Enumerable.Single[TSource](IEnumerable1 source, Func2 predicate)\r\n at Ext.Net.Store.InsertCallback(Int32 recordsAffected, Exception exception) in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 1053\r\n at System.Web.UI.DataSourceView.Insert(IDictionary values, DataSourceViewOperationCallback callback)\r\n at Ext.Net.Store.MakeInsertes(IDataSource ds, JArray data) in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 982\r\n at Ext.Net.Store.MakeChanges() in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 839\r\n at Ext.Net.Store.DoSaving(String action, String jsonData, JToken parameters) in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 793\r\n --- End of inner exception stack trace ---\r\n at Ext.Net.Store.DoSaving(String action, String jsonData, JToken parameters) in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 806\r\n at Ext.Net.Store.RaiseAjaxPostBackEvent(String eventArgument) in C:\Users\Geoffrey McGill\Documents\Visual Studio 2010\Projects\Ext.NET\v2\Ext.Net\Ext\Data\Store.cs:line 1131",
data:
}
}
There is no System.Linq.Enumerable.Single call in the Store.c file.
So, Ext.NET should not produce this exception.
Is this exception thrown on inserting a new record, right?
If yes I would try to check the SqlDataSource's InsertCommand as it is, i.e. without an Ext.NET context.
Also there is a question where a similar exception was discussed.
Sequence contains more than one element
Looks like the problem is that you are calling the extension method Single() somewhere, and the predicate you are passing results in more than one match. Single() can only return one entity, so it throws an exception.
Related
I need to rewrite an old web service because the team that supported the old one no longer wants to support it with their new tool. So I'm rewriting it using ASP.NET Core WebAPI and EF Core 3.1.
The majority of the logic for the service is stuck in stored procedures written years ago. Nothing super complex, but don't really think it's a good idea to start rewriting everything.
The problem is that EF Core's support for stored procs seems lacking at best. I got one working using Database.ExecuteSqlRaw which returns the results as output parameters, but I'm having trouble with another that returns the results as a dataset. (Actually two, but let's not get ahead of ourselves... I've commented it so it's only returning one right now.)
The (current) problem with the .FromSqlRaw query is that it doesn't appear to be querying the database at all when I watch for it in XEvent Profiler. (SQL Server 2016.)
Here's the code I'm using to call the proc:
var bundle_id = new SqlParameter("bundle_id", bundleID) { Direction = ParameterDirection.Input };
var result = this.BundleUserGuideDetails.FromSqlRaw("EXEC dbo.p_fetch_user_guide_details #bundle_id", bundle_id);
var deets = result.FirstOrDefault<BundleUserGuideDetail>();
I did create a DBSet for it in the DBContext class:
public DbSet<BundleUserGuideDetail> BundleUserGuideDetails { get; set; }
And since it's a keyless type I've got this per Microsoft's Keyless Entity guide:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<BundleUserGuideDetail>(eb =>
{
eb.HasNoKey();
});
}
The model I created has all the same field names as the data being returned as well.
So why is the DB not even getting called for this?
EDIT: Forgot to write that the call to FirstOrDefault is throwing "System.InvalidOperationException: 'Sequence contains no elements'"
EDIT: Here is the full exception text:
System.InvalidOperationException: Sequence contains no elements
at System.Linq.ThrowHelper.ThrowNoElementsException()
at System.Linq.Enumerable.Aggregate[TSource](IEnumerable`1 source, Func`3 func)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.EntityMaterializerInjectingExpressionVisitor.ProcessEntityShaper(EntityShaperExpression entityShaperExpression)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.EntityMaterializerInjectingExpressionVisitor.VisitExtension(Expression extensionExpression)
at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Linq.Expressions.ExpressionVisitor.VisitBinary(BinaryExpression node)
at System.Linq.Expressions.BinaryExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Dynamic.Utils.ExpressionVisitorUtils.VisitBlockExpressions(ExpressionVisitor visitor, BlockExpression block)
at System.Linq.Expressions.ExpressionVisitor.VisitBlock(BlockExpression node)
at System.Linq.Expressions.BlockExpression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at System.Linq.Expressions.ExpressionVisitor.VisitLambda[T](Expression`1 node)
at System.Linq.Expressions.Expression`1.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.EntityMaterializerInjectingExpressionVisitor.Inject(Expression expression)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.InjectEntityMaterializers(Expression expression)
at Microsoft.EntityFrameworkCore.Query.RelationalShapedQueryCompilingExpressionVisitor.VisitShapedQueryExpression(ShapedQueryExpression shapedQueryExpression)
at Microsoft.EntityFrameworkCore.Query.ShapedQueryCompilingExpressionVisitor.VisitExtension(Expression extensionExpression)
at System.Linq.Expressions.Expression.Accept(ExpressionVisitor visitor)
at System.Linq.Expressions.ExpressionVisitor.Visit(Expression node)
at Microsoft.EntityFrameworkCore.Query.QueryCompilationContext.CreateQueryExecutor[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Storage.Database.CompileQuery[TResult](Expression query, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.CompileQueryCore[TResult](IDatabase database, Expression query, IModel model, Boolean async)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass9_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQueryCore[TFunc](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.CompiledQueryCache.GetOrAddQuery[TResult](Object cacheKey, Func`1 compiler)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.FirstOrDefault[TSource](IQueryable`1 source)
at MandTBank.BBFB.BPS.BPSWebAPI.Data.BundleSystemContext.FetchUserGuideDetails(String bundleID) in C:\Users\tdevmcr\Source\Workspaces\BBFB\NeedsAssessmentSystem\Main\Sourcecode\BBFB NAS - I3 - BundleUserGuide Service\MandTBank.BBFB.BPS.BPSWebAPI\Data\BundleSystemContext.cs:line 65
Turns out I had made a simple mistake, and failed to make the fields in the model public
The exception being thrown certainly doesn't make that obvious though...
I also needed to add AsEnumerable() after the FromSqlRaw call for it to work, as per this question: Include with FromSqlRaw and stored procedure in EF Core 3.1
I have a list of location codes that are a concatenation of BUILDING/ROOM i.e. "BLD23223019" where the first 5 characters are the building. I split building code from the string and display it in one list for the user to select which then takes the user to a list of rooms within that building. So I pass the building code to the Room list to filter the rooms and I do this like:
_realm = Realm.GetInstance(RealmInstance.RealmPath);
try
{
_locations = _realm.All<Building>().Where(x => x.BuildingCode.Contains(_room.RoomCode)).ToList();
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
ListViewLocations.ItemsSource = _locations;
but it doesn't give me any results, instead I get a target invocation error and the inner exception is "This object belongs to a closed realm." This also happens if I use "Equals(_room.RoomCode). I can't understand why the realm would be closed just from the above code.
I'm new to Realm so maybe I'm doing something wrong, if anyone can point me in the right direction it would be much appreciated.
This is the inner exception that the above code throws
at Realms.NativeException.ThrowIfNecessary (System.Func`2[T,TResult]
overrider) [0x0000a] in
/Users/realm/jenkins/workspace/realm_realm-dotnet_PR-1775/Realm/Realm/Native/NativeException.cs:57
at Realms.MarshalHelpers.GetString
(Realms.MarshalHelpers+NativeCollectionGetter getter) [0x0002b] in
/Users/realm/jenkins/workspace/realm_realm-dotnet_PR-1775/Realm/Realm/MarshalHelpers.cs:55
at Realms.ObjectHandle.GetString (System.IntPtr propertyIndex)
[0x00013] in
/Users/realm/jenkins/workspace/realm_realm-dotnet_PR-1775/Realm/Realm/Handles/ObjectHandle.cs:258
at Realms.RealmObject.GetStringValue (System.String propertyName)
[0x00000] in
/Users/realm/jenkins/workspace/realm_realm-dotnet_PR-1775/Realm/Realm/RealmObject.cs:139
at AsssetMan.Models.Buildings.get_BuildingCode () [0x00014] in
D:\Projects\AssetManRealm\AssetMan\AssetMan\Models\Buildings.cs:8
at (wrapper managed-to-native)
System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
at System.Reflection.MonoMethod.Invoke (System.Object obj,
System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder
binder, System.Object[] parameters, System.Globalization.CultureInfo
culture) [0x00032] in <43dbbdc147f2482093d8409abb04c233>:0
Thanks to #mjwills I've figured it out. the first comment using var bob in the linq extension worked if I used a literal. That meant there had to be a problem with the variable or the way I was passing the BuildingCode to the RoomCode page. The message "Realm is closed", or something to that effect, had me stumped at first then I remembered that the Realm objects are "Live" and as I was closing the _realm on the previous page, the building object I was passing to the RoomCode page was no longer available. So I new'd up a building object and when the building was selected from the list of buildings, copied the building code into it and passed that to the lookup for the RoomCode so the BuildingCode was still available after the Realm is closed.
Thanks #mjwills.
I have json data that is being compressed using ServiceStacks's inbuilt ToOptimizedResult method. This has been working fine for a while now, recently though, when the data to be returned is high (50k+) rows etc. I get the Out Memory Error below:
System.OutOfMemoryException: Exception of type 'System.OutOfMemoryException' was thrown.
at System.Text.StringBuilder.ToString()
at ServiceStack.Text.JsonSerializer.SerializeToString(Object value, Type type)
at ServiceStack.Text.JsonSerializer.SerializeToString[T](T value)
at ServiceStack.ServiceModel.Serialization.JsonDataContractSerializer.SerializeToString[T](T obj)
at ServiceStack.Common.Web.HttpResponseFilter.SerializeToString(IRequestContext requestContext, Object response)
at ServiceStack.ServiceHost.RequestContextExtensions.ToOptimizedResult[T](IRequestContext requestContext, T dto)
at MyService.post(PostDDSReportDataSourceData Input) in MyService.vb:line 452
at lambda_method(Closure , Object , Object )
at ServiceStack.ServiceHost.ServiceRunner`1.Execute(IRequestContext requestContext, Object instance, TRequest request)
The weird part is that the exact same data is serialized ok on Dev, the error only appears in Production. The main solutions I've seen online recommend disabling buffering, however I've only seen examples that disable buffering entirely for the entire application. How can I disable buffering just for that one request?
Figured it out myself eventually. In the method simply turn off buffering like this:
CType(MyBase.Response.OriginalResponse, System.Web.HttpResponse).BufferOutput = False
As an addendum to the above solution, you will still receive this error if you store the json string in a variable. Only call the ToOptimized method when returning the result. Turning off buffering won't make a difference if you store the serialized string in a variable.
I eventually ended up serializing my list to a file, then sending the file down by returning an HttpResult below:
Dim PathToTheSerializedJsonFile as String = "C:\SomeFile.Json"
Using fl As StreamWriter = File.CreateText(PathToTheSerializedJsonFile)
Dim Serr As New Newtonsoft.Json.JsonSerializer()
Serr.Serialize(fl, Input)
End Using
Return New HttpResult(New FileInfo(PathToTheSerializedJsonFile),asAttachment:=True)
Ultimately I am trying to address the same issue that is referenced in Loading any MVC page fails with the error “An item with the same key has already been added.” and An item with the same key has already been added. A duplicate of the first link is All MVC pages fail with the message an item with the same key has already been added but it has some additional pertinent information, confirming that it only effects MVC pages, while webforms and other aspects of the application that deal with appSettings continue to work without error.
I have now seen this four times in production and it has not been seen in any other environment (dev, test, UAT). I have closely examined and debugged through the source code of System.Web.WebPages and the relevant sections of the MVC stack but did not run into anything that stood out. This problem has persisted through a migration from MVC3 to MVC4, and the latest changeset from aspnetwebstack.codeplex.com does not appear to address this issue.
A quick summary of the issue:
Every MVC page is affected and completely unusable
WebForms and other aspects of the application that use appSettings continue to work just fine
Only an appPool restart will correct this issue
At least once and as referenced in an article above, this has happened after a regular time interval recycle of the appPool by IIS
This has happened during both low and high volume traffic periods
This has happened on multiple production servers, but the issue only affects a single server at any given time, as other servers continue serving MVC pages
The offending line of code is var items = new Lazy<Dictionary<object, object>>(() => appSettings.AllKeys.ToDictionary(key => key, key => (object)appSettings[key], comparer));, but it occurs when the lazy initialization is forced by requesting a value from items The appSettings variable is from System.Web.WebConfigurationManager.AppSettings which is a direct static reference to System.Configuration.ConfigurationManager.AppSettings. So I beleive the line is equivalent to: var items = new Lazy<Dictionary<object, object>>(() => System.Configuration.ConfigurationManager.AppSettings.AllKeys.ToDictionary(key => key, key => (object)appSettings[key], comparer));
I rarely suspect framework issues, but it appears that appSettings has two distinct keys that are the same (not the same as a NameValueCollection supporting multiple values for the same key). The comparer being used in the MVC stack is the StringComparer.OrdinalIgnoreCase which appears to match what is used by the configuration system. If this is a framework issue, the MVC stack appears to be very unforgiving when it forces the NameValueColleciton into a dictionary using the ToDictionary() extension method. I believe using appSettings.AllKeys.Distinct().ToDictionary(...) would probably allow the MVC stack to operate normally as the rest of the application does and be oblivious to the possibility of duplicate keys. This unforgiving nature appears to also contribute to the issue described in NullReferenceException in WebConfigScopeDictionary
Server stack trace:
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at System.Web.WebPages.Scope.WebConfigScopeDictionary.<>c__DisplayClass4.<.ctor>b__0()
at System.Lazy`1.CreateValue()
Exception rethrown at [0]:
at System.Lazy`1.get_Value()
at System.Web.WebPages.Scope.WebConfigScopeDictionary.TryGetValue(Object key, Object& value)
at System.Web.Mvc.ViewContext.ScopeGet[TValue](IDictionary`2 scope, String name, TValue defaultValue)
at System.Web.Mvc.ViewContext.ScopeCache..ctor(IDictionary`2 scope)
at System.Web.Mvc.ViewContext.ScopeCache.Get(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.ViewContext.GetClientValidationEnabled(IDictionary`2 scope, HttpContextBase httpContext)
at System.Web.Mvc.Html.FormExtensions.FormHelper(HtmlHelper htmlHelper, String formAction, FormMethod method, IDictionary`2 htmlAttributes)
at ASP._Page_Areas_Client_Views_Equipment_Index_cshtml.Execute()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__22(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__18(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__3(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass4.<MakeVoidDelegate>b__3(IAsyncResult ar)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
To separate my question from the questions already asked, I will ask has anyone seen the configuration system be corrupted with multiple duplicate keys or where a NameValueCollection.AllKeys returns two identical keys? I know you can have multiple keys defined in the config file, but the last key wins, and that scenario does not reproduce this issue.
Although I am not alone in seeing this behavior multiple times, there are relatively few posts describing this issue, so I also suspect that it might be a configuration/environmental issue, but again, servers will run for months without experiencing this issue, and an appPool restart immediately corrects the problem.
I have mitigated this issue by forcing an appPool restart if a server starts seeing this error, but management is not happy about this "hacky" solution because some user will still experience an error.
Help?!?!?
EDIT:
Here is a contrived, cheezy test that can reproduce the scenario, but doesn't help in solving the issue. It happens during approx. 20% of the test runs. The code will blow up for other threading reasons, but it is the "Same key has already been added" error that is of interest.
[TestClass]
public class UnitTest1
{
readonly NameValueCollection _nameValueCollection = new NameValueCollection();
private Lazy<Dictionary<object, object>> _items;
[TestMethod]
public void ReproduceSameKeyHasAlreadyBeenAdded()
{
Thread[] threads = new Thread[1000];
for (int i = 0; i < 1000; i++)
{
ThreadStart threadStart = AddEntry;
Thread thread = new Thread(threadStart);
threads[i] = thread;
}
foreach (var thread in threads)
thread.Start();
Thread.Sleep(100);
_items = new Lazy<Dictionary<object, object>>(() => _nameValueCollection.AllKeys.ToDictionary(key => key, key => (object)_nameValueCollection[key], ScopeStorageComparer.Instance));
object value;
_items.Value.TryGetValue("4", out value); // approx. 20% of time, blows up here with mentioned error
Assert.IsTrue(value != null);
}
private int _counter;
private void AddEntry()
{
_counter++;
try
{ // add a bunch of even keys, every other one a duplicate
_nameValueCollection.Add((_counter%2) == 0 ? _counter.ToString() : (_counter + 1).ToString(), "some value");
}
catch {}
}
}
StackTrace:
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Linq.Enumerable.ToDictionary[TSource,TKey,TElement](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
at UnitTestProject1.ReproduceSameKeyHasAlreadyBeenAdded.<TestMethod1>b__0() in c:\Git\AspNetWebStack\aspnetwebstack\UnitTestProject1\UnitTest1.cs:line 37
at System.Lazy`1.CreateValue()
We came across this same issue and finally tracked it down to dynamic updating of the ConfigurationManager.AppSettings collection. I have posted a full answer here: https://stackoverflow.com/a/17415830/2423407
Are you absolutely positive the error is occurring on the line where you are initializing items and not the line on which items is being used to add to some other dictionary (Static I would presume).
To me the most likely way this would occur is if the code was executed in parallel (by two concurrent users) and the second one executing causing the exception.
As a general workaround I usually initialize a strongly typed class with all configuration parameters as an auto-start provider (and add some strongly-typed type checking of the values as well, such as checking that an int is an int, etc) to avoid run-time errors.
This has the double benefit of loading these at warmup, not when the users want the info (better response performance) and thread-safety is supposedly guaranteed with them as well.
See if that doesn't fix your issue. If you do not want to do that I would at the very least try to execute the code that is failing for you with multiple threats hitting it, as my guess would be that you will see your error occur fairly reliably.
I have a site which runs in ASP.NET 3.5, NHibernate 2.2 and Sprint .NET for Dependency Injection. On our test server a rather strange error occurrs, and also almost everytime there are multiple users online. After the problem has occurred, this error is displayed for every user and every request they make - until you do an IISRESET. Then it is all ok again.
Here's the exception:
'count' must be non-negative.
Parameter name: count
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count
Source Error:
[No relevant source lines]
Source File: c:\Windows\Microsoft.NET\Framework64\v2.0.50727\Temporary ASP.NET Files\root\4bf9aa39\6dcf5fc6\App_Web_z9ifuy6t.6.cs Line: 0
Stack Trace:
[ArgumentOutOfRangeException: 'count' must be non-negative.
Parameter name: count]
System.String.CtorCharCount(Char c, Int32 count) +10082288
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +3612
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) +75
Spring.Objects.Factory.Support.DefaultListableObjectFactory.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +365
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +136
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type) +66
[ActivationException: Activation error occured while trying to get instance of type InfoTextService, key ""]
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key) in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:57
Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance() in c:\Home\Chris\Projects\CommonServiceLocator\main\Microsoft.Practices.ServiceLocation\ServiceLocatorImplBase.cs:90
OurProjectsNamespace.Infrastructure.ObjectLocator.LocateService() +86
This is indeed a very wierd error. When you look at the source of the AbstractObjectFactory.GetObjectInternal you will see the following structure:
[ThreadStatic]
private int nestingCount;
protected object GetObjectInternal(...)
{
const int INDENT = 3;
bool hasErrors = false;
try
{
nestingCount++;
if (log.IsDebugEnabled)
{
log.Debug("msg" +
new String(' ', nestingCount * INDENT));
}
// More code: Calls self recursively.
}
catch
{
nestingCount--;
hasErrors = true;
if (log.IsErrorEnabled)
{
log.Error("msg" +
new String(' ', nestingCount * INDENT));
}
}
finally
{
if (!hasErrors)
{
nestingCount--;
if (log.IsDebugEnabled)
{
log.Debug("msg" +
new String(' ', nestingCount * INDENT));
}
}
}
}
The exception you are seeing must be thrown by one of the three new String(' ', nestingCount * INDENT) calls. That particular string constructor call throws when the supplied value is negative. Because INDENT is a const, nestingCount must have a negative value in that case. nestingCount is a thread-static variable. Thread-static variables are always initialized with their default value (0 in this case) and can't be influenced by other threads. Further more, nestingCount is never used outside this method.
Because nestingCount is thread-static and only used in that method, it is hard to imagine a scenario were nestingCount can get negative. Perhaps in the case of an asynchronous (ThreadAbort) exception, but even this I find hard to imagine. Other option is that the thread-static variable is changed by someone else using reflection.
But the big question is: how to solve this?
Solution:
There's only one thing I can think of and that is reconfigure log4net in a way that debug information isn't logged. When disallowing debug information, the string(char, int) constructor will probably never get called again, which will hide the problem. Not very pretty, but possibly effective. This might work, because the AbstractObjectFactory logs using the log variable that is initialized as follows:
this.log = LogManager.GetLogger(this.GetType());
You can do this by globally disabling the writing of debug information in log4net, or –when you think this is overkill- by configuring log4net to disable debug info for the type Spring.Objects.Factory.Support.DefaultListableObjectFactory (the instance that is actually causes the exception).
Good luck.
I have seen this error occur when a database column is mapped to more than one property. A typical case is when a foreign key column is mapped to a property and to collection. A second or third pair of eyes on the config files helps spot these.
One twist with this is that it occurs for all users. Do you have a persistent object that is stored in application state?
In my case, this error occurred after some time during performance testing. It starts fine and after some time this error pops up.
Turns out it was caused by a totally unrelated [ThreadLocal] variable I used in my code. I replaced it with a method parameter and now it works fine.