Linq- Random Item with same key has already been added Error - c#

I am getting error "An item with the same key has already been added." I get this error randomly when many user try to access the same page on site in production at the same time.
In the code docid is passed and relevant help is displayed to user. As each user is viewing the same page so same ID is passed for all users. There is no insert operation in this call
Stack trace and souce code of mentioned line is given as follows
public string DocDescription(int docid)
{
DocumentRepository _Documentrepository = new DocumentRepository();
return _Documentrepository.GetDocDescription(docid);
}
}
public string GetDocDescription(int DocID)
{
if (DocID != 0)
return db.sysDocuments.SingleOrDefault(p => p.DocumentID == DocID).Description==null?"No Description Available":db.sysDocuments.SingleOrDefault(p => p.DocumentID == DocID).Description;
else
return "No Description Available";
}
Stack Trace excerpt:
System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.Web.HttpException (0x80004005): Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerAsyncWrapper'. ---> System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Data.Linq.DataContext.GetTable(MetaTable metaTable)
at System.Data.Linq.DataContext.GetTable[TEntity]()
at UserManagement.Models.DocumentRepository.GetDocDescription(Int32 DocID) in D:\Myproj\UserManagement\UserManagement\Models\DocumnetRepository.cs:line 109
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at Castle.Proxies.ControllerActionInvokerProxy.InvokeActionMethod_callback(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at Castle.Proxies.Invocations.ControllerActionInvoker_InvokeActionMethod.InvokeMethodOnTarget()
at Castle.DynamicProxy.AbstractInvocation.Proceed()
at Glimpse.Net.Interceptor.InvokeActionMethodInterceptor.Intercept(IInvocation invocation)
at Castle.DynamicProxy.AbstractInvocation.Proceed()

From your code and comments, I get that you store db context in a static variable. This is generally a bad idea when working with entities.
DbContext is not thread safe. So, multiple users working with your site will cause such errors in context.
The general suggestion for working with context is to prefer short lived context. So just create a new instance, when you need it, and then forget it. For the web sites, it is quite common to use inversion of control container like Unity, Castle.Winsdor etc, and configure it to return one instance per web request for your DbContext. This will give you enough performance, so all entities needed for the current request are cached, and will not cause threading issues at the same time.

See comment too, static members are application scoped variables thus they're sharing the same dictionary which can throw errors like this if multiple requests add the same key.

Related

Untracked Exception: Value cannot be null. Parameter name: headers

Problem
There's WCF connected to Silverlight. When it's time for the service to return args, it returns an error with the exception and no actual result that it should return.
Exception
Value cannot be null.
Parameter name: headers
There's no parameter named headers. I put emphasis on not having a field named headers in the model which the service returns.
Possible Solution which didn't work out
Checked every Any(), Where and Count() not used when it's null
Checked {get;} doesn't exist except when it's with set;
Traced whole of code and it didn't have any exception or null value
Checked whole of code to be in different try-catches
Checked Web.config and all of connection strings are right; .
I updated the service multiple times and checked its configuration
I couldn't remove defining query I wasn't allowed to
Stack Trace
at System.ServiceModel.AsyncResult.End[TAsyncResult](IAsyncResult result)
at System.ServiceModel.Channels.ServiceChannel.EndCall(String action, Object[] outs, IAsyncResult result)
at System.ServiceModel.ClientBase`1.ChannelBase`1.EndInvoke(String methodName, Object[] args, IAsyncResult result)
at UIE.SrvE.SrvEClient.SrvEClientChannel.EndGetSubmit(IAsyncResult result)
at UIE.SrvE.SrvEClient.UIE.SrvEngineer.ISrvE.EndGetSubmit(IAsyncResult result)
at UIE.SrvE.SrvEClient.OnEndGetSubmit(IAsyncResult result)
at System.ServiceModel.ClientBase`1.OnAsyncCallCompleted(IAsyncResult result)
There are so many questions about this exception like this one source but none of them is about headers.
Please, suggest to me any possible solutions.

LightInject Attempt to create a scoped instance without a current scope

I (noob to light inject mvc) am using LightInject MVC in my asp.mvc 4 app with great results except an occasional exception. Now I am seeing it in pre-production. The exception is: System.InvalidOperationException: Attempt to create a scoped instance without a current scope.
My app start code is:
var container = new LightInject.ServiceContainer();
container.RegisterControllers();
container.RegisterAssembly(typeof(AppDDD.RegisterMe).Assembly, () => new PerScopeLifetime());
... scoped registrations
container.EnableMvc();
I get the error with a stack trace like:
System.InvalidOperationException: An error occurred when trying to
create a controller of type 'MvcAPP.Controllers.HomeController'. Make
sure that the controller has a parameterless public constructor. --->
System.InvalidOperationException: Attempt to create a scoped instance
without a current scope. at
LightInject.PerScopeLifetime.GetInstance(Func1 createInstance, Scope
scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.<>c__DisplayClass40.<WrapAsFuncDelegate>b__3f()
at LightInject.PerRequestLifeTime.GetInstance(Func1 createInstance,
Scope scope) at DynamicMethod(Object[] ) at
LightInject.ServiceContainer.TryGetInstance(Type serviceType) at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) --- End of inner exception
stack trace --- at
System.Web.Mvc.DefaultControllerFactory.DefaultControllerActivator.Create(RequestContext
requestContext, Type controllerType) at
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext
requestContext, String controllerName) at
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase
httpContext, IController& controller, IControllerFactory& factory)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase
httpContext, AsyncCallback callback, Object state) at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
I have created a couple of small test ASP MVC projects to isolate the exception with no success.
The Controllers are scoped per instance, and all the objects with in each instance are designated PerScopeLifetime.
Is there a tweak I can make, or should I stop using PerScopeLifetime? I must have scoped lifetimes for my EF contexts.
The exception is thrown before my controllers finish constructing, so it appears.
I would like you to know that the issue has been resolved and getting the latest and greatest from NuGet should fix your problem.
Best regards
Bernhard Richter

ResolutionFailedException with Unity

I'm using Patterns and Practices' Unity to inject dependencies into my objects and have hit a weird (to me, anyway) issue. Here's my class definitions:
public class ImageManager : IImageManager
{
IImageFileManager fileManager;
public ImageManager(IImageFileManager fileMgr)
{
this.fileManager = fileMgr;
}
}
public class ImageFileManager : IImageFileManager
{
public ImageFileManager(string folder)
{
FileFolder = folder;
}
}
And here's the code to register my classes
container.RegisterInstance<MainWindowViewModel>(new MainWindowViewModel())
.RegisterType<IPieceImageManager, PieceImageManager>(
new InjectionConstructor(typeof(string)))
.RegisterType<IImageFileManager, ImageFileManager>()
.RegisterType<IImageManager, ImageManager>(
new InjectionConstructor(typeof(IImageFileManager)));
I originally resolved this in the code behind (I know, it defeats the purpose. Bear with me.) of the XAML file like this
IImageManager imageManager = MvvmViewModelLocator.Container.Resolve<IImageManager>(
new ParameterOverride("folder", "/images"));
And it worked. But I created a view model for my main view and when I copied the same line into it, I get an exception. Here are the two most inner exceptions:
InnerException: Microsoft.Practices.Unity.ResolutionFailedException
HResult=-2146233088
Message=Resolution of the dependency failed, type = "SwapPuzzleApp.Model.IImageManager", name = "(none)".
Exception occurred while: while resolving.
Exception is: InvalidOperationException - The type IImageManager does not have an accessible constructor.
At the time of the exception, the container was:
Resolving SwapPuzzleApp.Model.IImageManager,(none)
Source=Microsoft.Practices.Unity
TypeRequested=IImageManager
StackTrace:
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name, IEnumerable`1 resolverOverrides)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides)
at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve[T](IUnityContainer container, ResolverOverride[] overrides)
at SwapPuzzleApp.ViewModel.MainWindowViewModel..ctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MainWindowViewModel.cs:line 17
at SwapPuzzleApp.ViewModel.MvvmViewModelLocator..cctor() in c:\Users\Carole\Documents\Visual Studio 2012\Projects\SwapPuzzle\SwapPuzzle\ViewModel\MvvmViewModelLocator.cs:line 51
InnerException: System.InvalidOperationException
HResult=-2146233079
Message=The type IImageManager does not have an accessible constructor.
Source=Microsoft.Practices.Unity
StackTrace:
StackTrace:
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForNullExistingObject(IBuilderContext context)
at lambda_method(Closure , IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicBuildPlanGenerationContext.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides)
InnerException:
I'm not sure what the problem is, as ImageManager clearly has a public constructor. I thought it might be due to an invalid path, but if I concretely instantiate the object, everything works.
// this line has no problems
IImageManager imageManager = new ImageManager(new ImageFileManager("/images"));
I also wondered if I needed to pass in new InjectionConstructor(typeof(string)) when I register IImageManager, but it doesn't seem to help and why would it be needed now and not before? So I'm stumped. This is my first attempt at using Dependency Injection, so it's probably something basic. I'm just not seeing what, though.
Look very closely at the error message. Notice this part:
Message=The type IImageManager does not have an accessible constructor.
Notice the type name is IImageManager, not ImageManager. Somewhere along the line you lost your type mapping.
Your registration of FileImageManager has a problem as well, since you don't specify the folder parameter in the registration, so Unity has no idea what string to pass.
I was using the examples in this article as my guide. Either the examples in there are way too advanced for an introduction, or there's misinformation in that topic.
After consulting other sources (mainly PluarlSight), I came up with a much simpler and more logical solution.
container.RegisterInstance<TimerViewModel>(new TimerViewModel());
container.RegisterType<IPieceImageManager, PieceImageManager>();
container.RegisterType<IImageFileManager, ImageFileManager>
(new InjectionConstructor("/images"));
container.RegisterType<IImageManager, ImageManager>();
I ran into a similar issue with this error tied directly to a Mock (using automoq) that I was doing for an operation. In this case it turned out that because there were a number of member methods that get called with the object being mocked, that I had to define all of those in the automoq chain to get it to resolve properly
I realize this is an example in instance code, but it could occur in Moqs also. So if you read this and are wondering about an example related to Moqs, look into that first.

