Ajax POST to MVC4 with special characters '&#' does not work [duplicate] - asp.net-mvc-4

This question already has answers here:
A potentially dangerous Request.Form value was detected from the client - ASP.NET MVC
(5 answers)
Closed 9 years ago.
Ajax POST data that contains '&#' characters causes MVC4 controller fails to decode. Following were my tests;
POST data contains 'MYNAMEIS&#XYZ' , result ERROR
POST data contains 'MYNAMEIS& #XYZ' (note the space), result SUCCESS
POST data contains 'MYNAMEIS#&XYZ' (note the order of special characters), result
SUCCESS
POST data contains 'Q&^%AA#####$%' (note bunch of special
characters), result SUCCESS
It doesn't work when # comes right after & in the POST request. I've verified that request encoding is set to UTF-8 in web.config, _layout.cshtml . But still no luck.
Please help how to resolve this issue.
Stack Trace from the exception;
<!--
[HttpRequestValidationException]: A potentially dangerous Request.Form value was detected from the client (Name="&#").
at System.Web.HttpRequest.ValidateString(String value, String collectionKey, RequestValidationSource requestCollection)
at System.Web.HttpRequest.<>c__DisplayClass5.<ValidateHttpValueCollection>b__3(String key, String value)
at System.Web.HttpValueCollection.EnsureKeyValidated(String key)
at System.Web.HttpValueCollection.GetValues(String name)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.GetResultFromCollection(String key, NameValueCollection collection, CultureInfo culture)
at System.Web.Mvc.NameValueCollectionValueProvider.ValueProviderResultPlaceholder.<>c__DisplayClass8.<.ctor>b__4()
at System.Lazy`1.CreateValue()
at System.Lazy`1.LazyInitValue()
at System.Lazy`1.get_Value()
at System.Web.Mvc.NameValueCollectionValueProvider.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.GetValueFromProvider(IValueProvider provider, String key, Boolean skipValidation)
at System.Web.Mvc.ValueProviderCollection.<>c__DisplayClass9.<GetValue>b__4(IValueProvider provider)
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at System.Web.Mvc.ValueProviderCollection.GetValue(String key, Boolean skipValidation)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder)
at System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor)
at System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model)
at System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor)
at System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.<>c__DisplayClass1d.<BeginExecuteCore>b__17(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.<>c__DisplayClass8.<BeginProcessRequest>b__2(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

Use the ValidateInput(false) attribute.
You can also encode the &# characters and then decode them on the server.

Related

Ninject not proving params to my Controller, after doing mass update with NuGet

I have an MVC4 project in which I use Ninject. I just use the Ninject MVC3-provided NinjectWebCommon.cs file, in the App_Start folder. I just performed a mass dependency update, with NuGet, without realizing how much trouble it might cause. It broke my Ninject setup, somehow. Prior to running the NuGet update, Ninject would properly create my controllers and provide them with the required constructor params. Now, after the update, I get the following error:
[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, StackCrawlMark& stackMark) +113
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +110
[InvalidOperationException: An error occurred when trying to create a controller of type 'Portal.Web.Controllers.MatterController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +226
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
The code inside of the NinjectWebCommon.cs file is being executed still, though. I can place breakpoints on it, and watch it apply my bindings. I don't think MVC is using it when creating controllers anymore, though.
Does anybody have any idea what might have been broken by this NuGet update?

NHibernate Image Storage - The length of the byte[] value exceeds the length configured

I am using Fluent NHibernate and am trying to store an image. Small images work, but larger images do not, and I receive this error when saving to the database (SQL Server):
Exception: Error dehydrating property value for CFC.Domain.Vehicle.Image
Inner Exception: The length of the byte[] value exceeds the length configured in the mapping/parameter.
Here is my mapping:
mapping.Table("Vehicle");
mapping.Id(x => x.Id, "VehicleID");
mapping.Map(x => x.Year).Not.Nullable();
mapping.Map(x => x.Image).CustomSqlType("VARBINARY(MAX)").Length(int.MaxValue);
The "Image" property is a byte[].
Note the CustomSqlType and the length, which creates the proper nvarchar(max) column in the database. I've read countless of other posts talking about similar issues, but none cover this specific error. It isn't that the data is being truncated and then saved, it just errors out before ever sending the SQL query.
The image I am testing with is just the standard Windows 7 sample images (Penguins.jpg of course) but an image around 1kb works fine.
I appreciate the help! Here is the beginning of the stack trace if it helps.
[HibernateException: The length of the byte[] value exceeds the length
configured in the mapping/parameter.]
NHibernate.Type.AbstractBinaryType.Set(IDbCommand cmd, Object value,
Int32 index) +207
NHibernate.Type.NullableType.NullSafeSet(IDbCommand cmd, Object value,
Int32 index) +397
NHibernate.Type.NullableType.NullSafeSet(IDbCommand st, Object value,
Int32 index, Boolean[] settable, ISessionImplementor session) +62
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Object rowId, Boolean[] includeProperty,
Boolean[][] includeColumns, Int32 table, IDbCommand statement,
ISessionImplementor session, Int32 index) +350
[PropertyValueException: Error dehydrating property value for
CFC.Domain.Vehicle.Image]
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Object rowId, Boolean[] includeProperty,
Boolean[][] includeColumns, Int32 table, IDbCommand statement,
ISessionImplementor session, Int32 index) +510
NHibernate.Persister.Entity.AbstractEntityPersister.Dehydrate(Object
id, Object[] fields, Boolean[] includeProperty, Boolean[][]
includeColumns, Int32 j, IDbCommand st, ISessionImplementor session)
+59 NHibernate.Persister.Entity.GeneratedIdentifierBinder.BindValues(IDbCommand
ps) +79
NHibernate.Id.Insert.AbstractReturningDelegate.PerformInsert(SqlCommandInfo
insertSQL, ISessionImplementor session, IBinder binder) +102
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[]
fields, Boolean[] notNull, SqlCommandInfo sql, Object obj,
ISessionImplementor session) +265
NHibernate.Persister.Entity.AbstractEntityPersister.Insert(Object[]
fields, Object obj, ISessionImplementor session) +358
NHibernate.Action.EntityIdentityInsertAction.Execute() +262
NHibernate.Engine.ActionQueue.Execute(IExecutable executable) +56
NHibernate.Event.Default.AbstractSaveEventListener.PerformSaveOrReplicate(Object
entity, EntityKey key, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess) +811
NHibernate.Event.Default.AbstractSaveEventListener.PerformSave(Object
entity, Object id, IEntityPersister persister, Boolean
useIdentityColumn, Object anything, IEventSource source, Boolean
requiresImmediateIdAccess) +543
NHibernate.Event.Default.AbstractSaveEventListener.SaveWithGeneratedId(Object
entity, String entityName, Object anything, IEventSource source,
Boolean requiresImmediateIdAccess) +257
I know it's a little late to be posting a reply but I just came across this exact same error. Below was my resolution - hopefully it helps someone else in the future.
I changed:
Map(x => x.ByteArrayProperty);
to:
Map(x => x.ByteArrayProperty).Length(int.MaxValue);
Sigh, sometimes after 2 days of research you just have to post a question to StackOverflow to find the answer right after.
I'm not sure of the underlying reason, but specifying the property directly when mapping was the problem. To resolve the issue I ended up creating a new "BinaryLengthConvention" below.
public class BinaryColumnLengthConvention : IPropertyConvention, IPropertyConventionAcceptance
{
public void Accept(IAcceptanceCriteria<IPropertyInspector> criteria)
{
criteria.Expect(x => x.Property.PropertyType == typeof(byte[]));
}
public void Apply(IPropertyInstance instance)
{
instance.Length(2147483647);
instance.CustomSqlType("varbinary(MAX)");
}
}
Magically it all started working. Hopefully someone else that searches for that error message finds this useful.
I got the same error while storing the big images. I resolved by adding length attribute to image field as <property name="image" length="2147483647"/>

System.Data.SQLite type affinity int in string column

From what I've read about SQLite it has a feature called Type Affinity which means that data types are not strictly enforced (More info here).
I am reading from a database created in another application using POCO objects with EF4.1, the problem arises when a supposedly string field has an integer in it. I could understand an exception being thrown if an int field had a non-numeric string in it... but why would this screw up my app?
This is a sample of my test code, I've removed everything else until I was left with the bare minimum of code that makes this pop up.
Public Class TVSerie
Public Property Id As Integer
Public Property PrettyName As String
End Class
Public Class TVSeriesDb
Inherits DbContext
Public Property TVSeries As DbSet(Of TVSerie)
End Class
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Dim db As New TVSeriesDb
Dim sb As New StringBuilder
Dim series = db.TVSeries.Where(Function(c) c.PrettyName.Length > 0)
For Each s In series
sb.Append(s.Id & "-" & s.PrettyName & "<br/>")
Next
Return Content(sb.ToString)
End Function
End Class
The error is popping up in the "PrettyName" column with the TVSeries 24:
[InvalidCastException: Specified cast is not valid.]
System.Data.SQLite.SQLiteDataReader.VerifyType(Int32 i, DbType typ) +492
System.Data.SQLite.SQLiteDataReader.GetString(Int32 i) +131
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner) +72
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +251
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +28
System.Data.Common.Internal.Materialization.ErrorHandlingValueReader`1.GetValue(DbDataReader reader, Int32 ordinal) +342
System.Data.Common.Internal.Materialization.Shaper.GetPropertyValueWithErrorHandling(Int32 ordinal, String propertyName, String typeName) +79
lambda_method(Closure , Shaper ) +167
System.Data.Common.Internal.Materialization.Shaper.HandleEntityAppendOnly(Func`2 constructEntityDelegate, EntityKey entityKey, EntitySet entitySet) +218
lambda_method(Closure , Shaper ) +291
System.Data.Common.Internal.Materialization.Coordinator`1.ReadNextElement(Shaper shaper) +170
System.Data.Common.Internal.Materialization.SimpleEnumerator.MoveNext() +84
Test.Controllers.HomeController.Index() in C:\Projects\PlayListShuffler\Test\Controllers\HomeController.vb:14
lambda_method(Closure , ControllerBase , Object[] ) +96
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +208
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12() +55
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +263
System.Web.Mvc.<>c__DisplayClass17.<InvokeActionMethodWithFilters>b__14() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +191
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +343
System.Web.Mvc.Controller.ExecuteCore() +116
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +97
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
System.Web.Mvc.<>c__DisplayClassb.<BeginProcessRequest>b__5() +37
System.Web.Mvc.Async.<>c__DisplayClass1.<MakeVoidDelegate>b__0() +21
System.Web.Mvc.Async.<>c__DisplayClass8`1.<BeginSynchronous>b__7(IAsyncResult _) +12
System.Web.Mvc.Async.WrappedAsyncResult`1.End() +62
System.Web.Mvc.<>c__DisplayClasse.<EndProcessRequest>b__d() +50
System.Web.Mvc.SecurityUtil.<GetCallInAppTrustThunk>b__0(Action f) +7
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +22
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +60
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8920029
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184
While it's true that sqlite is not strongly typed (which plays very nicely with a dynamically typed language like Python) the strongly typed nature of .NET is enforced in the wrapper. So that the type of the column detected when the table is read is the type that is required by Reader.Getxxx(n).

NHibernate Not Compile on my Window Server

My Apps was developed with NHibernate Working fine on my system but giving this error on the host Server
Index was outside the bounds of the array.
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.IndexOutOfRangeException: Index was outside the bounds of the array.
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:
[IndexOutOfRangeException: Index was outside the bounds of the array.]
NHibernate.Dialect.Dialect.IsQuoted(String name) +84
NHibernate.Dialect.Dialect.QuoteForSchemaName(String schemaName) +20
NHibernate.Cfg.HbmBinder.MakeIdentifier(XmlNode node, SimpleValue model, Mappings mappings) +228
NHibernate.Cfg.HbmBinder.BindRootClass(XmlNode node, RootClass model, Mappings mappings) +1223
NHibernate.Cfg.HbmBinder.BindRoot(XmlDocument doc, Mappings mappings) +398
NHibernate.Cfg.Configuration.AddValidatedDocument(XmlDocument doc, String name) +69
[MappingException: Could not compile the mapping document: CMS.Common.Mapping.CMS.Common.Data.AccountPeriod.hbm.xml]
NHibernate.Cfg.Configuration.LogAndThrow(MappingException me) +40
NHibernate.Cfg.Configuration.AddValidatedDocument(XmlDocument doc, String name) +137
NHibernate.Cfg.Configuration.AddXmlReader(XmlTextReader hbmReader, String name) +29
NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name) +109
NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly) +185
NHibernate.Cfg.Configuration.AddResources(Assembly assembly, IList resources, Boolean skipOrdering) +166
NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly, Boolean skipOrdering) +32
NHibernate.Cfg.Configuration.AddAssembly(String assemblyName) +150
NHibernate.Cfg.Configuration.DoConfigure(XmlDocument doc) +644
NHibernate.Cfg.Configuration.Configure(XmlTextReader reader) +304
NHibernate.Cfg.Configuration.Configure(XmlNode node) +81
NHibernate.Cfg.Configuration.Configure() +35
ProjectBase.Data.NHibernateSessionManager.InitSessionFactory() +60
ProjectBase.Data.NHibernateSessionManager..ctor() +39
ProjectBase.Data.Nested..cctor() +39
[TypeInitializationException: The type initializer for 'Nested' threw an exception.]
ProjectBase.Data.NHibernateSessionManager.get_Instance() +38
CMS.Facade.CoreSystem.BuildSession() in C:\Users\Oladapo\Documents\Visual Studio 2008\Projects\Property Manager\CMS.Facade\CoreSystem.cs:440
CMS.Facade.AdvertSystem.RetrieveAllAdvert() in C:\Users\Oladapo\Documents\Visual Studio 2008\Projects\Property Manager\CMS.Facade\AdvertSystem.cs:16
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +0
System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner) +71
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks) +350
System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +29
System.Web.UI.WebControls.ObjectDataSourceView.InvokeMethod(ObjectDataSourceMethod method, Boolean disposeInstance, Object& instance) +488
System.Web.UI.WebControls.ObjectDataSourceView.ExecuteSelect(DataSourceSelectArguments arguments) +1247
System.Web.UI.WebControls.BaseDataList.GetData() +38
System.Web.UI.WebControls.DataList.CreateControlHierarchy(Boolean useDataSource) +153
System.Web.UI.WebControls.BaseDataList.OnDataBinding(EventArgs e) +54
System.Web.UI.WebControls.BaseDataList.DataBind() +55
System.Web.UI.WebControls.BaseDataList.EnsureDataBound() +60
System.Web.UI.WebControls.BaseDataList.CreateChildControls() +69
System.Web.UI.Control.EnsureChildControls() +87
System.Web.UI.Control.PreRenderRecursiveInternal() +44
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Control.PreRenderRecursiveInternal() +171
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
After adding some NHibernate goodness to a project, I had similar problems deploying because I forgot to update the web.config file on production. Once I defined the hibernate-configuration section, everything worked.
Also happened to me when I had an empty enum defined.
That you have a MappingException included in your stack trace is key. This implies either a problem with your class mappings, or your NHibernate configuration. It could also be that your database does not contain tables or fields defined in your class mappings.
To be more specific, you would need to provide additional information.

