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.
Related
I know that this is a duplicate question but i can't find answer to my error.
I'm trying to show a list of my rooms saved in database but i get next error:
Server Error in '/' Application.
No parameterless constructor defined for this object.
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.MissingMethodException: No parameterless constructor defined for this object.
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:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a controller of type 'HotelProjectFinal.Controllers.RoomController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +182
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +74
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +232
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +49
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +13
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +124
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +98
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8969412
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
But i have a constructor withou a parameter:
namespace HotelProjectFinal.Controllers
{
public class RoomController : Controller
{
private IRoomRepository repository;
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
public ViewResult List()
{
return View(repository.Rooms);
}
}
}
My view is :
#model IEnumerable<HotelProjectFinal.Models.Room>
#{
ViewBag.Title = "List";
}
#foreach (var p in Model)
{
<div class="item">
<h3>#p.Room_number</h3>
#p.Room_Type
<h4>#p.Room_Type.Price.ToString("c")</h4>
</div>
}
I am using ninject:
public class NinjectControllerFactory : DefaultControllerFactory
{
private IKernel ninjectKernel;
public NinjectControllerFactory()
{
ninjectKernel = new StandardKernel();
AddBindings();
}
protected override IController GetControllerInstance(RequestContext requestContext,
Type controllerType)
{
return controllerType == null
? null
: (IController)ninjectKernel.Get(controllerType);
}
private void AddBindings()
{
ninjectKernel.Bind<IRoomRepository>().To<EFRoomRepository>();
}
}
}
You've got a controller factory, but the fact that the stacktrace says nothing about Ninject suggests you have forgotten to tell MVC about it.
You could fix that by adding a line to tell it that.
However the recommended practice is to hook Ninject in by adding a NuGet reference to Ninject.MVC3. There are docs about it on the associated Ninject MVC3 wiki.
Please try changing your constructors to the following:
public RoomController() { } // You were missing this parameterless constructor
[Inject]
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Ninject is looking for a parameterless constructor because you haven't specified [Inject] above constructor that you wish to use for dependency injection. This has confused "Ninject" and caused an exception to be thrown.
The primary DI pattern is Constructor Injection. When activating an instance of a type Ninject will choose one of the type’s constructors to use by applying the following rules in order:-
If a constructor has an [Inject] attribute, it is used (but if you apply the attribute to more than one, Ninject will throw a NotSupportedException at runtime upon detection).
If no constructors have an [Inject] attribute, Ninject will select the one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default parameterless constructor (assuming there is one).
More information can be found here:
https://github.com/ninject/ninject/wiki/Injection-Patterns
As pointed out by Ruben, [Inject] attribute pollutes the controller with external concerns.
This ties your code to a specific container. (Although Ninject does permits the customization of the specific attribute to look for, the point remains – you’re polluting an interface with external concerns.)
Your actual problem probably relies in a missing reference to Ninject.MVC3
Even though IRoomRepository could be null, that doesn't make it a parameterless constructor. At first glace, it looks like your IoC isn't wired up correctly for IRoomRepository. With no IoC, or misconfigured IoC, the controller activator looks for a parameterless constructor for your controllers.
// This is a parameterless constructor.
public RoomController()
{ }
// This is not a parameterless constructor.
public RoomController(IRoomRepository roomRepository)
{
repository = roomRepository;
}
Edit, Are you using Ninject.Mvc and your base MvcHttpApplication is implementing NinjectHttpApplication?
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.
Edit: This is fixed -- See Solution below
Solution: First I incorrectly had my node defined in /shared/web.config instead of the web.config in the root of the WebUI project. I also had not correctly defined my connection string within web.config. I have pasted the proper web.config sections below:
<configuration>
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor"/>
<!--more sectiongroup and sections redacted for brevity -->
</configSections>
<castle>
<components>
<component id="ProdsRepository" service="DomainModel.Abstract.IProductsRepository, DomainModel" type="DomainModel.Concrete.SqlProductsRepository, DomainModel">
<parameters>
<connectionString>Data Source=.\SQLExpress;Initial Catalog=SportsStore; Integrated Security=SSPI</connectionString>
</parameters>
</component>
</components>
</castle>
I also had to adjust the method body of WindsorControllerFactory.cs (IoC Container) to return null for invalid requests like so:
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
if (controllerType == null)
return null;
else
return (IController)container.Resolve(controllerType);
}
End of Solution
I'm following the book Pro ASP.NET MVC2 by Sanderson. I've implemented the IoC container and gotten the web.config straightened out. When I attempt to run my application I get the error "No parameterless constructor defined for this object"
After some searching I found this exact issue on SO here. The solution is to create the constructor with no parameters but I'm having an issue doing this. I've pasted the code from ProductsController.cs below
namespace WebUI.Controllers
{
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController(IProductsRepository productsRepository)
{
this.productsRepository = productsRepository;
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
}
}
Above the public ProductsController that has parameters I tried doing:
public ProductsRepository() : this(new productsRepository())
{
}
I'm unclear about exactly what needs to go after the "new". IProductsRepository doesn't seem to work and neither does what I have written. I have pasted the stack trace below:
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +80
[InvalidOperationException: An error occurred when trying to create a controller of type 'WebUI.Controllers.ProductsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +190
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +68
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +118
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +46
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +63
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +13
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8682818
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Any help would be greatly appreciated.
Edit: Posting WindsorControllerFactory.cs code:
namespace WebUI
{
public class WindsorControllerFactory : DefaultControllerFactory
{
WindsorContainer container;
// The contructor:
// 1. Sets up a new IoC container
// 2. Registers all components specified in web.config
// 3. Registers all controller types as components
public WindsorControllerFactory()
{
// Instantiate a container, taking config from web.config
container = new WindsorContainer(new XmlInterpreter(new ConfigResource("castle")));
// Also register all the controller types as transient
var controllerTypes = from t in Assembly.GetExecutingAssembly().GetTypes()
where typeof(IController).IsAssignableFrom(t)
select t;
foreach (Type t in controllerTypes)
container.AddComponentLifeStyle(t.FullName, t, Castle.Core.LifestyleType.Transient);
}
// Constructs the controller instance needed to service each request
protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
return (IController)container.Resolve(controllerType);
}
}
}
Edit2: Pertinent Web.config nodes:
<configSections>
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor" />
</configSections>
<castle>
<components>
<component id="ProdsRepository"
service="DomainModel.Abstract.IproductsRepository, DomainModel"
type="DomainModel.Concrete.SqlProductsRepository, DomainModel"></component>
<parameters>
</parameters>
</components>
</castle>
You need to configure a custom controller factory in order to wire up your DI framework inside Application_Start method in global.asax. So for example if you are using Unity as DI framework you could:
ControllerBuilder.Current.SetControllerFactory(
typeof(UnityControllerFactory)
);
Check out this blog post for more information.
you can make use of setter based injection
public class ProductsController : Controller
{
private IProductsRepository productsRepository;
public ProductsController()
{
}
public ViewResult List()
{
return View(productsRepository.Products.ToList());
}
public IProductsRepository MyRepository
{
get
{
return productsRepository;
}
set
{
productsRepository = value;
}
}
}
here , you need to manually set the MyRepository.
but best would be , if you register your repository to a container and beliving that you are using Unity framework , so you can do it by IUnityContainer.RegisterType() method
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.
i am following the example at http://msdn.microsoft.com/en-us/library/system.web.util.requestvalidator.aspx but it doesn't seem to work and i still get error. Here is my class and how i add it to webconfig
my webconfig:
<httpRuntime requestValidationType="CustomRequestValidation"/>
my class:
public class CustomRequestValidation : RequestValidator
{
public CustomRequestValidation() { }
protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
{
validationFailureIndex = -1;
if (requestValidationSource == RequestValidationSource.Path)
{
// value "&","=" allowed.
if (value.Contains("&") || value.Contains("="))
{
validationFailureIndex = -1;
return true;
}
else
{
//Leave any further checks to ASP.NET.
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
else
{
return base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex);
}
}
}
Error details are:
System.Web.HttpException
A potentially dangerous Request.Path value was detected from the client (=).
System.Web.HttpException (0x80004005): A potentially dangerous Request.Path value was detected from the client (:).
at System.Web.HttpRequest.ValidateInputIfRequiredByConfig()
at System.Web.HttpApplication.ValidateRequestExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
I had this issue too and adding this to the web.config resolved the issue.
<httpRuntime requestPathInvalidCharacters="" />
By Default, .Net 4.0 rejects all requests with <>*%&:\? characters which may be causing the issue for you like it was for me.
[ConfigurationProperty("requestPathInvalidCharacters", DefaultValue=#"<,>,*,%,&,:,\,?")]
public string RequestPathInvalidCharacters { get; set; }
Please try with adding namespace in requestValidationType
requestValidationType="CustomControlTest.CustomRequestValidator"
Here CustomControlTest is the namespace.