Checkbox Helper: Odd string to bool conversion error - asp.net

I've a web using asp.net MVC 3 with razor.
In one view I'm having an odd error with the checkbox helper.
Here is the razor code:
#Html.CheckBox("rememberPassword", Model.RememberPassword, new { tabindex = "4", style = "width:15px" })
The property in the model (which I set to true in the Model constructor):
public bool RememberPassword { get; set; }
And the logged error:
2012-04-13 01:20:33.334 [13 ] Error - Reference: 0413-012033-334 - Global site error, page: /es/login
System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information. ---> System.FormatException: -1' is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.
at System.Boolean.Parse(String value)
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
--- End of inner exception stack trace ---
at System.ComponentModel.BooleanConverter.ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, Object value)
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
--- End of inner exception stack trace ---
at System.Web.Mvc.ValueProviderResult.ConvertSimpleType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.UnwrapPossibleArrayType(CultureInfo culture, Object value, Type destinationType)
at System.Web.Mvc.ValueProviderResult.ConvertTo(Type type, CultureInfo culture)
at System.Web.Mvc.HtmlHelper.GetModelStateValue(String key, Type destinationType)
at System.Web.Mvc.Html.InputExtensions.InputHelper(HtmlHelper htmlHelper, InputType inputType, ModelMetadata metadata, String name, Object value, Boolean useViewData, Boolean isChecked, Boolean setId, Boolean isExplicitValue, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBoxHelper(HtmlHelper htmlHelper, ModelMetadata metadata, String name, Nullable`1 isChecked, IDictionary`2 htmlAttributes)
at System.Web.Mvc.Html.InputExtensions.CheckBox(HtmlHelper htmlHelper, String name, Boolean isChecked, Object htmlAttributes)
at ASP._Page_Views_Login_Index_cshtml.Execute() in d:\[...]\Views\Login\Index.cshtml:line 49
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__DisplayClass1c.<InvokeActionResultWithFilters>b__19()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilter(IResultFilter filter, ResultExecutingContext preContext, Func`1 continuation)
at System.Web.Mvc.ControllerActionInvoker.<>c__DisplayClass1c.<>c__DisplayClass1e.<InvokeActionResultWithFilters>b__1b()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult)
at System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName)
Why is this happening?
Note:
It keeps getting odder and odder. As magically as the error started appearing (in a productive site some day without any updates or releases) not it has stopped. It's been three days without the error. However, I'd still like to know why was it.

It had nothing to do with the way of creating the checkbox. In some very odd scenarios (which I had forgotten at all), this forms may be submitted (from other sites) without this parameter. In this cases the bool field was trying to obtained from the string "-1".
One way of resolving this issue (that I have discovered to be a good practice) is to avoid "not-nullable" fields in the Model.

Just try this instead
Html.CheckBoxFor(model => model.RememberPassword , chkHtmlAttributes)
And define the chkHtmlAttributes to these
tabindex = "4", style = "width:15px"

Related

Deserialization of DbGeography Entity Framework

I have a class Event with a property of the type DbGeography.
public class Event
{
public long Id { get; set; }
public DateTime Date { get; set; }
public DbGeography Location { get; set; }
}
In the class DatabaseHelper I try to load data from a server.
public async Task<IEnumerable<Event>> GetEventsAsync()
{
var uri = new Uri(string.Format(Constants.EventsUrl, string.Empty));
var content = await _client.GetStringAsync(uri);
IEnumerable<Event> events = JsonConvert.DeserializeObject<List<Event>>(content);
return events;
}
But an error is thrown:
Newtonsoft.Json.JsonSerializationException: Error getting value from 'WellKnownValue' on 'System.Data.Entity.Spatial.DbGeography'.
I did found out that I should use a custom JsonConverter.
// DbGeographyConverter.cs
public class DbGeographyConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return objectType.IsAssignableFrom(typeof(string));
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
JObject location = JObject.Load(reader);
JToken token = location["Geography"]["WellKnownText"];
string value = token.ToString();
System.Data.Entity.Spatial.DbGeography converted = System.Data.Entity.Spatial.DbGeography.PointFromText(value, 4326);
return converted;
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
// Base serialization is fine
serializer.Serialize(writer, value);
}
}
But when calling http://localhost:57609/api/events, which returns list of Event objects, the following error is thrown:
{"Message":"An error has occurred.","ExceptionMessage":"The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.","ExceptionType":"System.InvalidOperationException","StackTrace":null,"InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Error while copying content to a stream.","ExceptionType":"System.Net.Http.HttpRequestException","StackTrace":" at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.WebHost.HttpControllerHandler.<WriteBufferedResponseContentAsync>d__1b.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)","ExceptionType":"System.IO.FileLoadException","StackTrace":" at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly, RuntimeModule decoratedModule, MetadataToken decoratedToken, RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[] attributes, IList derivedAttributes, RuntimeType& attributeType, IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean& isVarArg)
at System.Reflection.CustomAttribute.IsCustomAttributeDefined(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, RuntimeType attributeFilterType, Int32 attributeCtorToken, Boolean mustBeInheritable)
at System.Reflection.CustomAttribute.IsDefined(RuntimePropertyInfo property, RuntimeType caType)
at System.Reflection.RuntimePropertyInfo.IsDefined(Type attributeType, Boolean inherit)
at Newtonsoft.Json.Serialization.DefaultContractResolver.GetSerializableMembers(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateProperties(Type type, MemberSerialization memberSerialization)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateObjectContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.CreateContract(Type objectType)
at Newtonsoft.Json.Serialization.DefaultContractResolver.ResolveContract(Type type)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.WriteStartArray(JsonWriter writer, Object values, JsonArrayContract contract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeList(JsonWriter writer, IEnumerable values, JsonArrayContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeValue(JsonWriter writer, Object value, JsonContract valueContract, JsonProperty member, JsonContainerContract containerContract, JsonProperty containerProperty)
at Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.Serialize(JsonWriter jsonWriter, Object value, Type objectType)
at Newtonsoft.Json.JsonSerializer.SerializeInternal(JsonWriter jsonWriter, Object value, Type objectType)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
at System.Net.Http.Formatting.JsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, Encoding effectiveEncoding)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStream(Type type, Object value, Stream writeStream, HttpContent content)
at System.Net.Http.Formatting.BaseJsonMediaTypeFormatter.WriteToStreamAsync(Type type, Object value, Stream writeStream, HttpContent content, TransportContext transportContext, CancellationToken cancellationToken)"}}}
What could be the problem?
Problem is you are referencing Newtonsoft.Json 10.0.0.0
Could not load file or assembly 'Newtonsoft.Json, Version=10.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference.
It seems version 10.0.0.0 is no longer available on NuGet servers, thus you can't have it locally. No where to download from. Try to update/install existing version. It might work then.
Install-Package Newtonsoft.Json -Version 10.0.3

IIS Breaks application after recycle

I recently have this strange issue with IIS. We have an ASP.NET website and recently it fails after an application pool recycle. When I stop the applicationpool, clear the "ASP.NET Temporary Files" and restart the applicationpool. It works again. When i manually recycle it, it breaks again. I can reproduce this every time. The big problem is that our web application recycles every night.
Can I in some way prevent the usage of these ASP.NET Temporary Files? Or how could i fix this issue.
[Edit]
this is a screenshot of the error:
Screenshot
[Edit 2:Full error page]
Server Error in 'WebSite' Application.
Could not load type from string value 'MyOwnClass'.
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.TypeLoadException: Could not load type from string value 'MyOwnClass'.
Source Error:
Line 120: private static void InitalizeApplicationContext()
Line 121: {
Line 122: Spring.Context.Support.ContextRegistry.GetContext();
Line 123: }
Line 124:
Source File: path-to-website\Global.asax Line: 122
Stack Trace:
[TypeLoadException: Could not load type from string value 'MyOwnClass'.]
Spring.Core.TypeResolution.TypeResolver.Resolve(String typeName) +240
Spring.Core.TypeResolution.GenericTypeResolver.Resolve(String typeName) +530
Spring.Core.TypeResolution.CachedTypeResolver.Resolve(String typeName) +411
Spring.Core.TypeResolution.TypeResolutionUtils.ResolveType(String typeName) +85
Spring.Objects.Factory.Support.AbstractObjectDefinition.ResolveObjectType() +39
Spring.Objects.Factory.Support.AbstractObjectFactory.ResolveObjectType(RootObjectDefinition rod, String objectName) +74
[CannotLoadObjectTypeException: Cannot resolve type [MyOwnClass] for object with name 'AuthenticationUtil' defined in file [path-to-website\spring\Utils.xml] line 5]
Spring.Objects.Factory.Support.AbstractObjectFactory.ResolveObjectType(RootObjectDefinition rod, String objectName) +180
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.PredictObjectType(String objectName, RootObjectDefinition mod) +108
Spring.Objects.Factory.Support.DefaultListableObjectFactory.DoGetObjectNamesForType(Type type, Boolean includeNonSingletons, Boolean allowEagerInit) +879
Spring.Objects.Factory.Support.DefaultListableObjectFactory.GetObjectsOfType(Type type, Boolean includePrototypes, Boolean includeFactoryObjects) +99
Spring.Context.Support.AbstractApplicationContext.GetObjectsOfType(Type type) +51
Spring.Messaging.Core.MessageQueueMetadataCache.Initialize() +78
Spring.Messaging.Core.MessageQueueTemplate.CreateDefaultMetadataCache() +253
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InvokeInitMethods(Object target, String name, IConfigurableObjectDefinition definition) +250
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.ConfigureObject(String name, RootObjectDefinition definition, IObjectWrapper wrapper) +740
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +637
[ObjectCreationException: Error thrown by a dependency of object 'AddExamSessionToQueueCommand' defined in 'file [path-to-website\spring\Commands.xml] line 22' : Initialization of object failed : Cannot resolve type [MyOwnClass] for object with name 'AuthenticationUtil' defined in file [path-to-website\spring\Utils.xml] line 5
while resolving 'constructor argument with index 0' to 'MsmqExamSessionAccessCodeService' defined in 'file [path-to-website\spring\Services.xml] line 23'
while resolving 'MessageQueueTemplate' to 'ExamSessionAccessCodeMessageQueueTemplate' defined in 'file [path-to-website\spring\MsmqMessageQueueTemplates.xml] line 18']
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveReference(IObjectDefinition definition, String name, String argumentName, RuntimeObjectReference reference) +585
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolvePropertyValue(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +429
Spring.Objects.Factory.Support.ObjectDefinitionValueResolver.ResolveValueIfNecessary(String name, IObjectDefinition definition, String argumentName, Object argumentValue) +19
Spring.Objects.Factory.Support.ConstructorResolver.ResolveConstructorArguments(String objectName, RootObjectDefinition definition, ObjectWrapper wrapper, ConstructorArgumentValues cargs, ConstructorArgumentValues resolvedValues) +327
Spring.Objects.Factory.Support.ConstructorResolver.GetConstructorInstantiationInfo(String objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, Object[] explicitArgs) +263
Spring.Objects.Factory.Support.ConstructorResolver.AutowireConstructor(String objectName, RootObjectDefinition rod, ConstructorInfo[] chosenCtors, Object[] explicitArgs) +80
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.CreateObjectInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +216
Spring.Objects.Factory.Support.AbstractAutowireCapableObjectFactory.InstantiateObject(String name, RootObjectDefinition definition, Object[] arguments, Boolean allowEagerCaching, Boolean suppressConfigure) +863
Spring.Objects.Factory.Support.AbstractObjectFactory.CreateAndCacheSingletonInstance(String objectName, RootObjectDefinition objectDefinition, Object[] arguments) +379
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) +1744
Spring.Objects.Factory.Support.DefaultListableObjectFactory.PreInstantiateSingletons() +722
Spring.Context.Support.AbstractApplicationContext.Refresh() +1009
Spring.Context.Support.XmlApplicationContext..ctor(XmlApplicationContextArgs args) +206
_dynamic_Spring.Context.Support.XmlApplicationContext..ctor(Object[] ) +320
Spring.Context.Support.RootContextInstantiator.InvokeContextConstructor(ConstructorInfo ctor) +169
Spring.Context.Support.ContextInstantiator.InstantiateContext() +55
Spring.Context.Support.ContextHandler.InstantiateContext(IApplicationContext parentContext, Object configContext, String contextName, Type contextType, Boolean caseSensitive, String[] resources) +174
Spring.Context.Support.ContextHandler.Create(Object parent, Object configContext, XmlNode section) +476
[ConfigurationErrorsException: Error creating context 'spring.root': Could not load type from string value 'MyOwnClass'.]
System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult) +278
System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject) +2095
System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) +2023
System.Configuration.BaseConfigurationRecord.GetSection(String configKey) +79
System.Configuration.ConfigurationManager.GetSection(String sectionName) +91
Spring.Util.ConfigurationUtils.GetSection(String sectionName) +100
Spring.Context.Support.ContextRegistry.InitializeContextIfNeeded() +68
Spring.Context.Support.ContextRegistry.GetContext() +83
ASP.global_asax.InitalizeApplicationContext() in path-to-website\Global.asax:122
ASP.global_asax.Application_Start(Object sender, EventArgs e) in path-to-website\Global.asax:20
[HttpException (0x80004005): Error creating context 'spring.root': Could not load type from string value 'MyOwnClass'.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +540
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343
[HttpException (0x80004005): Error creating context 'spring.root': Could not load type from string value 'MyOwnClass'.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +539
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +125
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +731
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.1590.0

Controller Action ambiguity even with [HttpPost] attribute? (ASP.NET MVC4)

So I have a "Register" view (that maps to a RegisterController), which is a simple form for people to register in my service. Given that the form's method is POST, then I can name both actions of the controller (the one that shows the form, and the one that receives its submission) the same name, but discriminate them via the [HttpPost] attribute, this way:
open System
open System.Web
open System.Web.Mvc
open System.Net
open System.Threading
open System.Configuration
[<HandleError>]
type RegisterController() =
inherit Controller()
member this.Index (guid: string) =
let model = new RegisterModel(guid)
this.View("Register", model) :> ActionResult
[<HttpPost>]
member this.Index
(guid: string, password: string, passwordRetry: string) =
if not (password.Equals(passwordRetry)) then
raise(new Exception("Passwords must be the same"))
WebDbAccess.SetNewPassword guid password
RedirectResult("/") :> ActionResult
This works perfectly.
However, I just tried to use this same technique in the Home view of my app (for the Login functionality), and it doesn't work! It throws this:
The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController
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.Reflection.AmbiguousMatchException: The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController
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:
[AmbiguousMatchException: The current request for action 'Index' on controller type 'HomeController' is ambiguous between the following action methods:
System.Web.Mvc.ActionResult Index(System.String, System.String) on type FsWeb.Controllers.HomeController
System.Web.Mvc.ActionResult Index() on type FsWeb.Controllers.HomeController]
System.Web.Mvc.Async.AsyncActionMethodSelector.FindAction(ControllerContext controllerContext, String actionName) +495852
System.Web.Mvc.Async.ReflectedAsyncControllerDescriptor.FindAction(ControllerContext controllerContext, String actionName) +57
System.Web.Mvc.ControllerActionInvoker.FindAction(ControllerContext controllerContext, ControllerDescriptor controllerDescriptor, String actionName) +16
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +114
System.Web.Mvc.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState) +30
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +382
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +317
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +15
System.Web.Mvc.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState) +71
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +249
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() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17929
What's the difference between the 2 cases? I don't get it.
The HomeController's implementation is:
open System
open System.Web
open System.Web.Http
[<HandleError>]
type HomeController() =
inherit Controller()
[<HttpGet>]
member this.Index () =
this.View() :> ActionResult
[<HttpPost>]
member this.Index
(id:string, password:string) =
if (UserIsValid id password) then
RedirectResult("lobby") :> ActionResult
RedirectResult("loginError") :> ActionResult
#nemesv was right, I had to fully qualify HttpPost with System.Web.Mvc.HttpPost because otherwise it would use System.Web.Http.HttpPost!!

.Net Null Reference Exception in DocumentXPathNavigator

I've run into an interesting exception. On one of my production servers, occasionally I'll get the following exception.
System.NullReferenceException: Object reference not set to an instance of an object.
at System.Xml.DocumentXPathNavigator.get_NameTable()
at System.Xml.Xsl.Runtime.XmlQueryContext.get_DefaultNameTable()
at System.Xml.Xsl.Runtime.XmlQueryRuntime..ctor(XmlQueryStaticData data, Object defaultDataSource, XmlResolver dataSources, XsltArgumentList argList, XmlSequenceWriter seqWrt)
at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlSequenceWriter results)
at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer, Boolean closeWriter)
at System.Xml.Xsl.XmlILCommand.Execute(IXPathNavigable contextDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter results)
at System.Xml.Xsl.XslCompiledTransform.Transform(IXPathNavigable input, XsltArgumentList arguments, TextWriter results)
at sftControls.SearchListLandingPage.getHtml(IXPathNavigable document, String Xsl, String headerLinks)
Opening up the IL and looking through each method suggests that the DocumentXPathNavigator => this.document is null. What's strange is that I can in no way duplicate this issue locally or on our test servers.
A little background, and this might be the key...
This is a web application(running .Net 3.5) that caches the XmlDocument that gets passed into XslCompiledTransform.Transform(). Our caching is serviced through a distributed cache server. The XmlDocument is serialized and cached so a reference to the specific object should not continue to exist. That leads me to believe that either something is explicitly preventing this.document from ever being set when the implicit XmlDocument -> DocumentXPathNavigator happens or some reference somewhere is removed while the Transform() is running. Either way I am perplexed.
So, I guess my questions are:
Has anyone else seen this before?
Does anyone know what could be causing it or how to deal with it?
Thanks
EDIT:
After further thinking about this, the only thing that would make sense is that it's a race condition. The caching appliance is somehow expiring the object while the application is using the object.
EDIT/EDIT:
.Net 3.5, the assembilies being referenced above are 2.0
In case anyone has this same exception.
We found that this exception occurs when xmldocument.HasChildNodes is false or DocumentElement is null. Verifying that the document has elements, BEFORE querying on it, resolves this.
I experienced a very similar exception inside an XslCompiledTransform:
System.Web.HttpUnhandledException (0x80004005): Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at MS.Internal.Xml.Cache.XPathDocumentNavigator.get_NodeType()
at System.Xml.XPath.XPathNavigator.MoveToNonDescendant()
at System.Xml.Xsl.Runtime.DescendantMergeIterator.MoveNext(XPathNavigator input)
at <xsl:template name="SystemPartIncluded">(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, IList`1 PartNumber, XPathNavigator Description, IList`1 DescriptionOverride, IList`1 Quantity, IList`1 ExtendedPrice, String LabelWhiteSpace)
at <xsl:template name="compiler:generated"> (30)(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current, XPathNavigator isBundledWithCanvas, XPathNavigator SoftwareExtendedPrice, XPathNavigator SoftwareUnitPrice, IList`1 PixelNet, IList`1 Revision_Date, IList`1 Catalyst)
at <xsl:template name="compiler:generated"> (45)(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current, XPathNavigator SoftwareUnitPrice, XPathNavigator HardwareExtendedPrice, XPathNavigator HardwareUnitPrice, XPathNavigator PixelNetUnitPrice, XPathNavigator FusionUnitPrice)
at <xsl:template match="Quote">(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current, Double {urn:schemas-microsoft-com:xslt-debug}position, Double {urn:schemas-microsoft-com:xslt-debug}last)
at <xsl:template match="/">(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime, XPathNavigator {urn:schemas-microsoft-com:xslt-debug}current)
at Root(XmlQueryRuntime {urn:schemas-microsoft-com:xslt-debug}runtime)
at System.Xml.Xsl.XmlILCommand.Execute(Object defaultDocument, XmlResolver dataSources, XsltArgumentList argumentList, XmlWriter writer)
at MyApp.clsXML.XslTransformationToHtml(IQEntities DC, Int32 loggedOnUserID, IXPathNavigable input, String xslStylesheetFilePath, XsltArgumentList xslArgs, String XmlRepositoryVersion) in MyApp\App_Data\Static Classes\xml_routines.cs:line 510
at MyApp.clsQuote.RenderOneQuote(IQEntities DC, Int32 loggedOnUserID, Int32 quoteID, Boolean booPrintFormat, Boolean booDiscount_Prices, Boolean booIs_Super_Administrator, Boolean isHostRep, String strOrganization_Table_Caption, Boolean showBottomLineOnly) in MyApp\App_Data\Static Classes\quote_routines.cs:line 476
at MyApp.Pages.AJAX.BrowseQuotes.RenderSelectedQuote(Int32 quoteID) in MyApp\Pages\AJAX\BrowseQuotes.aspx.cs:line 66
at MyApp.Pages.AJAX.BrowseQuotes.ucQuotePicker1_OnQuoteSelectedEvent(Object sender, Int32 quoteID) in b:\DotNet\IQ\WinMetrics.IQ\Pages\AJAX\BrowseQuotes.aspx.cs:line 56
at System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.HandleError(Exception e)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
at System.Web.UI.Page.ProcessRequest()
at System.Web.UI.Page.ProcessRequest(HttpContext context)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Like you, we were passing an XPathDocument to the Xsl transform and the XPathDocument was being retrieved from distributed cache. Unfortunately, an XPathDocument is not serializable and therefore unusable after it is retrieved from the distributed cache. We fixed the problem by using an XmlDocument instead of an XPathDocument and using SerializedXmlDocument to serialize and deserialize it as follows:
public static XmlDocument CachedXmlDoc
{
get
{
lock (_locker)
{
// maintain the Part XmlDocument in the distributed cache so that it can be reset from any production instance
SerializedXmlDocument serializedXmlDoc = Reliable.Application[Global.CACHED_XML_DOC] as SerializedXmlDocument;
XmlDocument cachedDoc = (serializedXmlDoc == null) ? null : serializedXmlDoc.XmlDocument;
if (cachedDoc == null)
{
cachedDoc = myController.CreateXmlDoc();
Reliable.Application[Global.CACHED_XML_DOC] = new SerializedXmlDocument(cachedDoc);
}
return cachedDoc;
}
}
set
{
lock (_locker)
{
if (value == null)
{
Reliable.Application[Global.CACHED_XML_DOC] = null;
}
else
{
throw new Exception("Tried to set the cached XmlDocument to something other than null.");
}
}
}
}

ErrorMessageResourceName and ErrorMessage cannot both be set, but I'm only setting one

This is the error I'm getting using MVC2:
Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.
It is coming from the [Required] Validation DataAnnotation.
Stack trace:
InvalidOperationException: Either ErrorMessageString or ErrorMessageResourceName must be set, but not both.]
System.ComponentModel.DataAnnotations.ValidationAttribute.SetupResourceAccessor() +89338
System.ComponentModel.DataAnnotations.ValidationAttribute.FormatErrorMessage(String name) +38
System.Web.Mvc.<Validate>d__1.MoveNext() +215
System.Web.Mvc.<Validate>d__5.MoveNext() +735
System.Web.Mvc.DefaultModelBinder.OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) +424
System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +732
System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +475
System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +152
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
I've boiled my view model down to this(it breaks any time there is a [Required] attribute, works fine without):
[Required(ErrorMessage = "")]
[DataType(DataType.Text)]
[DisplayName("Property Name")]
public string MyProperty { get; set; }
My controller returns an empty ViewModel, and the form in the view is completely blank...just a submit button.
In my case, I have write ErrorMessage = null, example :
[EmailAddress(ErrorMessageResourceName = "FORM_FIELD_VALIDATION_EMAIL", ErrorMessageResourceType = typeof(App_GlobalResources.Common.View_Common_Forms), ErrorMessage = null)]
ErrorMessage = " " don't work.
The problem lies in setting the ErrorMessage to a blank string. I would have to assume that at some point there is a check for String.Empty in the MVC code that is causing problems.
Setting the ErrorMessage to " "(one space) solved the issue.
My guess is [DataType(DataType.Text)] has a validation message defined in resources (in System.ComponentModel.DataAnnotations.Resources) and the existence of that and your [Required] is causing this InvalidOperationException. Try Removing [DataType] or [Required] and see if the exception goes away.
I had a simmilar issue with a custom ValidationAttribute.
In the IsValid method I was setting the ErrorMessage. The fix was to remove the assignation to the ErrorMessage propety...
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
//code before ...
this.ErrorMessage = this.FormatErrorMessage(validationContext.DisplayName); //NOT GOOD...
ValidationResult validationResult = new ValidationResult(this.ErrorMessage, //And using the ErrorMessage Here...
new[] { validationContext.MemberName });
return validationResult;
}
I was writting Unit test and they were pasisng only if i was running/debugging one by one. But when I click "Run All", only the first one was passing? They are not Linked in any ways...
I also tried https://stackoverflow.com/a/20848920/4798459
Didn't work either.
So yeah, the fix was to remove the assignation to the ErrorMessage propety!

Resources