IIS7 + NHibernate: Illegal operation attempted on a registry key that has been marked for deletion

We have an asp.net MVC app using Fluent Nhibernate running on top of IIS7 & Windows Sever 2008. Frequently (although so far we have yet to consistently reproduce it) after a build we get a yellow screen of death with this exception:
[COMException (0x800703fa): Illegal operation attempted on a registry key that has been marked for deletion. (Exception from HRESULT: 0x800703FA)]
System.Reflection.Assembly._nDefineDynamicModule(Assembly containingAssembly, Boolean emitSymbolInfo, String filename, StackCrawlMark& stackMark) +0
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternalNoLock(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +381
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModuleInternal(String name, Boolean emitSymbolInfo, StackCrawlMark& stackMark) +105
System.Reflection.Emit.AssemblyBuilder.DefineDynamicModule(String name, Boolean emitSymbolInfo) +83
Castle.DynamicProxy.ModuleScope.CreateModule(Boolean signStrongName) +206
Castle.DynamicProxy.ModuleScope.ObtainDynamicModuleWithWeakName() +63
Castle.DynamicProxy.Generators.Emitters.ClassEmitter.CreateTypeBuilder(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +78
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces, TypeAttributes flags, Boolean forceUnsigned) +69
Castle.DynamicProxy.Generators.Emitters.ClassEmitter..ctor(ModuleScope modulescope, String name, Type baseType, Type[] interfaces) +36
Castle.DynamicProxy.Generators.BaseProxyGenerator.BuildClassEmitter(String typeName, Type parentType, Type[] interfaces) +140
Castle.DynamicProxy.Generators.ClassProxyGenerator.GenerateCode(Type[] interfaces, ProxyGenerationOptions options) +648
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors) +139
Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, IInterceptor[] interceptors) +39
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +416
[HibernateException: Creating a proxy instance failed]
NHibernate.ByteCode.Castle.ProxyFactory.GetProxy(Object id, ISessionImplementor session) +642
NHibernate.Tuple.Entity.AbstractEntityTuplizer.CreateProxy(Object id, ISessionImplementor session) +49
NHibernate.Persister.Entity.AbstractEntityPersister.CreateProxy(Object id, ISessionImplementor session) +102
NHibernate.Event.Default.DefaultLoadEventListener.CreateProxyIfNecessary(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options, IPersistenceContext persistenceContext) +255
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +400
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.InternalLoad(String entityName, Object id, Boolean eager, Boolean isNullable) +310
NHibernate.Type.EntityType.ResolveIdentifier(Object id, ISessionImplementor session) +211
NHibernate.Engine.TwoPhaseLoad.InitializeEntity(Object entity, Boolean readOnly, ISessionImplementor session, PreLoadEvent preLoadEvent, PostLoadEvent postLoadEvent) +527
NHibernate.Loader.Loader.InitializeEntitiesAndCollections(IList hydratedObjects, Object resultSetId, ISessionImplementor session, Boolean readOnly) +544
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1158
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +105
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +472
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +77
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +30
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +182
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +174
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +194
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +923
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +169
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +191
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +139
NHibernate.Impl.SessionImpl.Get(Object id) +136
Huddle.DataAccess.Persistence.Repository`1.FindById(Int32 id) +281
Huddle.WebSite.Global.GetWorkspace() +241
Huddle.WebSite.Global.Application_BeginRequest(Object sender, EventArgs e) +437
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
It seems a few other people have found the same problem although no one seems to have a solution, any ideas?
This sounds like something I've seen with COM+ and MSMQ on Windows 2008. What happens is that Windows 2008 unloads the user registry hive as soon as the user is logged off, regardless of any remaining open handles. You should see entries in the event log that the hive was unloaded with processes still using it.
There is a GPO that can be set to prevent this from happening (DisableForceUnload)
More information here:
http://blogs.msdn.com/distributedservices/archive/2009/11/06/a-com-server-application-may-stop-working-on-windows-server-2008.aspx
This looks like a bug in the .NET framework itself.
Notice that the innermost method being called, does not specify it can throw a ComException.
I would suggest updating to the most recent version of Castle Dynamic Proxy (2.2 beta) to see if the problem persists.
If it does you may try using one of the other proxy providers.
And also report this issue to Microsoft Connect