I am having an odd issue.
My MVC application seems to be working perfectly fine except for one view page.
The view page in question (Organization/Edit) gets a 'NullReferenceException' on every code item on the page. Whether it is Html.TextBoxFor() or HTML.AntiForgeryToken().
I have my model, view, and controller laid out here on another question that i think is related -- https://stackoverflow.com/questions/26475866/dropdownlistfor-null-reference-error
As you can see below, my model does have information inside of it. This screen capture was taken at the "Return View("Edit", model)" inside the controller.
Exception Details
- Source = App_Web_zu4jlld0
- StackTrace = at ASP._Page_Views_Organization_Edit_vbhtml.Execute() in C:\Users\mtaylor\Projects\Check Im Here\mtaylor-branch\CheckImHere_v2\CheckImHereMVC\Views\Organization\Edit.vbhtml:line 16
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy()
at System.Web.Mvc.WebViewPage.ExecutePageHierarchy()
at System.Web.WebPages.StartPage.RunPage()
at System.Web.WebPages.StartPage.ExecutePageHierarchy()
at System.Web.WebPages.WebPageBase.ExecutePageHierarchy(WebPageContext pageContext, TextWriter writer, WebPageRenderingBase startPage)
at System.Web.Mvc.RazorView.RenderView(ViewContext viewContext, TextWriter writer, Object instance)
at System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer)
at System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1a.<InvokeActionResultWithFilters>b__17()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
View
#ModelType CheckImHereMVC.OrganizationEditViewModel
#Using Html.BeginForm("Edit", "Organization", FormMethod.Post)
#Html.AntiForgeryToken() 'get errors here
#Html.ValidationSummary(True) 'get errors here
#Html.TextBoxFor(Function(model) model.organizationSub.subName, New With {.class = "span12"}) 'and errors here
End Using
One thing i notice is that if i comment out my 'textboxfor', my error will occur at the 'ValidationSummary()', if i comment out my 'ValidationSummary()', then my error will occur at 'AntiForgeryToken()'.
So it seems that the error just happens at the last possible code area.
I found the answer to my problem here
For anyone finding this:
Try commenting out the next code line AFTER the error.
#ModelType CheckImHereMVC.OrganizationEditViewModel
#Using Html.BeginForm("Edit", "Organization", FormMethod.Post)
#Html.AntiForgeryToken()
#Html.ValidationSummary(True)
#Html.TextBoxFor(Function(model) model.organizationSub.subName, New With {.class = "span12"})
#Html.TextBoxFor(Function(model) model.organizationSub.subTitle, New With {.class = "span12"})
<img src="#Url.Content(Model.img.imgPath)" alt="IMAGES"/> 'commenting out this line fixed my issue
End Using
In the case above, i would get errors on the model.organizationSub.subTitle. If i commented that line out, i would get errors on the model.organizationSub.subName line. I then found the link mentioned and commented out the line AFTER all of my TextBoxFors. That fixed my issue.
From link: "Some times compiler could not point on exact lines having specific kind of errors in razor view may be because it could not keep their line number in stack trace or somewhere. I have found this case with Null Reference Exception and when null is passed in Url.Content.
So it helps to check the next C# statement in razor view when you did not get any error on the line shown by stack trace."
Related
Here are the symptoms I am experiencing:
I have a brand new empty controller in an area:
public class JamController : Controller
{
public JamController()
{
throw new Exception("Not implemented!");
}
If I visit http://myprojectserver.example.com:12345/urlthatdoesnotexist, I get the following error:
[CompositionException: The composition produced a single composition error. The root cause is provided below. Review the CompositionException.Errors property for more detailed information.
1) Not implemented!
Resulting in: An exception occurred while trying to create an instance of type 'MyWebProject.Areas.Users.Controllers.JamController'.
Resulting in: Cannot activate part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController --> MyWebProject.Areas.Users.Controllers.JamController
Resulting in: Cannot get export 'MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")' from part 'MyWebProject.Areas.Users.Controllers.JamController'.
Element: MyWebProject.Areas.Users.Controllers.JamController (ContractName="System.Web.Mvc.IController")
]
System.ComponentModel.Composition.Hosting.CompositionServices.GetExportedValueFromComposedPart(ImportEngine engine, ComposablePart part, ExportDefinition definition) +55
System.ComponentModel.Composition.Hosting.CatalogExportProvider.GetExportedValue(CatalogPart part, ExportDefinition export, Boolean isSharedPart) +78
System.ComponentModel.Composition.Hosting.CatalogExport.GetExportedValueCore() +47
System.ComponentModel.Composition.Primitives.Export.get_Value() +57
System.ComponentModel.Composition.ExportServices.GetCastedExportedValue(Export export) +40
System.ComponentModel.Composition.<>c__DisplayClassa`1.<CreateStronglyTypedLazyOfT>b__6() +39
System.Lazy`1.CreateValue() +416
System.Lazy`1.LazyInitValue() +382
System.Lazy`1.get_Value() +75
MefContrib.Web.Mvc.<>c__DisplayClass4.<GetControllerType>b__0(Lazy`1 e) +53
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +204
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) +381
System.Linq.Enumerable.ToList(IEnumerable`1 source) +58
MefContrib.Web.Mvc.CompositionControllerFactory.GetControllerType(RequestContext requestContext, String controllerName) +412
System.Web.Mvc.DefaultControllerFactory.System.Web.Mvc.IControllerFactory.GetControllerSessionBehavior(RequestContext requestContext, String controllerName) +61
System.Web.Mvc.MvcRouteHandler.GetSessionStateBehavior(RequestContext requestContext) +122
System.Web.Mvc.MvcRouteHandler.GetHttpHandler(RequestContext requestContext) +33
System.Web.Mvc.MvcRouteHandler.System.Web.Routing.IRouteHandler.GetHttpHandler(RequestContext requestContext) +10
System.Web.Routing.UrlRoutingModule.PostResolveRequestCache(HttpContextBase context) +9709884
System.Web.Routing.UrlRoutingModule.OnApplicationPostResolveRequestCache(Object sender, EventArgs e) +82
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +136
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +699
My question is "Why?" Why on earth is it trying to instantiate this controller? Where do I look to determine what is causing this. I'm pretty sure it isn't expected behaviour to instantiate every controller on "page not found".
I'm at a loss to know where to look. Can someone point me in the direction of something that will help?
UPDATE:
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
This is down to a bug in MefContrib.Web.Mvc. This assembly implements it's own ControllerFactory that inherits from DefaultControllerFactory.
The factory overrides GetControllerType, I assume to try and resolve controllers that live in assemblies somewhere other than the default application or it's references. The implementation of GetControllerType first calls into base.GetControllerType to see if Defaultcontroller can resolve it.
If it can't - which is the case for urls that don't exist - it asks MEF for all exports that implement IController. This returns an IEnumerable<Lazy<IController>> with one item for every class that implements IController in the bin/ folder (by default).
It then runs a linq query over the IEnumerable, calling GetType() on the Value property of each Lazy<IController>. Requesting the Value of a Lazy<T> forces the instance to be created. This is why every controller in the bin/ is being constructed for a page that doesn't exist.
I don't think this is an easy problem to fix properly as there is no way of getting the Type instance from Lazy<T>.Value without creating the value. However by removing the lines from AppStart_MefContribMVC3.cs that register the ControllerFactory with Asp.Net - you have effectively stopped using MefContrib.Web.Mvc's ControllerFactory and just used Asp.Net's DefaultControllerFactory instead.
Turns out that the SetControllerFactory method below is causing the issue:
// Tell MVC3 to use MEF as its dependency resolver.
var dependencyResolver = new CompositionDependencyResolver(catalog);
DependencyResolver.SetResolver(dependencyResolver);
// Tell MVC3 to resolve dependencies in controllers
ControllerBuilder.Current.SetControllerFactory(
new CompositionControllerFactory(
new CompositionControllerActivator(dependencyResolver)));
Commenting out the "Tell MVC3 to resolve dependencies in controllers" section fixes my issue, and no controllers except those I ask for get instantiated. Luckily, that's only needed if you're not using the standard Asp.Net controller resolution (and we are).
I created a MVC 2 Application to work as a RSS Feeder and deliver News Contents for a number of applications to consume.
Everything was doing fine until yesterday when suddenly my application started throwing a random error which doesn't tell me much of what's going on (or at least I don't understand it).
This error only occurs in Production and cannot be reproduced in staging or my local machine.
Here's the stack trace:
Error executing child request for handler
'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'.errorPath:/Android/Edition/2011-11-22/P1
HostIP:##.##.##.## at
System.Web.HttpServerUtility.ExecuteInternal(IHttpHandler handler,
TextWriter writer, Boolean preserveForm, Boolean setPreviousPage,
VirtualPath path, VirtualPath filePath, String physPath, Exception
error, String queryStringOverride) at
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter
writer, Boolean preserveForm, Boolean setPreviousPage) at
System.Web.HttpServerUtility.Execute(IHttpHandler handler, TextWriter
writer, Boolean preserveForm) at
System.Web.HttpServerUtilityWrapper.Execute(IHttpHandler handler,
TextWriter writer, Boolean preserveForm) at
System.Web.Mvc.ViewPage.RenderView(ViewContext viewContext) at
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context)
at System.Web.Mvc.ControllerActionInvoker.<>c_DisplayClass14.b_11()
at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter
filter, ResultExecutingContext preContext, Func1 continuation) at
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext
controllerContext, IList1 filters, ActionResult actionResult) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName) at
System.Web.Mvc.Controller.ExecuteCore() at
System.Web.Mvc.MvcHandler.<>c__DisplayClass8.b__4() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass1.b__0() at
System.Web.Mvc.Async.AsyncResultWrapper.<>c__DisplayClass81.b__7(IAsyncResult
_) at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End() at
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at
System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step,
Boolean& completedSynchronously)
This error only occurs sometimes and can throw at any action of any controller.
I would like to have found the reason in a specific action but it only throws sometimes and can throw for any action.
Such byzantine errors are hard to debug. The stack trace you're seeing does not help in diagnosing the error.
First, you should improve error logging. In your global.asax, create an implementation of the Application_Error hook that logs the exception and all inner exceptions to a file (I wouldn't log this to the database, because the db connection could be the culprit). Make sure that this code is solid: it should focus on these critical errors and not log every 404 page. Also, make sure that the logging code itself does not create any problems (it should be highly error tolerant).
The cause for this kind of problems is usually access to some kind of static variables. Out of all keywords, I believe static is by far the most dangerous one because it is so subtle.
Some common errors I've seen.
Caching Someone wanted to be smart and cache some data in a static dictionary or so. Unfortunately, the locking code is flawed. An exception occurs only if the code for some user tries to add sth. to the cache, but it's already there:
if(_dict.ContainsKey(cacheKey) == false)
{
// second thread adds data to the dictionary here
_dict.Add(cacheKey, cacheData); // exception
}
This can also happen in a 3rd party library that uses caching or pooling. Access static variables with care.
Uncommon Code Paths Something unusual happens that calls code that is not called very often, and that code is flawed. If you have testing with high code coverage, check the spots that are not covered by the tests.
DB Connection Lost A socket reset on the db connection could lead to exceptions. Many database connection libraries / drivers fix this quickly (i.e. the next request will be fine). This is hard to handle; basically it shouldn't happen but there are many reasons why it could occur.
This error tells you, that the true error is somewhere in some child action, that is action rendered by Html.RenderAction().
There is no such thing as "random" error - there has to be scenario where it happens, you just dont know it because the conditions vary maybe.
You should identify all your child actions, and test them with various inputs.. after you identify the problematic input set, try disabling child actions one by one and find the error this way.
I have an ASPNET MVC application that works fine locally but when I deployed it to production I get the following stack trace.
There are a few puzzling things about this stack trace, for one everything worked fine before i deployed my changes, for two the location of the code is wrong it's now on a production server not my dev machine and for three Rework is a controller method, not an object
2/28/2011 11:03:47 PM COB_Database.Controllers.ClaimsController Rework Object reference
not set to an instance of an object. at COB_Database.ViewModels.ErrorVM.
<>c__DisplayClass12.<.ctor>b__1(Error err) in
C:\Users\jperrine251\documents\visual studio 2010\Projects\COB Database\COB
Database\ViewModels\ErrorVM.cs:line 26 at
System.Linq.Enumerable.WhereEnumerableIterator`1.MoveNext() at
System.Collections.Generic.List`1..ctor(IEnumerable`1 collection) at
System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source) at
COB_Database.ViewModels.ErrorVM..ctor(User user, Claim claim, IEnumerable`1 actions,
IEnumerable`1 users, IEnumerable`1 referralReasons, Boolean editing) in
C:\Users\jperrine251\documents\visual studio 2010\Projects\COB Database\COB
Database\ViewModels\ErrorVM.cs:line 26 at
COB_Database.Controllers.ClaimsController.Rework(Int32 id) in
C:\Users\jperrine251\documents\visual studio 2010\Projects\COB Database\COB
Database\Controllers\ClaimsController.cs:line 160 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
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext
controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.
<InvokeActionMethodWithFilters>b__12() at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter,
ActionExecutingContext preContext, Func`1 continuation) at
System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass15.<>c__DisplayClass17.
<InvokeActionMethodWithFilters>b__14() at
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext
controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2
parameters) at
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext
controllerContext, String actionName)
Anyone have any ideas?
EDIT: The line in question in the stack trace is this
UsersErrors = claim.Errors.Where(err => err.UserID == user.id && err.ErrorActionID != null &&
err.ErrorActionLogs.OrderByDescending(eal => eal.id).FirstOrDefault().Timestamp >= DateTime.Now.AddHours(-10)).ToList();
And UsersErrors is defined as List<Error> UsersErrors
I tried changing the code to this but still no luck:
var userErrors = claim.Errors.Where(err => err.UserID == user.id && err.ErrorActionID != null &&
err.ErrorActionLogs.OrderByDescending(eal => eal.id).FirstOrDefault().Timestamp >= DateTime.Now.AddHours(-10));
UsersErrors = userErrors == null ? new List<Error>() : userErrors.ToList();
Edit, I've isolated the line causing the problem further, I took the above code and broke it down into predicates and passed those to my linq expression, the following is what is failing (but working locally)
Func<Error, bool> errorLogp =
(err) =>
err.ErrorActionLogs
.OrderByDescending(eal => eal.id)
.FirstOrDefault().Timestamp >= DateTime.Now.AddHours(-10);
Errors have a log of actions taken on them, this is just grabbing the most recent and ensuring it was done in the last 10 hours, I've checked the database for the record i'm testing on and it is present along with an error action log that meets the requirements
EDIT: Also to ensure that claim.Errors isn't null I've done the following
UsersErrors = Claim.Errors == null ?
new List<Error>() :
Claim.Errors.Where(err => errorp(err) && errorLogp(err)).ToList();
but the code still bombs out at the errorLogp predicate Func
Are you jperrine251? If that's not you, your code isn't running on the server. From what I can tell it looks like your error handling code is making some assumptions that don't hold in production and the whole thing is bombing out. Be very defensive in your error handling.
Posting applicable code from ErrorVM and ClaimsController would be helpful too.
A few things to consider:
The location of the code is from the PDB (symbol) files that you compiled on your machine. It doesn't update when you deploy to a different environment. The location does give you an exact line number to investigate though, which is good. (For future production releases, you will want to compile your code in release mode and not debug mode.)
The exception message is "Object reference not set to an instance of an object." This exception isn't telling you that Rework is an object, but that during the rework action a NullReferenceException was thrown. Somewhere on line 26 of ErrorVM.cs you have a variable that is null and you're trying to access one of its members.
The location is where the code was compiled and therefore it's normal that it has your development path (not the production box since the source code was never on that box)
As far as the error it looks like you have a null reference inside the ErrorVM
ViewModels\ErrorVM.cs:line 26 at
It might be that the original error is being composed during the process of displaying the error view (?)
I found the problem, looks like there was some data missing from the database that was expected to be there, thanks for all the help everyone
I get the following error randomly when running an ASP.NET MVC 2 project. This error occurs on different pages at different times. Cannot reproduce this error or identify pattern of when and on which page the error occurs.
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
It happens on different pages
Example: (Trying to view a partial view)
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at ASP.views_shared_searchcontrol_ascx.__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)
Another Example (While building sitemap, sitemap code omitted)
System.Web.HttpException: Error executing child request for handler 'System.Web.Mvc.HttpHandlerUtil+ServerExecuteHttpHandlerWrapper'. ---> System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
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)
--- End of inner exception stack trace ---
at System.Web.UI.Page.HandleError(Exception e)
I was having this problem. For me it turned out I had strongly typed my master page to be of a certain type and in some scenarios I was returning a model that was not of that type and that is what was causing this error.
I'm baffled. My site randomly throws the following error:
System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: The partial view '/SiteUserMenu' could not be found. The following locations were searched:
/SiteUserMenu
at System.Web.Mvc.HtmlHelper.FindPartialView(ViewContext viewContext, String partialViewName, ViewEngineCollection viewEngineCollection)
at System.Web.Mvc.HtmlHelper.RenderPartialInternal(String partialViewName, ViewDataDictionary viewData, Object model, ViewEngineCollection viewEngineCollection)
at System.Web.Mvc.Html.RenderPartialExtensions.RenderPartial(HtmlHelper htmlHelper, String partialViewName)
at ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer)
Most of the time, the site runs fine... sometimes it throws the above error, which makes no sense to me. If the partial view wasn't found, why would it not be able to find it sometimes?
The partial view is saved in a folder named "en" under the Shared folder (inside of the views folder). Here's how I render the view:
<% Html.RenderPartial(ViewData["lang"] + "/SiteUserMenu"); %>
ViewData["lang"] is set in my base controller, in the OnActionExecuting action, like so:
var l = (RouteData.Values["language"] != null) ? RouteData.Values["language"].ToString() : string.Empty;
if (string.IsNullOrEmpty(l))
l = "en";
if (l.Contains("en"))
{
IsEnglish = true;
l = "en";
}
else
l = "ja";
ViewData["lang"] = l.ToLower();
Language = l.ToLower();
Language and IsEnglish are properties of the base controller. The whole site uses them to maintain language selection and to make appropriate choices based on language. If language is not set, it will be set to "en". So ViewData["lang"] should always be available to my views.
Any reason why a partial view couldn't be found somtimes, while most of the time (I'm talking 90% of the time) it works fine?
As the error points to 'The partial view '/SiteUserMenu' could not be found.' you can see that its not picking up the 'en'. I would suggest that the best place to start debugging is the ViewData["lang"]. See if you can produce steps to replicate the error everytime, then debug into your solution to see if ViewData["lang"] has been set whilst you are in the erroring Action method of your Controller.