how can I handle exception that is thrown in NHibernate method Flush? I have a action for deleting objects. It loads the objects from repository using posted ids and calls repository.Delete(obj).
Leaving aside that my mapping in NHibernate is not complete and the delete results in "The DELETE statement conflicted with REFERENCE constraint" exception, this is good case to implement the exception hadling for this case.
So the exception is thrown in Flush and the Flush is called in UnitOfWorkPerRequestTask, which is task created and destroyed on every request and it starts and flushes the UnitOfWork (Rhino.Commons.UnitOfWork). This task is registered using Windsor container and LifestyleType.Transient and it is called by HttpApplication inside Begin and EndRequest methods.
Is there any way how to handle this exception in my delete action, so I can notice user that this object cannot be deleted because of some relationships?
The exception stack trace is here (not full):
NHibernate.Transaction.AdoTransaction.Commit() +212
Rhino.Commons.NHibernateTransactionAdapter.Commit() +33
Rhino.Commons.BaseUnitOfWorkFactory.TransactionalFlush(IsolationLevel isolationLevel) +116
Rhino.Commons.BaseUnitOfWorkFactory.TransactionalFlush() +35
Cereal.Mvc.DataModule.Tasks.UnitOfWorkPerRequestTask.DisposeCore() in C:\projects\Sample\Cereal.Mvc.DataModule\Tasks\UnitOfWorkPerRequestTask.cs:33
System.Web.Mvc.Extensibility.Disposable.Dispose(Boolean disposing) in C:\projects\System.Web.Mvc.Extensibility\Abstraction\Disposable.cs:52
System.Web.Mvc.Extensibility.Disposable.Dispose() in C:\projects\System.Web.Mvc.Extensibility\Abstraction\Disposable.cs:35
Castle.MicroKernel.LifecycleConcerns.DisposalConcern.Apply(ComponentModel model, Object component) +47
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.ApplyConcerns(Object[] steps, Object instance) +129
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.ApplyDecommissionConcerns(Object instance) +106
Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalDestroy(Object instance) +37
Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Destroy(Object instance) +37
Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Release(Object instance) +48
Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleManager.Evict(Object instance) +38
Castle.MicroKernel.Lifestyle.PerWebRequestLifestyleModule.Application_EndRequest(Object sender, EventArgs e) +305
System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
Thanks for help.
If you call Flush() in a UnitOfWork, you can only catch the error and log it.
If you want your users inform about the error, then close the transaction or do the Flush earlierer (as stated in the comments of Paco and cbp). One place is to handle it in your action method. Check the outcome and report it to the user with an error page.
Related
I am currently developing an ASP.NET MVC application that uses Unity for the IoC container. The solution is deployed to Windows Azure using a SQL Azure backend and implments Azure Caching.
After deploying the app to Windows Azure everything seems to work fine. But then after a few requests I get the error "An attempt was made to access a socket in a way forbidden by its access permissions".
For example, if I browse to the site and repeatedly initiate an AJAX POST (e.g. autocomplete input) request it will work fine for the first few requests, but then crash out (by means of displaying a HTTP 500 error in the Chrome Dev Tools console). Then if I try and fresh the page I get the sockets error until the app is restart or the pool is recycled.
Even if I flick between pages I get the same error after a while, i.e. it's not just isolated to the AJAX request. The AJAX request is just the quickest way to replicate the issue.
I'm wondering if the error An error occurred when trying to create a controller of type 'MySite.Web.MVC.Controllers.LocationsController'. Make sure that the controller has a parameterless public constructor.] in the stack trace is a red herring because the ILocationCacheService mapping used by the controller is being resolved by Unity. The AJAX request works for the first few times so it definitely resolves the mapping.
Everything works fine locally, or at least I can't replicate the error.
Stack Trace
Server Error in '/' Application.
An attempt was made to access a socket in a way forbidden by its access permissions
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.Net.Sockets.SocketException: An attempt was made to access a socket in a way forbidden by its access permissions
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:
[SocketException (0x271d): An attempt was made to access a socket in a way forbidden by its access permissions]
System.Net.Sockets.Socket.DoMultipleAddressConnectCallback(Object result, MultipleAddressConnectAsyncResult context) +1847654
System.Net.Sockets.Socket.DoDnsCallback(IAsyncResult result, MultipleAddressConnectAsyncResult context) +34
System.Net.Sockets.Socket.BeginConnect(String host, Int32 port, AsyncCallback requestCallback, Object state) +271
Microsoft.ApplicationServer.Caching.SocketConnectionFactory.BeginConnect(String host, Int32 port, AsyncCallback callback, Object state, TimeSpan timeout) +469
Microsoft.ApplicationServer.Caching.TcpClientChannelFactory.BeginConnect(String host, Int32 port, AsyncCallback callback, Object state) +119
Microsoft.ApplicationServer.Caching.TcpClientChannel.ConnectAsync() +368
Microsoft.ApplicationServer.Caching.SocketClientChannel.TryGetTcpChannelUntilTimeout(TcpClientChannel clientChannel, ITcpChannel& chnl) +41
Microsoft.ApplicationServer.Caching.SocketClientChannel.Send(EndpointID endpoint, IVelocityRequestPacket packet) +188
Microsoft.ApplicationServer.Caching.SocketClientChannel.Send(EndpointID endpoint, ICreateMessage message) +112
Microsoft.ApplicationServer.Caching.SimpleSendReceiveModule.Send(EndpointID endpoint, RequestBody request, Int32 retries) +73
Microsoft.ApplicationServer.Caching.SimpleSendReceiveModule.SendMsgAndWait(EndpointID endpt, RequestBody reqMsg, TimeSpan requestTimeout, IRequestTracker& tracker) +428
Microsoft.ApplicationServer.Caching.SocketClientProtocol.SendMessage(EndpointID endPt, RequestBody request) +52
Microsoft.ApplicationServer.Caching.DataCacheFactory.EstablishConnection(IEnumerable`1 servers, RequestBody request, Func`3 sendMessageDelegate, DataCacheReadyRetryPolicy retryPolicy) +253
Microsoft.ApplicationServer.Caching.<>c__DisplayClass5.<Initialize>b__2(RequestBody req) +83
Microsoft.ApplicationServer.Caching.SocketClientProtocol.SendReceive(IVelocityRequestPacket request, Func`2 delegate, EndpointID& destination) +34
Microsoft.ApplicationServer.Caching.SocketClientProtocol.Initialize(IEnumerable`1 servers) +367
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName, CreateNewCacheDelegate cacheCreationDelegate, DataCacheInitializationViaCopyDelegate initializeDelegate) +400
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetCache(String cacheName) +61
Microsoft.ApplicationServer.Caching.DataCacheFactory.GetDefaultCache() +11
MySite.Services.Cache.Implementations.LocationCacheService..ctor(ILocationService locationService) +64
lambda_method(Closure , IBuilderContext ) +176
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.ObjectBuilder2.BuilderContext.NewBuildUp(NamedTypeBuildKey newBuildKey) +113
Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context) +48
lambda_method(Closure , IBuilderContext ) +107
Microsoft.Practices.ObjectBuilder2.<>c__DisplayClass1.<GetBuildMethod>b__0(IBuilderContext context) +35
Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context) +10
Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context) +196
Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context) +193
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +165
[ResolutionFailedException: Resolution of the dependency failed, type = "MySite.Web.MVC.Controllers.LocationsController", name = "(none)".
Exception occurred while: Calling constructor MySite.Services.Cache.Implementations.LocationCacheService(MySite.Services.Interfaces.ILocationService locationService).
Exception is: SocketException - An attempt was made to access a socket in a way forbidden by its access permissions
-----------------------------------------------
At the time of the exception, the container was:
Resolving MySite.Web.MVC.Controllers.LocationsController,(none)
Resolving parameter "locationCacheService" of constructor MySite.Web.MVC.Controllers.LocationsController(MySite.Services.Cache.Interfaces.ILocationCacheService locationCacheService)
Resolving MySite.Services.Cache.Implementations.LocationCacheService,(none) (mapped from MySite.Services.Cache.Interfaces.ILocationCacheService, (none))
Calling constructor MySite.Services.Cache.Implementations.LocationCacheService(MySite.Services.Interfaces.ILocationService locationService)
]
Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name, IEnumerable`1 resolverOverrides) +329
Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name, ResolverOverride[] resolverOverrides) +15
Microsoft.Practices.Unity.UnityContainerExtensions.Resolve(IUnityContainer container, Type t, ResolverOverride[] overrides) +18
Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType) +67
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +41
[InvalidOperationException: An error occurred when trying to create a controller of type 'MySite.Web.MVC.Controllers.LocationsController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +178
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +77
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +66
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +191
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +50
System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
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
I managed to resolve this issue using connection pooling for cache with maxconnectionstoserver="1". Here is the web.config setting for the datacacheclient section:
<dataCacheClient name="default" isCompressionEnabled="true" maxConnectionsToServer="1" connectionPool="true" useLegacyProtocol="false">
My ASP.NET MVC 3 app works fine on my local machine (And usually works fine when i deploy it), but on this occasion i get the following error. The server is windows 2008 R2 with IIS7
EDIT: Bothe ILoggingService & IConfigSettings are both bound in Singleton Scope by Ninject (If That Helps)
Anyone get any pointers on what i should look for?
Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[NullReferenceException: Object reference not set to an instance of an object.]
DataPortal.Models.Repositories.KpiRepository..ctor(ILoggingService ls, IConfigSettings configSettings) +1295
DynamicInjector3f592a0195c345d8a7d555c4c4085e12(Object[] ) +128
Ninject.Activation.Context.Resolve() +279
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +237
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +298
System.Linq.WhereSelectArrayIterator`2.MoveNext() +109
System.Linq.Buffer`1..ctor(IEnumerable`1 source) +487
System.Linq.Enumerable.ToArray(IEnumerable`1 source) +103
Ninject.Activation.Providers.StandardProvider.Create(IContext context) +479
Ninject.Activation.Context.Resolve() +279
System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +237
System.Linq.Enumerable.SingleOrDefault(IEnumerable`1 source) +298
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +67
[InvalidOperationException: An error occurred when trying to create a controller of type 'DataPortal.Controllers.KpiController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +85
System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +280
System.Web.Mvc.<>c__DisplayClass6.<BeginProcessRequest>b__2() +66
System.Web.Mvc.<>c__DisplayClassb`1.<ProcessInApplicationTrust>b__a() +19
System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Func`1 func) +161
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +405
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +375
it was a dependency issue in the end. The project had a dependency on another project that hadn't been deployed.
It seems one of your argument "LoggingService or ConfigSettings" is not configured properly in your web.config. Check your previous working version config file.
In some cases it can be related to a problem with the database for example :
a select which returns a null value without a correct exception handling would cause the same error. Therefore,one needs to check his sql requests.
We're running a web application distributed across load balanced 3 web servers. The exact same code base & configuration is deployed across the 3 servers, and since about 1 hour ago I'm getting the following error on one of them, but not the other two.
System.InvalidOperationException: An error occurred when trying to create a controller of type 'XXX.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor. ---> System.MissingMethodException: No parameterless constructor defined for this object.
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache)
at System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
--- End of inner exception stack trace ---
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory)
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)
We are running this with ASP.NET MVC (with Output Caching), NHibernate (with NHibernate caching) & StructureMap. The cache is not shared, so each web server manages its own cache, though the cache dependencies are the same across the 3 servers.
I don't really know where to start describing what/where it could be going wrong or the circumstances, because it's so strange to me.
I've seen this once before about 2 weeks ago, but it went away on its own after about an hour and I haven't seen it since. Has anyone else seen an error like this before?
Well, it seems your HomeController is missing a parameterless constructor. Are you sure it has one?
The default controller factory needs one to intialize your constructor.
Unless you are using your own ControllerFactory, in which case you need to register it during Application_Start:
protected void Application_Start()
{
//other code
ControllerBuilder.Current.SetControllerFactory(new MyCustomControllerFactory());
}
Assuming you're resolving controllers with structuremap, it may be your components are registered at the wrong place/time.
Are you registering components in Application_Start ?
Using asp.net Mvc3 RTM, IIS7.
I'm getting flooded with errors like this one:
System.Web.HttpException
A public action method 'Application' was not found on controller 'Interreg.Web.Controllers.ApplicationsController'.
System.Web.HttpException (0x80004005): A public action method 'Application' was not found on controller 'Interreg.Web.Controllers.ApplicationsController'.
at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
at System.Web.Mvc.Controller.ExecuteCore()
at System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext)
at System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext)
at System.Web.Mvc.MvcHandler.<>c_DisplayClass6.<>c_DisplayClassb.b_5()
at System.Web.Mvc.Async.AsyncResultWrapper.<>c_DisplayClass1.b_0()
at System.Web.Mvc.Async.AsyncResultWrapper>
c_DisplayClass8'1.BeginSynchronous>b__7(IAsyncResult )
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult`1.End()
at System.Web.Mvc.MvcHandler.<>c_DisplayClasse.b_d()
at System.Web.Mvc.SecurityUtil.b_0(Action f)
at System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action)
at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
Controllers and actions changes, they surely do exist and app does not crash - user does not see yellow screen of death.
I suspect it has something to do with static resource loading (images, scripts), probably routing.
Any ideas what's wrong, what can cause this?
It may be what you say. I'd suggest to check IIS log for queries against /Application to see where is that URL and where it's called.
Another option is navigating while in debug mode and in that case exception should pause the execution in Visual Studio.
Good luck!
Verify the type of request.(Either GET or POST)
Add [AcceptVerbs(HttpVerbs.Get | HttpVerbs.Post)] attributes at above the method
If Application method was returning the Json result add JsonRequestBehavior.AllowGet behavior in return Json.
Eg: return Json(zeroResult, JsonRequestBehavior.AllowGet);
I am developing a ASP.NET MVC web app under .NET 3.5, NHibernate and hosted on Windows Azure. When, the webapp is run from the local development fabric it works fine. Yet, when I move it to Windows Azure, every insert performed from the MVC web role ends up with the exception listed below.
Any idea what's wrong with my NHibernate logic? (might be the session management, not sure)
[AssertionFailure: null id in Lokad.Translate.Entities.User entry (don't flush the Session after an exception occurs)]
NHibernate.Event.Default.DefaultFlushEntityEventListener.CheckId(Object obj, IEntityPersister persister, Object id, EntityMode entityMode) +292
NHibernate.Event.Default.DefaultFlushEntityEventListener.GetValues(Object entity, EntityEntry entry, EntityMode entityMode, Boolean mightBeDirty, ISessionImplementor session) +93
NHibernate.Event.Default.DefaultFlushEntityEventListener.OnFlushEntity(FlushEntityEvent event) +158
NHibernate.Event.Default.AbstractFlushingEventListener.FlushEntities(FlushEvent event) +469
NHibernate.Event.Default.AbstractFlushingEventListener.FlushEverythingToExecutions(FlushEvent event) +339
NHibernate.Event.Default.DefaultFlushEventListener.OnFlush(FlushEvent event) +85
NHibernate.Impl.SessionImpl.Flush() +275
NHibernate.Transaction.AdoTransaction.Commit() +236
Lokad.Translate.Repositories.PageRepository.Create(Page page)
Lokad.Translate.Controllers.PagesController.Create(Page page)
lambda_method(ExecutionScope , ControllerBase , Object[] ) +69
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +251
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +31
System.Web.Mvc.<>c__DisplayClassa.b__7() +88
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func1 continuation) +534
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +312
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +856
System.Web.Mvc.Controller.ExecuteCore() +185
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +221
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +586
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +177
Note that I am using _session.FlushMode = FlushMode.Commit; and that the User is used in a custom RoleProvider
public class SimpleRoleProvider : RoleProvider
{
readonly UserRepository Users = new UserRepository();
public override string[] GetRolesForUser(string username)
{
try
{
var user = Users.Get(username);
// no role if user is not registered
if (null == user) return new string[0];
// default role for registered user
return user.IsManager ? new[] { "Manager", "User" } : new[] { "User" };
}
catch (Exception)
{
// role should not fail in case of DB issue.
return new string[0];
}
}
}
You should never catch exceptions and ignore them during a NHibernate transaction.
I try to explain why.
There could be exceptions for instance caused by constraints in the database. (it could also be caused by mapping problems, exceptions thrown by properties or anything else.) NHibernate tries to synchronize the state in memory with the database. This is done on commit - and sometimes before queries to make sure that queries are done on actual data. When this synchronization fails, the state in the database is something random, some changes are persisted, others are not. The only thing you can do in such a case is closing the session.
Consider that decisions and calculations in your code are based on values in memory. But - in case of an ignored exception, this values are not the values in the database, they will never be there. So your logic will decide and calculate on 'fantasy-data'.
By the way, it is never a good idea to catch any exception (untyped) and ignore them. You should always know the exceptions you handle, and be sure that you can continue.
What you're doing here is swallowing programming errors. Believe me, the system will not be more stable. The question is only: do you notice the error when it occurs, or do you ignore it there and even persist the result of the error to the database? When you do the latter, you don't have to be surprised when your database is inconsistent and other error arise when you try to get the data from the database. And you will never ever find the code that is the actual cause of the error.
I have finally found a solution to my own problem. In case people would be interested, I am posting the solution here.
public class SimpleRoleProvider : RoleProvider
{
// isolated session management for the RoleProvider to avoid
// issues with automated management of session lifecycle.
public override string[] GetRolesForUser(string username)
{
using (var session = GlobalSetup.SessionFactory.OpenSession())
{
var users = new UserRepository(session);
var user = users.Get(username);
// no role if user is not registered
if (null == user) return new string[0];
// default role for registered user
return user.IsManager ? new[] {"Manager", "User"} : new[] {"User"};
}
}
}
Basically what was happening is that the RoleProvider repository does not seem to have the same lifecycle than regular in-view / in-controller repositories. As a result, at the time the RoleProvider is called, the NHibernate session has already been disposed causing the exception observed here above.
I have replaced the code by the following one here above. This one has its own NHibernate session management, and ends up working fine.
This exception can occur if your column names include reserved words (e.g. use status as a column name and it will become impossible to Save)