It doesn't happen often but from time to time I'll get an exception report emailed to me pointing to this bit of code. I'm wondering if you see anything wrong with the following code. I cannot get it to fail locally and tracing the data using breakpoints always gives the correct results, step by step.
namespace DomainModel.Concrete
{
public class ConfigRepository : IConfigRepository
{
static mvCmsContext context { get; set; }
public ConfigRepository() { context = new mvCmsContext(); }
private static Func<mvCmsContext, string, Configuration> _byName =
CompiledQuery.Compile((mvCmsContext context, string configName) =>
(from c in context.Configs
where c.configName == configName
select c).SingleOrDefault());
static public Configuration ByName(string configName)
{
var result = (Configuration)HttpContext.Current.Cache.Get(configName);
if (result == null)
{
using (new mvCmsContext())
{
HttpContext.Current.Cache.Insert(configName, _byName(context, configName));
result = (Configuration)HttpContext.Current.Cache.Get(configName);
}
}
return result;
}
}
}
Here is the service calling that method:
public class ConfigService
{
public static string siteName
{
get { return ConfigRepository.ByName("Site_Name").configValue; }
}
public static string copyright
{
get { return ConfigRepository.ByName("Copyright").configValue; }
}
public static string companyName
{
get { return ConfigRepository.ByName("Company_Name").configValue; }
}
public static string homeTitle
{
get { return ConfigRepository.ByName("Home_Title").configValue; }
}
public static string contactEmail
{
get { return ConfigRepository.ByName("Contact_Email").configValue; }
}
public static string physicalAddress
{
get { return ConfigRepository.ByName("Physical_Address").configValue; }
}
public static string phoneNumber
{
get { return ConfigRepository.ByName("Phone_Number").configValue; }
}
}
Here is the report received:
** Summary **
--------------- This message contains events 1 to 1 from the total of 1
events scheduled for this
notification. There were 0 events
left in the buffer at the beginning of
this notification.
** Application Information **
--------------- Application domain: /LM/W3SVC/66/ROOT-7-129384226573152341
Trust level: Full Application Virtual
Path: / Application Path:
D:*****.com\ Machine name:
WIN11
** Events **
--------------- Event code: 3005 Event message: An unhandled exception has
occurred. Event time: 1/2/2011
12:17:44 AM Event time (UTC): 1/2/2011
6:17:44 AM Event ID:
f909c5c676bd4ca1ba21512c678ac502 Event
sequence: 6 Event occurrence: 1 Event
detail code: 0
Process information:
Process ID: 26904
Process name: w3wp.exe
Account name: NT AUTHORITY\NETWORK SERVICE
Exception information:
Exception type: System.InvalidOperationException
Exception message: Invalid operation. The connection is closed.
Request information:
Request URL: http://.com/article/-ALERT
Request path: /article/III-ALERT
User host address: 68.230.129.53
User:
Is authenticated: False
Authentication Type:
Thread account name: NT AUTHORITY\NETWORK SERVICE
Thread information:
Thread ID: 6
Thread account name: NT AUTHORITY\NETWORK SERVICE
Is impersonating: False
Stack trace: at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at
System.Data.SqlClient.SqlConnection.get_HasLocalTransactionFromAPI()
at
System.Data.SqlClient.SqlCommand.ValidateCommand(String
method, Boolean async) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior,
Boolean returnStream, String method,
DbAsyncResult result) at
System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior
cmdBehavior, RunBehavior runBehavior,
Boolean returnStream, String method)
at
System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior
behavior, String method) at
System.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior
behavior) at
System.Data.Linq.SqlClient.SqlProvider.Execute(Expression
query, QueryInfo queryInfo,
IObjectReaderFactory factory, Object[]
parentArgs, Object[] userArgs,
ICompiledSubQuery[] subQueries, Object
lastResult) at
System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression
query, QueryInfo[] queryInfos,
IObjectReaderFactory factory, Object[]
userArguments, ICompiledSubQuery[]
subQueries) at
System.Data.Linq.SqlClient.SqlProvider.CompiledQuery.Execute(IProvider
provider, Object[] arguments) at
System.Data.Linq.CompiledQuery.ExecuteQuery(DataContext
context, Object[] args) at
System.Data.Linq.CompiledQuery.Invoke[TArg0,TArg1,TResult](TArg0
arg0, TArg1 arg1) at
DomainModel.Concrete.ConfigRepository.ByName(String
configName) at
DomainModel.Services.ConfigService.get_companyName()
at
ASP.views_shared_site_master._Render_control1(HtmlTextWriter
__w, Control parameterContainer) at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter
writer, ICollection children) at
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter
writer, ICollection children) at
System.Web.UI.Page.Render(HtmlTextWriter
writer) at
System.Web.Mvc.ViewPage.Render(HtmlTextWriter
writer) at
System.Web.UI.Page.ProcessRequestMain(Boolean
includeStagesBeforeAsyncPoint, Boolean
includeStagesAfterAsyncPoint)
If I were closing the datacontext at the wrong place it would fail all the time, wouldn't it?
Edit - Data context:
public class mvCmsContext : DataContext
{
public mvCmsContext():
base(ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString,XmlMappingSource.FromStream(Assembly.GetExecutingAssembly().GetManifestResourceStream("DomainModel.mvCmsMapping.map"))){
Log = (StringWriter)HttpContext.Current.Items["linqToSqlLog"];
}
public Table<DomainModel.Entities.Configuration> Configs { get { return this.GetTable<DomainModel.Entities.Configuration>(); } }
}
Edit to add update:
Does this look better? I'll upload it and give it a go.
public class ConfigRepository : IConfigRepository
{
private mvCmsContext context { get; set; }
public ConfigRepository() { context = new mvCmsContext(); }
private static Func<mvCmsContext, string, Configuration> _byName =
CompiledQuery.Compile((mvCmsContext context, string configName) =>
(from c in context.Configs
where c.configName == configName
select c).SingleOrDefault());
static public Configuration ByName(string configName)
{
var result = (Configuration)HttpContext.Current.Cache.Get(configName);
if (result == null)
{
using (var context = new mvCmsContext())
{
HttpContext.Current.Cache.Insert(configName, _byName(context, configName));
result = (Configuration)HttpContext.Current.Cache.Get(configName);
}
}
return result;
}
Your issue is that you are defining your datacontext as static. This means its shared by all requests and threads.
When you have two different requests hitting your static datacontext, these sort of exceptions occur. Your using section in ByName will recreate and dispose of the datacontext, imagine another request is using the datacontext while your doing this....... hence the exceptions.
The solution is to make your datacontext non-static.
Related
Currently on a project to create a check-in system and I'm creating this in ASP.NET MVC. I'm at the stage where I'm in my ImportController and using the Nuget package CsvHelper.
I'm getting errors including 'No overload for method 'Add' takes 3 arguments. Is anyone able to help? I've included a snip of my code below.
Any help would be much appreciated :)
[Route("import")]
public class ImportController : Controller
{
private readonly AppDbContext _appDbContext;
public ImportController(AppDbContext appDbContext)
{
_appDbContext = appDbContext;
}
[HttpGet("")]
public IActionResult Index()
{
return View();
}
public IActionResult Index(ImportIndexViewModel vm)
{
if (ModelState.IsValid)
{
using (var csvStream = new StreamReader(vm.File.OpenReadStream()))
using (var csv = new CsvReader(csvStream))
{
csv.Read();
csv.ReadHeader();
while (csv.Read())
{
try
{
// Application reference
var AdmissionNumber = csv["Admission Number"];
var Firstname = csv["Students Firstname"];
var Surname = csv["Students Surname"];
if (string.IsNullOrWhiteSpace(AdmissionNumber))
throw new NullReferenceException("admissionNumber");
if (string.IsNullOrWhiteSpace(Firstname))
throw new NullReferenceException("Forename");
if (string.IsNullOrWhiteSpace(Surname))
throw new NullReferenceException("Surname");
// Add student to system
_appDbContext.Students.Add(AdmissionNumber.Trim(), Firstname.Trim(), Surname.Trim());
}
catch (NullReferenceException ex)
{
throw;
Console.WriteLine($"'{ex.Message}' is missing from row {csv.Context.Row}");
}
}
}
}
return View(vm);
}
}
}
Here is the exception stack it's providing me when I click upload. I think this again is due to this line here: _appDbContext.Students.Add(AdmissionNumber.Trim(), Firstname.Trim(), Surname.Trim());
System.InvalidOperationException: Could not create an instance of type 'System.Func`1[[SelfRegister.WebApp.Models.StudentsIndexViewModel+StudentViewModel, SelfRegister.WebApp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]'. Model bound complex types must not be abstract or value types and must have a parameterless constructor. Alternatively, give the '_appDbContext' parameter a non-null default value.
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.CreateModel(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.ComplexTypeModelBinder.BindModelCoreAsync(ModelBindingContext bindingContext, Int32 propertyData)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Logged|17_1(ResourceInvoker invoker)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
we use a StateServer for handling Session for the known benefits (web farm, IIS recycling).
However I am trying to figure out how to make this fault tolerant. Nothing we store in the Session is critical, it is just used for performance. So if the StateServer is not available we are happy to reload from disk.
However there appears to be no way of detecting if the StateServer is online or not, so the following code all runs fine even if the StateServer is down
try
{
//It is not NULL as it has been configured
if (HttpContext.Current.Session != null)
Session["Test"] = "value";
}
// No exception is thrown
catch (Exception)
{
throw new Exception();
}
Now it makes sense to me that no exception is thrown. The Session handling would not be very performant if it had to check the status on every write. So I am guessing what happens is that it writes all the Session vaiables when the Response is written.
There lies the problem, when it tries to write the Session it fails with a 500 error and I do not know anyway to intercept this error and handle it.
Unable to make the session state request to the session state server.
Please ensure that the ASP.NET State service is started and that the
client and server ports are the same.
What I would like to happen is that the write just fails silently (or logs an error) and clients are not impacted. As it is write now the entire site goes down due to this single point of failure.
Any ideas - am I missing something obvious?
well, it can be hard. Asp.net uses session tightly, so if session storage fails, it asp.net will also fails during initialization of session module. You can write own session state provider, that will wrap existing one, and in case of fail it will return empty session items, but it can be hard to use it, because session behavior can be unpredictable.
You can look into built in SQL session state provider, that has failover in case if your SQL server has replication.
UPDATE1
Here is example of wrapper for default session providers
public class SessionProviderWrapper : SessionStateStoreProviderBase
{
private readonly SessionStateStoreProviderBase _provider;
private static Func<SessionStateStoreProviderBase> _createProvider;
static SessionProvider()
{
_createProvider = InitializerProvider();
}
private static Func<SessionStateStoreProviderBase> InitializerProvider()
{
if (_createProvider != null)
return _createProvider;
var sessionType = "stateserver"; // you can switch to another session provider
Type type;
switch (sessionType)
{
case "inproc":
type = Type.GetType("System.Web.SessionState.InProcSessionStateStore, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
break;
case "sql":
type = Type.GetType("System.Web.SessionState.SqlSessionStateStore, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
break;
case "stateserver":
type = Type.GetType("System.Web.SessionState.OutOfProcSessionStateStore, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a");
break;
default:
throw new ConfigurationErrorsException("Unknow session type: " + sessionType);
}
if (type == null)
{
throw new InvalidOperationException("Failed to find session provider for " + sessionType);
}
_createProvider = GenerateConstructorCall(type);
return _createProvider;
}
private static Func<SessionStateStoreProviderBase> GenerateConstructorCall(Type type)
{
// we are searching for public constructor
var constructor = type.GetConstructors().FirstOrDefault(c => c.GetParameters().Length == 0);
if (constructor == null)
{
// otherwise for internal. SQL session provider has internal constructor, but we don't care
constructor = type.GetConstructors(BindingFlags.NonPublic | BindingFlags.Instance).FirstOrDefault(c => c.GetParameters().Length == 0);
}
var node = Expression.New(constructor);
var lambda = Expression.Lambda<Func<SessionStateStoreProviderBase>>(node, null);
var func = lambda.Compile();
return func;
}
public SessionProvider()
{
var createProvider = InitializerProvider();
_provider = createProvider();
}
public override void Initialize(string name, NameValueCollection config)
{
_provider.Initialize(name, config);
}
public override string Name
{
get { return _provider.Name; }
}
public override string Description
{
get { return _provider.Description; }
}
public override void Dispose()
{
_provider.Dispose();
}
public override bool SetItemExpireCallback(SessionStateItemExpireCallback expireCallback)
{
return _provider.SetItemExpireCallback(expireCallback);
}
public override void InitializeRequest(HttpContext context)
{
_provider.InitializeRequest(context);
}
public override SessionStateStoreData GetItem(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId,
out SessionStateActions actions)
{
try
{
return _provider.GetItem(context, id, out locked, out lockAge, out lockId, out actions);
}
catch (Exception ex)
{
locked = false;
lockAge = TimeSpan.Zero;
lockId = null;
actions = SessionStateActions.None;
// log ex
return new SessionStateStoreData(new SessionStateItemCollection(), new HttpStaticObjectsCollection(), 10);
}
}
public override SessionStateStoreData GetItemExclusive(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId,
out SessionStateActions actions)
{
return _provider.GetItemExclusive(context, id, out locked, out lockAge, out lockId, out actions);
}
public override void ReleaseItemExclusive(HttpContext context, string id, object lockId)
{
_provider.ReleaseItemExclusive(context, id, lockId);
}
public override void SetAndReleaseItemExclusive(HttpContext context, string id, SessionStateStoreData item, object lockId, bool newItem)
{
_provider.SetAndReleaseItemExclusive(context, id, item, lockId, newItem);
}
public override void RemoveItem(HttpContext context, string id, object lockId, SessionStateStoreData item)
{
_provider.RemoveItem(context, id, lockId, item);
}
public override void ResetItemTimeout(HttpContext context, string id)
{
_provider.ResetItemTimeout(context, id);
}
public override SessionStateStoreData CreateNewStoreData(HttpContext context, int timeout)
{
return _provider.CreateNewStoreData(context, timeout);
}
public override void CreateUninitializedItem(HttpContext context, string id, int timeout)
{
_provider.CreateUninitializedItem(context, id, timeout);
}
public override void EndRequest(HttpContext context)
{
_provider.EndRequest(context);
}
}
Basically you can make try\catch on each method like in GetItem method, and in case of error, you can return empty session object. If it fails in try\catch application still will be alive. But performance will be decreased as for each request it will throw a couple of exceptions on Get\Release, that will be handled in catch section. But anyway these exceptions will decrease performance a bit
I would like to accept tgolisch answer as a solution that works for me.
In Global.asax we will look for the missing StateServer error in the Application_Error event
If we find it we will use Server.ClearError() and log the error
We will also use this to log the error and possibly send out an alert
Thanks all!
I'm getting a strange issue on our MVC app. We are inheriting the RazorViewEngine to create a custom view engine, to facilitate custom logic in the arrangement of views.
We have a list of potential view paths:
PartialViewLocationFormats = new[]
{
"~/Views/Partial/Shared/Base/$thing/{0}.$otherthing.cshtml",
"~/Views/Partial/Shared/Base/$thing/{0}.cshtml",
"~/Views/Partial/Shared/Base/{0}.$otherthing.cshtml",
"~/Views/Partial/Shared/Base/{0}.cshtml"
};
Then we override the FileExists method, like:
protected override bool FileExists(ControllerContext controllerContext, string virtualPath)
{
return base.FileExists(controllerContext, this.ParsePath(controllerContext, virtualPath));
}
ParsePath method looks like:
private string ParsePath(ControllerContext controllerContext, string virtualPath)
{
string newPath = virtualPath;
BaseController controller = controllerContext.Controller as BaseController;
if (controller != null)
{
if (controller.Model != null)
{
if (!string.IsNullOrEmpty(controller.Model.Thing))
{
newPath = newPath.Replace("$thing", controller.Model.Thing);
}
if (!string.IsNullOrEmpty(controller.Model.OtherThing))
{
newPath = newPath.Replace("$otherthing", controller.Model.OtherThing);
}
}
}
return newPath;
}
This works fine locally, but after publishing to a Win 2012, IIS8 box, I'm seeing the following error:
The file '/Views/Partial/Shared/Base/Footer.blar.cshtml' does not exist.
TargetSite: System.Web.Compilation.BuildResult GetVPathBuildResultInternal(System.Web.VirtualPath, Boolean, Boolean, Boolean, Boolean, Boolean)
StackTrace: at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate) yadda yadda yadda
'/Views/Partial/Shared/Base/Footer.cshtml' does exist, why does it throw the exception?
My hunch is the code is fine and its a issue with IIS - I've checked that the sites are running integrated mode etc...
Any ideas?
This is happening because of an optimization MVC has when you have the application set to debug="false". Once I set debug="true", This error went away for me.
I have a DateTime field for storing the creation date of my entity:
private DateTime _creationDate;
[Column(DbType = "DATETIME")]
public DateTime CreationDate
{
get { return _creationDate; }
set { SetProperty(ref _creationDate, value); }
}
This will throw the follwoing exception:
System.Data.SqlServerCe.SqlCeException:
HResult=-2147467259
Message=Overflow while converting to 'datetime'.
Source=SQL Server Compact ADO.NET Data Provider
ErrorCode=-2147467259
NativeError=25933
StackTrace:
at System.Data.SqlServerCe.SqlCeDataReader.ProcessResults(Int32 hr)
at System.Data.SqlServerCe.SqlCeResultSet.SetValues(SEPREPAREMODE mode, SqlCeUpdatableRecord record)
at System.Data.SqlServerCe.SqlCeResultSet.InternalInsert(Boolean fMoveTo, Object sender, SqlCeUpdatableRecord record)
at System.Data.SqlServerCe.SqlCeResultSet.Insert(SqlCeUpdatableRecord record, DbInsertOptions options)
at System.Data.Linq.ChangeDirector.StandardChangeDirector.DoResultSetInsert(TrackedObject item)
at System.Data.Linq.ChangeDirector.StandardChangeDirector.Insert(TrackedObject item)
at System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode)
at System.Data.Linq.DataContext.SubmitChanges()
at PinboardApp1.App..ctor()
InnerException:
I have also tried using DbType="DATETIME2".
Is this a general issue or is there a work-around?
I am getting this error randomly at the production server here is the stack trace of the error. I am using linq to sql and .net 4.0
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.EvoletDataContext.get_sysModules() in D:\MyProj\Models\datamdl.designer.cs:line 1294
at UserManagement.Models.FilterRepository.GetModuleHead(String actionName) in D:\MyProj\Models\FilterRepository.cs:line 14
at UserManagement.Models.DummyAttrib.OnAuthorization(AuthorizationContext filterContext) in D:\MyProj\Models\Filters.cs:line 44
at Glimpse.Net.Plumbing.GlimpseAuthorizationFilter.OnAuthorization(AuthorizationContext filterContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass6.<>c__DisplayClassb.<BeginProcessRequest>b__5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.<MakeVoidDelegate>b__0()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.<>c__DisplayClasse.<EndProcessRequest>b__d()
at System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Code at line 14 is below. I have also included the datacontext
private EvoletDataContext db = new EvoletDataContext();
public sysModule GetModuleHead(string actionName)
{
var val = (from mod in db.sysModules
where
mod.ModuleActionResult.ToLower().Equals(actionName.ToLowerInvariant())
select mod).SingleOrDefault();
return val;
}
Code at line 44 is
public class DummyAttrib:FilterAttribute,IAuthorizationFilter
{
private readonly FilterRepository _filterRepository = new FilterRepository();
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.Controller.ControllerContext.IsChildAction && !filterContext.HttpContext.Request.IsAjaxRequest())
{
var cont = (ApplicationController)filterContext.Controller;
var modhead = _filterRepository.GetModuleHead(filterContext.RouteData.Values["action"].ToString());
if (cont.DocumentID != 0 && modhead !=null)
{
if (_filterRepository.hasRightonModuleChildren(modhead.ModuleID, cont.RoleID))
return;
}
if (cont.DocumentID == 0 && !filterContext.RouteData.Values["action"].ToString().ToLowerInvariant().Equals("index"))
{
filterContext.Result = new RedirectResult("/account.mvc/AccessDenied");
return;
}
if (!_filterRepository.hasRighton(cont.DocumentID, cont.RoleID))
{
filterContext.Result = new RedirectResult("/account.mvc/AccessDenied");
return;
}
}
}
}
LINQ maintains a 'cache' of sorts of tables you have already used, to prevent having to look them up multiple times.
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]()
The table you're trying to use hasn't been used within the data context before, so it's being added to the 'cache'. One of the ways this could fail is if you're calling GetTable() from multiple threads simultaneously, which suggests you're using a single data context for the entire application, which is not a good idea. Also, don't use the same data context if you're executing tasks in parallel.
I have a same problem. I've solved it.
Actually I have a duplicate property with the same name in my ViewModel.
One Property was in BaseViewModel and another is in derived Model.
For Example
public class BaseviewModel{
public int UserId { get; set; }
}
public class Model : BaseViewModel
{
public int UserId { get; set; }
}
I have changed them as
public class BaseviewModel{
public int UserId { get; set; }
}
public class Model : BaseViewModel
{
public int User_Id { get; set; }
}
Now it is working fine.
It looks like a bug - but MS have fixed it for .NET 4
http://connect.microsoft.com/VisualStudio/feedback/details/496178/linq-to-sql-projection-throws-argumentexception-an-item-with-the-same-key-has-already-been-added
Are you overriding any properties in your model classes?
Hope this helps,
Matt
I had the same error but the cause was one of my many-to-one relationships being defined with the wrong ends as the primary and secondary keys in the relationship.
Using the SQL Server Management Studio designer it was too easy to drag-drop from the child table to the parent table and miss the difference in the created relationship.
Check that all your relationships are correctly defined.
We have had similar problems after couple of months of deployment in production server. After doing some research I found out that sometimes there is a problem with LINQ closing connection automatically. Now we are specifically closing all the LINQ TO SQL connection via static extension method. Sample code:
public static void extClose(this System.Data.Linq.DataContext dataContext, bool submitChanges)
{
if (null != dataContext && System.Data.ConnectionState.Closed != dataContext.Connection.State)
{
if (true == submitChanges)
{
dataContext.SubmitChanges();
}
dataContext.Connection.Close();
}
}
I got the same issue in EF 4.1. with an existing application.
What happened? The EF 4.1 requires the .net framework 4.0. Windows update replaced the .net framework 4.0 with 4.5 and I got the same error you got.
The solution was to uninstall .net 4.5 and install .net 4.0.
On the production machine you should set the windows to skip the update to 4.5.