Response is not available in this context

I have problem. Locally everything works fine but in the production server it always throws exception 'Response is not available in this context'. What can be the problem? I've noticed that a lot of people experience this problem due to some changes of global.asax. Here is the code of global.asax, the part related to application start.
protected void Application_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
Application["SystemUser"] = TUser.GetUserByIdentifier("system").UID;
InitializeSolrInstances();
SearchIndexer.DoIndex();
StartRatingTimer();
SolrManager.RecalculateMostRequested();
}
private static void InitializeSolrInstances() {
SolrConfigurationManager.InitSolrConnection<OfferItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/offer");
SolrConfigurationManager.InitSolrConnection<SavedQueryItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/savedquery");
SolrConfigurationManager.InitSolrConnection<TopProductsPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topproducts");
SolrConfigurationManager.InitSolrConnection<TopSellersPresenter>(Resources.ApplicationResources.SolrServiceURL + "/topsellers");
SolrConfigurationManager.InitSolrConnection<MostRequestedItemPresenter>(Resources.ApplicationResources.SolrServiceURL + "/mostrequested");
SolrConfigurationManager.InitSolrConnection<MostRequestedQuery>(Resources.ApplicationResources.SolrServiceURL + "/requestedquery");
}
private void StartRatingTimer() {
_LastRatingRenewedTime = DateTime.Now;
DateTime CurrentTime = DateTime.Now;
DateTime StartTime = new DateTime(2011, 1, 1);
GlobalSettings.ReIndexMainSolrCores(StartTime, CurrentTime);
Timer OfferAndUserRatingRenewerTimer = new Timer() {
/*Timer interval for 24 hours*/
Interval = 24 * 60 * 60 * 1000, Enabled = true };
OfferAndUserRatingRenewerTimer.Elapsed += new ElapsedEventHandler(OfferAndUserRatingRenewerTimer_Elapsed);
}
public void OfferAndUserRatingRenewerTimer_Elapsed(Object Sender, ElapsedEventArgs e) {
GlobalSettings.ReIndexMainSolrCores(_LastRatingRenewedTime, e.SignalTime);
_LastRatingRenewedTime = e.SignalTime;
}
I do not use Response or Request properties of HttpContext at all. Neither in global asax itself, nor within the methods to be called. Help me.
That what it shows.
`
Server Error in '/' Application.
Response is not available in this context.
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.Web.HttpException: Response is not available in this context.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[HttpException (0x80004005): Response is not available in this context.]
System.Web.Util.HttpEncoder.get_Current() +11406684
System.Web.HttpUtility.UrlEncode(String str, Encoding e) +137
SolrNet.Impl.SolrConnection.<Get>b__0(KeyValuePair`2 input) +89
SolrNet.Utils.<Select>d__1a`2.MoveNext() +612
SolrNet.Utils.Func.Reduce(IEnumerable`1 source, TResult startValue, Accumulator`2 accumulator) +393
SolrNet.Impl.SolrConnection.Get(String relativeUrl, IEnumerable`1 parameters) +908
SolrNet.Impl.SolrQueryExecuter`1.Execute(ISolrQuery q, QueryOptions options) +195
SolrNet.Impl.SolrBasicServer`1.Query(ISolrQuery query, QueryOptions options) +176
SolrNet.Impl.SolrServer`1.Query(ISolrQuery query, QueryOptions options) +176
TebeComSearchEngine.SolrManager.RecalculateMostRequested() in SolrManager.cs:77
TebeCom.MvcApplication.Application_Start() in Global.asax.cs:101
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +4043621
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +191
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +352
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +407
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +375
[HttpException (0x80004005): Response is not available in this context.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11612256
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4842149`
'Response is not available in this context'. What can be the problem?
You are running this in IIS7 Integrated Application Pool mode instead of Classic mode. In Integrated mode you don't have access to the HttpResponse in Application_Start any any attempt to access it will blow.
Here's a blog post which covers a similar situation but with the HttpRequest.
After a lot of digging and looking around the SolrNet code, they don't appear to be doing anything wrong. Also, as Darin pointed out in an indirect manner, HttpUtility.UrlEncode should work fine in code without a HttpContext, such as a console application, and it does.
However, as VinayC pointed out in his comment on that answer of Darin's:
Actually, it appears to be a bug. From
reflector, actual code appears to be
"if (null != current && null !=
current.Response && ...)" where
current is current http context. Issue
here is that Response getter throws an
exception, instead of returning null
Instead of throwing that overly descriptive exception (no doubt they were trying to be helpful), they should have just returned null and let null reference exceptions happen. In this case, they were simply checking for nulls, so the exception wouldn't have happened anyway! I'll report it as a bug if it hasn't been already.
Unfortunately, what this means to you is that you have pretty much no choice but to run in Classic mode. Technically you could put the call to TebeComSearchEngine.SolrManager.RecalculateMostRequested() in a thread that you spawn in application_start and delay its execution until after the app finishes starting. As far as I know, there is no surefire way to programmatically signal the end of the application starting so, that approach may be a little messy.
If you're up for it though, you could probably get that delayed startup mechanism implemented. Compared to punishing the first visitor to the site, it doesn't seem too bad.
This was discussed about a month ago in the SolrNet mailing list.
It's a regression in ASP.NET 4, here's a mention of this bug.
A future release of SolrNet will replace System.Web.HttpUtility.UrlEncode to work around this bug. (or if you really need this, why not fork the source code and fix it?)
EDIT: I just fixed this.

Problem with Linq to SQL

I've been working with Linq to SQL for some time now, and I never had a problem ... until now. I have a method that send a query to the database, but different from the other times I did it, I cannot cast the result (be it to List or to Array). The method look as follows:
public List<vwContainer> GetConteinerPorto(int id)
{
return (from cont in db.vwContainers
where cont.idHarbor == id
orderby cont.Year
select cont).ToList();
}
I tried some variations of it, but it always result with a "Specified cast is not valid." exception being thrown. Can you guys give me some light?
Stacktrace:
[InvalidCastException: Specified cast is not valid.]
System.Data.SqlClient.SqlBuffer.get_Int32() +6271252
Read_vwCargas_movimentadas_conteiner(ObjectMaterializer`1 ) +636
System.Data.Linq.SqlClient.ObjectReader`2.MoveNext() +42
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +472
System.Linq.Enumerable.ToList(IEnumerable`1 source) +80
WebPortosSEP.Web.Models.PortoRepository.GetConteinerPorto(Int32 id) +867
WebPortosSEP.Web.Controllers.PortoController.Cargas(Int32 id) +255
lambda_method(Closure , ControllerBase , Object[] ) +112
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +258
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
System.Web.Mvc.<>c__DisplayClassd.<InvokeActionMethodWithFilters>b__a() +125
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +640
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +709
System.Web.Mvc.Controller.ExecuteCore() +162
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__4() +58
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +20
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +453
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +371
This might be because of the mismatch between the types of columns in the database and the .Net types.
When the values of fields like cont.idHarbor and cont.Year are read from the database and converted to .Net types the resulting types may not match those of the properties in your class.
Check if idHarbor is bigInt in database and you are comparing it with an int. Also check the Year field types. You can take a clue from the stacktrace. Is the exception thrown by SqlDataReader.GetInt64 or any such similar method?
It would seem that cont is not actually a vwContainer.
Your method does not contain any cast.
Are your sure the Exception is throw from within the method and not from its call site?
Try this:
public List<vwContainer> GetConteinerPorto(int id)
{
return (from cont in db.vwContainers
where cont.idHarbor == id
orderby cont.Year
select cont).ToList<vwContainer>();
}
It's possible you changed the database schema (e.g. an into to a string) and didn't update the DBML (you would only see this error at runtime when you first access the table that has the error)
If it's a runtime exception and not a compile tome error, then the problem is almost surely that your dbml file is out of sync with your database on some level. I have also seem similar problems when you have more than one dbml file in the same namespace.
Try deleting the table in question out of the dbml file and recreate it.
UPDATE:
Based on your stacktrace, I find it highly suspicious that your exception occurs within a lambda method, but the code you have sown does not include any lambdas. That's not to say there might not be an internal lambda going on, but I don't think so.
Also, note that your stack trace includes this:
Read_vwCargas_movimentadas_conteiner
That's different from the code you posted.
Update 2:
The exception is occuring in an Int32 conversion, which suggests that one of your data columns is not correctly defined. Did you change the type from nullable to non-nullable?

Categories