Authorize attribute not working with Windows Authentication application - asp.net-mvc-4

I have an MVC4 application whereby I have assigned roles to my user using a custom role provider so that when I check User.IsInRole against my User table it determines which links etc to display on screen in my _Layout.cshtml page. This is working on the Layout page in that the correct links are appearing.
However when I secure my Admin controller using the
[Authorize(Roles = "Admin")]
I am getting the following stack trace from an object not set to instance of an object error:
[NullReferenceException: Object reference not set to an instance of an object.]
System.Web.Mvc.AuthorizeAttribute.AuthorizeCore(HttpContextBase httpContext) +39
System.Web.Mvc.AuthorizeAttribute.OnAuthorization(AuthorizationContext filterContext) +159
System.Web.Mvc.ControllerActionInvoker.InvokeAuthorizationFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor) +96
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
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
What exactly is in this Filter context? This works without any further configuration when I use ADFS or Forms based authentication but when using Windows based authentication I have had to do the following to get IsInRole method working:
this.UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
if (this.UserName.Contains("\\"))
{
string[] stringArray = this.UserName.Split(new Char[] { '\\' });
this.UserName = stringArray[1];
MyUser identity = userRepository.Get(u => u.Username == this.UserName).FirstOrDefault();
HttpContext.Current.User = identity;
}
Do I need to configure some other HttpContext proper in order for Authorize attribute to work in same manner as IsInRole method?

In the forms case, it could be anything but it is very common to implement a username password form with a lookup by username in a user table, based on the code presented it looks like the repository expects just a username, it just turns out that windows.identity.name returns domain\user. That's where the extra effort comes in to split into domain, user. example below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcApplication6
{
public class DemoAuthAttribute : AuthorizeAttribute
{
// create a file like auth.cs in the mvc project
// called
// [DemoAuth("BAR")]
// as an attibute on a controller method
private string _role;
public DemoAuthAttribute(string role)
{
_role = role; // should be exapanded to handle more than one
}
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return httpContext.Request.IsAuthenticated && _role == "FOO";
// lookup the current user in database does the user have role as specificed by the attribute?
// if yes sucess if not fail.
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
// your custom logic here
string text = string.Format("<u><h5>Auth successfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
else
{
// RedirectResult, etc.
string text = string.Format("<u><h5>Auth unsuccessfull.....</h5></u></br>");
filterContext.HttpContext.Response.Write(text);
}
}
}
}

Related

RavenDb JsonIgnore Attribute throws error when generating document key

Im moving out from Guid to string (HiLo) keys which is suggested by RavenDb docs.
Some of my DomainEvents gets fired inside the constructor so the Id should be known before firing the event. When I was using Guid, I'll just create Guid.NewGuid() to generate Id. But for the HiLo provided by RavenDb, what I did was an extension method to generate keys for me and then pass to my Entity constructor as argument.
RavenDb Version: RavenDb.Client 3.0.30000
Note that this is a copy-paste code I found on the internet :)
public static class RavenDbExtensions
{
public static string GenerateIdFor<T>(this IDocumentSession session)
{
// We need the advanced session in order to ensure that the keys are generated in the correct database.
// session.Advanced.DocumentStore.DatabaseCommands is not sufficient.
var advancedSession = session.Advanced as DocumentSession;
if (advancedSession == null)
throw new InvalidOperationException();
// An entity instance is required to generate a key, but we only have a type.
// In our case, the entities don't have public constructors so we must use reflection.
var entity = Activator.CreateInstance(typeof(T), true);
// Generate an ID using the commands and conventions from the current session
return advancedSession.Conventions.GenerateDocumentKey(
advancedSession.DocumentStore.Identifier,
advancedSession.DatabaseCommands,
entity);
}
}
My controller method.
[HttpPost]
[ValidateAntiForgeryToken]
[Route("add", Name = "courses.add")]
public ActionResult Add(AddViewModel model)
{
if (!ModelState.IsValid)
{
model.Categories = DocumentSession.Query<Category>().ToList();
return View(model);
}
string courseId = DocumentSession.GenerateIdFor<Course>();
var course = Course.Create(
courseId,
model.Title,
CourseCode.FromString(model.Code),
StandardDuration.Create(model.Days, model.HoursPerDay),
model.StandardPrice,
model.CategoryId);
DocumentSession.Store(course);
return RedirectToAction("Add");
}
I have this class with JsonIgnore (Raven.Imports.Newtonsoft.Json) attribute
public class StandardDuration : ValueObject
{
private StandardDuration(int days, int hoursPerDay)
{
Days = days;
HoursPerDay = hoursPerDay;
}
public int Days { get; private set; }
public int HoursPerDay { get; private set; }
public static StandardDuration Create(int days, int hoursPerDay)
{
if (days <= 0)
throw new DomainModelException("Days should be atleast one");
if (hoursPerDay <= 0)
throw new DomainModelException("CreditHours should be greater than zero");
return new StandardDuration(days, hoursPerDay);
}
[JsonIgnore]
public int CreditHours
{
get { return HoursPerDay * Days; }
}
protected override IEnumerable<object> GetEqualityComponents()
{
yield return Days;
yield return HoursPerDay;
}
}
which throws an error
Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.
UPDATE
I cant reproduce the error on the code above due to same issue but before showing the page.
But Im facing the same issue even on non JsonIgnore decorated classes.
public class Category : Entity
{
private Category() { }
private Category(Guid id, string name)
{
Id = id;
Name = name;
}
public string Name { get; private set; }
public static Category Create(Guid id, string name)
{
if (string.IsNullOrWhiteSpace(name))
throw new DomainModelException("Category name should not be blank or null.");
return new Category(id, name);
}
}
controller action
[HttpPost]
[Route("add", Name = "course_categories.add")]
public ActionResult Add(string name)
{
if (ModelState.IsValid)
{
var courseCategory = Category.Create(Guid.NewGuid(), name);
DocumentSession.Store(courseCategory);
AddSuccessMessage("Course Category created");
return RedirectToRoute("course_categories.add_page");
}
ModelState.AddModelError("", "An error occurred please try again.");
return View();
}
stack trace:
[MethodAccessException: Attempt by method 'Raven.Client.Document.DocumentConvention.DefaultTypeTagName(System.Type)' to access method 'Raven.Imports.Newtonsoft.Json.Utilities.TypeExtensions.IsGenericType(System.Type)' failed.]
Raven.Client.Document.DocumentConvention.DefaultTypeTagName(Type t) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:264
Raven.Client.Document.DocumentConvention.GetTypeTagName(Type type) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:296
Raven.Client.Document.DocumentConvention.DefaultFindFullDocumentKeyFromNonStringIdentifier(Object id, Type type, Boolean allowNull) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\DocumentConvention.cs:152
Raven.Client.Document.GenerateEntityIdOnTheClient.GetIdAsString(Object entity, Object value, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:49
Raven.Client.Document.GenerateEntityIdOnTheClient.TryGetIdFromInstance(Object entity, String& id) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\GenerateEntityIdOnTheClient.cs:33
Raven.Client.Document.InMemoryDocumentSessionOperations.Store(Object entity) in c:\Builds\RavenDB-Stable-3.0\Raven.Client.Lightweight\Document\InMemoryDocumentSessionOperations.cs:646
Web.Features.CourseCategories.CourseCategoriesController.Add(String name) in E:\Projects\Akademia\Presentation\Web\Features\CourseCategories\CourseCategoriesController.cs:39
lambda_method(Closure , ControllerBase , Object[] ) +104
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +14
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +157
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +27
System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +22
System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +32
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +50
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +225
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +34
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +26
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +100
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +10
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +27
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +13
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +36
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +12
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +22
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +26
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +10
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +21
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +29
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +49
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +28
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9721605
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

An Xaml Error: The property "Value" was not found in type "WindowsUIXamlBindingWrapper"

I'm coding a Windows 8.1 app that use Hub control.
this project also use mvvmLight.
DataContext Class like this
public class UserInfoViewModel : ViewModelBase
{
private UserInfo userInfo;
public UserInfo User
{
get { return userInfo; }
set
{
if (value == userInfo)
return;
userInfo = value;
RaisePropertyChanged("User");
}
}
public UserInfoViewModel()
{
User = new UserInfo()
{
NikeName = "User",
ProfileImage = "ms-appx:///image/test.jpg"
};
}
}
When I use HubSection.ContentTemplate like this,
it's seems something wrong with the binding
<HubSection.ContentTemplate>
<DataTemplate>
<ContentControl>
<StackPanel
DataContext="{Binding User, Source={StaticResource Locator}}">
</StackPanel>
</ContentControl>
</DataTemplate>
</HubSection.ContentTemplate>
There will have an XAML error
The property "Value" was not found in type "WindowsUIXamlBindingWrapper"
System.ArgumentNullException
Value cannot be null.
Parameter name: key
at System.Collections.Generic.Dictionary`2.Remove(TKey key)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.WindowsRuntimeContext.UnregisterDynamicType(Type dynamicType)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.UnregisterDynamicType(Type dynamicType)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.MockTypes.MockTypeGenerator.Reset()
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.XamlProjectMetadata.OnTypesInvalidatedInternal(IList`1 invalidatedAssemblies)
at Microsoft.VisualStudio.DesignTools.Platform.Metadata.TypeResolver.OnAssemblyCollectionChanged(NotifyCollectionChangedEventArgs e)
at Microsoft.VisualStudio.DesignTools.XamlDesigner.Metadata.XamlProjectMetadata.OnAssemblyCollectionChanged(NotifyCollectionChangedEventArgs e)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectAssemblyCollection.FireChangedEvent(NotifyCollectionChangedEventArgs eventArguments)
at Microsoft.VisualStudio.DesignTools.Designer.Project.ProjectAssemblyCollection.AssemblyCollection_EnumerationChanged(Object sender, EnumerationChangedEventArgs`1 e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Microsoft.VisualStudio.DesignTools.Utility.Collections.NotifyingCollectionBase`1.EventInvoker(EnumerationChangedEventArgs`1 eventArguments)
at Microsoft.VisualStudio.DesignTools.Utility.Events.SuspendingEventManager`1.ForwardEvents()
at Microsoft.VisualStudio.DesignTools.Utility.Events.Suspender.SuspendDisposer.Dispose(Boolean disposing)
at Microsoft.VisualStudio.DesignTools.Utility.Events.Suspender.SuspendDisposer.Dispose()
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyCollection.AssemblyService_AssembliesUpdated(Object sender, EventArgs`1 e)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.OnAssembliesUpdated(IEnumerable`1 assemblyInformation)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.RefreshDesignerCaches()
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.SetIterationContext(String[] paths)
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.SynchronizeDesignerContext()
at Microsoft.VisualStudio.DesignTools.Utility.WindowsRuntimeService.ProcessShadowCopyResults(IEnumerable`1 results)
at Microsoft.VisualStudio.DesignTools.Designer.Assemblies.AssemblyService.FlushShadowCopyUpdateQueue()
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.DispatcherOperation.InvokeImpl()
at System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Windows.Threading.DispatcherOperation.Invoke()
at System.Windows.Threading.Dispatcher.ProcessQueue()
at System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.RunApplication()
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.AppContainerDesignerProcessRun(String[] activationContextArgs)
at Microsoft.VisualStudio.DesignTools.DesignerContract.Isolation.DesignerProcess.DesignProcessViewProvider.<>c__DisplayClass3_0.<applicationView_Activated>b__0()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

RavenDB - EmbeddableDocumentStore already disposed or NRE

This question is about creating a single instance of the Raven document store in the lifetime of a ASP.Net MVC application and subsequently using a new IDocumentSession per request to serve the client with. I believe to have followed the recommended procedure described at http://ravendb.net/kb/3/using-ravendb-in-an-asp-net-mvc-website I'm still experiencing errors once the site is deployed.
My code looks as follows. The HepApp class contains the document store and is referenced by the application:
internal class HepApp
{
internal static readonly Object padlock = new object();
private static IDocumentStore _DB;
internal IDocumentStore DB
{
get
{
if (_DB == null)
{
lock (padlock)
{
if (_DB == null)
{
_DB = new EmbeddableDocumentStore().Initialize();
return _DB;
}
}
}
return _DB;
}
}
public IDocumentSession GetSession()
{
return DB.OpenSession();
}
}
My MVC Controller:
public class HomeController : Controller
{
IDocumentSession RavenSession;
public HomeController()
{
}
protected void Init()
{
RavenSession = MvcApplication.HepApp.GetSession();
}
protected override void OnActionExecuting(ActionExecutingContext filterContext)
{
base.OnActionExecuting(filterContext);
Init();
}
The application class Global.asax binds to:
public class MvcApplication : System.Web.HttpApplication
{
static readonly Object padlock = new object();
static HepApp _HepApp;
internal static HepApp HepApp
{
get
{
if(_HepApp == null)
{
lock(padlock)
{
if(_HepApp == null)
{
_HepApp = new HepApp();
}
}
}
return _HepApp;
}
}
When the application starts the document store should be initialized and live for the remainder of the application's lifetime. For each request a new Session object is created. At least, that's the idea. Instead null reference errors occur in OnActionExecuting (though I suspect the HomeController.Init method but it doesn't appear on the stack) or the EmbeddableDocumentStore object is reported als already disposed. Confusingly, these errors only crop up after the application has been running for a while which might suggest it's an app pool recycle issue
EDIT:
The errors differ but all seem to indicate a problem with the instantiation of the database store :
[EsentFileAccessDeniedException: Cannot access file, the file is locked or in use]
[InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path.]
System.InvalidOperationException: Could not write to location: \192.168.0.100\localuser\x\App_Data/Raven. Make sure you have read/write permissions for this path. ---> Microsoft.Isam.Esent.Interop.EsentFileAccessDeniedException: Cannot access file, the file is locked or in use
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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)
[ObjectDisposedException: The document store has already been disposed and cannot be used
Object name: 'EmbeddableDocumentStore'.]
Raven.Client.DocumentStoreBase.EnsureNotClosed() +82
System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
[NullReferenceException: Object reference not set to an instance of an object.]
HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:31
System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext) +10
System.InvalidOperationException: Could not open transactional storage: \192.168.0.100\localuser\x\App_Data/Raven\Data ---> Microsoft.Isam.Esent.Interop.EsentTempPathInUseException: Temp path already used by another database instance
at Microsoft.Isam.Esent.Interop.Api.Check(Int32 err)
at Microsoft.Isam.Esent.Interop.Api.JetInit(JET_INSTANCE& instance)
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
--- End of inner exception stack trace ---
at Raven.Storage.Esent.TransactionalStorage.Initialize(IUuidGenerator uuidGenerator, OrderedPartCollection1 documentCodecs)
at Raven.Database.DocumentDatabase..ctor(InMemoryRavenConfiguration configuration, TransportState transportState)
at Raven.Client.Embedded.EmbeddableDocumentStore.InitializeInternal()
at Raven.Client.Document.DocumentStore.Initialize()
at HEPlaceHolder.HepApp.get_DB() in e:\projects\HEPlaceHolder\HEPlaceHolder\Logic\HepApp.cs:line 27
at HEPlaceHolder.Controllers.HomeController.OnActionExecuting(ActionExecutingContext filterContext) in e:\projects\HEPlaceHolder\HEPlaceHolder\Controllers\HomeController.cs:line 31
at System.Web.Mvc.Controller.System.Web.Mvc.IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.AsyncInvocationWithFilters.InvokeActionMethodFilterAsynchronouslyRecursive(Int32 filterIndex)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass33.b__31(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList1 filters, ActionDescriptor actionDescriptor, IDictionary2 parameters, AsyncCallback callback, Object state)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.b__19(AsyncCallback asyncCallback, Object asyncState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.Begin(AsyncCallback callback, Object state, Int32 timeout)
at System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state)
at System.Web.Mvc.Controller.b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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.b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallBeginDelegate(AsyncCallback callback, Object callbackState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.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)
EDIT:
Whenever the bin folder is updated with a tweaked version to debug the problem the site will initially run ok, presumably because the application is reset.

Invalid value for key 'attachdbfilename' on WebSecurity.InitializeDatabaseConnection

I get this error message when trying to initialize my database connection using SimpleMembership. The first initialize statement goes through, while the second does not. The goal is to use connection strings defined in the Azure service configuration when running Azure emulator or when deployed.
Web.config:
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-**********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-**********.mdf" providerName="System.Data.SqlClient" />
</connectionStrings>
Azure .cscfg configuration files:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
SimpleMembershipInitializer:
string connectionStringName = "DefaultConnection";
string connectionString = CloudConfigurationManager.GetSetting("SqlConnectionString");
const string userTableName = "UserProfile";
const string providerName = "System.Data.SqlClient";
const string userIdColumn = "UserId";
const string userNameColumn = "UserName";
// This works fine.
// WebSecurity.InitializeDatabaseConnection(connectionStringName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
// This throws exception.
// WebSecurity.InitializeDatabaseConnection(connectionString, providerName, userTableName, userIdColumn, userNameColumn, autoCreateTables: true);
Environment: Visual Studio 2012, EntityFramework 5.0 and MVC4 RTM with default SimpleMembership structure.
Full stacktrace:
[ArgumentException: Invalid value for key 'attachdbfilename'.]
System.Data.SqlClient.SqlConnectionString.VerifyLocalHostAndFixup(String& host, Boolean enforceLocalHost, Boolean fixup) +888986
System.Data.SqlClient.SqlConnectionString..ctor(String connectionString) +5330002
System.Data.SqlClient.SqlConnectionFactory.CreateConnectionOptions(String connectionString, DbConnectionOptions previous) +24
System.Data.ProviderBase.DbConnectionFactory.GetConnectionPoolGroup(DbConnectionPoolKey key, DbConnectionPoolGroupOptions poolOptions, DbConnectionOptions& userConnectionOptions) +167
System.Data.SqlClient.SqlConnection.ConnectionString_Set(DbConnectionPoolKey key) +61
System.Data.SqlClient.SqlConnection.set_ConnectionString(String value) +66
WebMatrix.Data.DbProviderFactoryWrapper.CreateConnection(String connectionString) +96
WebMatrix.Data.<>c__DisplayClass15.<OpenConnectionStringInternal>b__14() +16
WebMatrix.Data.Database.get_Connection() +19
WebMatrix.Data.Database.EnsureConnectionOpen() +12
WebMatrix.Data.<QueryInternal>d__0.MoveNext() +66
System.Linq.Enumerable.FirstOrDefault(IEnumerable`1 source) +164
WebMatrix.Data.Database.QuerySingle(String commandText, Object[] args) +103
WebMatrix.WebData.DatabaseWrapper.QuerySingle(String commandText, Object[] parameters) +14
WebMatrix.WebData.SimpleMembershipProvider.CheckTableExists(IDatabase db, String tableName) +57
WebMatrix.WebData.SimpleMembershipProvider.CreateTablesIfNeeded() +49
WebMatrix.WebData.WebSecurity.InitializeMembershipProvider(SimpleMembershipProvider simpleMembership, DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean createTables) +73
WebMatrix.WebData.WebSecurity.InitializeProviders(DatabaseConnectionInfo connect, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +51
WebMatrix.WebData.WebSecurity.InitializeDatabaseConnection(String connectionString, String providerName, String userTableName, String userIdColumn, String userNameColumn, Boolean autoCreateTables) +63
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:55
[InvalidOperationException: The ASP.NET Simple Membership database could not be initialized. For more information, please see http://go.microsoft.com/fwlink/?LinkId=256588]
MyProject.Filters.SimpleMembershipInitializer..ctor() in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:59
[TargetInvocationException: Exception has been thrown by the target of an invocation.]
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.Threading.LazyHelpers`1.ActivatorFactorySelector() +68
System.Threading.LazyInitializer.EnsureInitializedCore(T& target, Boolean& initialized, Object& syncLock, Func`1 valueFactory) +115
System.Threading.LazyInitializer.EnsureInitialized(T& target, Boolean& initialized, Object& syncLock) +106
MyProject.Filters.InitializeSimpleMembershipAttribute.OnActionExecuting(ActionExecutingContext filterContext) in c:\Repos\MyRepo\trunk\Web\MyProject\Filters\InitializeSimpleMembershipAttribute.cs:23
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +69
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.AsyncControllerActionInvoker.InvokeActionMethodFilterAsynchronously(IActionFilter filter, ActionExecutingContext preContext, Func`1 nextInChain) +489
System.Web.Mvc.Async.<>c__DisplayClass3b.<BeginInvokeActionMethodWithFilters>b__35() +21
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeActionMethodWithFilters>b__31(AsyncCallback asyncCallback, Object asyncState) +191
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters, AsyncCallback callback, Object state) +197
System.Web.Mvc.Async.<>c__DisplayClass25.<BeginInvokeAction>b__1e(AsyncCallback asyncCallback, Object asyncState) +446
System.Web.Mvc.Async.WrappedAsyncResult`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +130
System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +302
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
It seems to me you might be suffering from the lack of double-escaping (do \\v11.0 instead of \v11.0), as discussed in this post.
I'm ashamed to realize I had a typo in my connection strings. I was getting connection strings from Azure Deployment configuration files, such as:
<Setting name="SqlConnectionString" value="Server=Data Source=(LocalDb)\v11.0;Initial Catalog=aspnet-********;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnet-********.mdf" />
The typo was included here, at the start of the value string. It must've been a copy'n'paste bug.
This string was duplicated in Azure configuration files Local.cscfg and Cloud.cscfg, for Azure emulator and Azure deployment respectively, as well as in web.config for running locally outside emulator. The typo was only in the Local.cscfg file, which made me very confused when trying to figure out why it did not work in certain scenarios. In addition the typo was for some reason very hard for me to spot. In hindsight I don't see how I didn't figure this out sooner.
I don't have a solution yet, but here is my own investigation and theory so far:
I took a look at the source code of WebSecurity.InitializeDatabaseConnection() and think maybe I have found a bug. It doesn't seem to ever set the DatabaseConnectionInfo.Type property, which defaults to ConnectionStringName, which could explain why it doesn't like my connection string, since it would interpret it as a connection string name instead.
WebSecurity class:
public static void InitializeDatabaseConnection(string connectionString, string providerName, string userTableName, string userIdColumn, string userNameColumn, bool autoCreateTables)
{
WebSecurity.InitializeProviders(new DatabaseConnectionInfo()
{
ConnectionString = connectionString,
ProviderName = providerName
}, userTableName, userIdColumn, userNameColumn, autoCreateTables);
}
DatabaseConnectionInfo class:
public Database Connect()
{
switch (this.Type)
{
case DatabaseConnectionInfo.ConnectionType.ConnectionStringName:
return Database.Open(this.ConnectionStringName);
case DatabaseConnectionInfo.ConnectionType.ConnectionString:
return Database.OpenConnectionString(this.ConnectionString, this.ProviderName);
default:
return (Database) null;
}
}
private enum ConnectionType
{
ConnectionStringName,
ConnectionString,
}

Mapped Objectified relationship with nhibernate can not initialize collection

I'm mapping a objectified relationship (the many->many mapping table contains properties),
following this guide.
The SQL generated(see exception) is working and returns what i want(strictly speaking it should have been an inner join?).
But I get a GenericADOException saying:
could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]
I'm guessing this is because Questionnaire is really mapping to QuestionnaireQuestion not Question(Questionnaire->hasMany->QuestionnaireQuestion<-hasMany<-Question). But I can't seem to find a way of going around this.
Question:
public class Question : PersistentObjectWithTypedId<string>
{
#region Constructors
public Question()
{
Alternatives = new List<Alternative>();
Questionnaires = new List<Questionnaire>();
}
public Question(string description)
: this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Type { get; set; }
public virtual string Description { get; set; }
public virtual int Order { get; set; }
public virtual IList<Questionnaire> Questionnaires { get; set; }
public virtual IList<Alternative> Alternatives { get; set; }
public virtual Validator MyValidator { get; set; }
}
public class QuestionMap : ClassMap<Question>
{
public QuestionMap()
{
WithTable("ida_question");
Id(x => x.ID, "ida_question_id").WithUnsavedValue(0).GeneratedBy.UuidHex("");
Map(x => x.Description, "description").AsReadOnly();
Map(x => x.Type, "ida_question_type_id").AsReadOnly();
Component<Core.Validator>(x => x.MyValidator, m =>
{
m.Map(x => x.Type, "ida_question_type_id");
m.Map(x => x.RangeMin, "validate_min");
m.Map(x => x.RangeMax, "validate_max");
});
HasMany<QuestionnaireQuestion>(x => x.Questionnaires)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_question_id");
HasMany<Alternative>(x => x.Alternatives)
.IsInverse()
.WithKeyColumn("ida_question_id")
.AsBag().SetAttribute("cascade", "all");
}
}
QuestionnaireQuestion:
public class QuestionnaireQuestion : PersistentObjectWithTypedId<string>
{
protected QuestionnaireQuestion()
{
}
public virtual int QuestionOrder { get; set; }
public virtual Question Question {get;set;}
public virtual Questionnaire Questionnaire { get; set; }
}
public class QuestionnaireQuestionMap : ClassMap<QuestionnaireQuestion>
{
public QuestionnaireQuestionMap()
{
WithTable("ida_questionnaire_question");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_question_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
References(x => x.Question, "ida_question_id")
.WithForeignKey("ida_question_id")
.FetchType.Join();
References(x => x.Questionnaire, "ida_questionnaire_id")
.WithForeignKey("ida_questionnaire_id")
.FetchType.Join();
Map(x => x.QuestionOrder, "question_no");
}
}
Questionnaire:
public class Questionnaire : PersistentObjectWithTypedId<string>
{
#region Constructors
public Questionnaire()
{
Questions = new List<Question>();
}
public Questionnaire(string description) : this()
{
Check.Require(!string.IsNullOrEmpty(description) && description.Trim() != string.Empty);
Description = description;
}
#endregion
#region Properties
public virtual string Description { get; set; }
public virtual IList<Question> Questions { get; set; }
#endregion
}
public class QuestionnaireMap : ClassMap<Questionnaire>
{
public QuestionnaireMap(){
WithTable("ida_questionnaire");
SetAttribute("lazy", "false");
Id(x => x.ID, "ida_questionnaire_id")
.WithUnsavedValue(0)
.GeneratedBy.UuidHex("");
Map(x => x.Description);
HasMany<QuestionnaireQuestion>(x => x.Questions)
.Cascade.AllDeleteOrphan()
.WithKeyColumn("ida_questionnaire_id");
}
}
The result of running the SQL in the exception in the DB is 6 rows (the expected number) containing:
IDA4_2_: Guids
IDA1_2_: Guids
IDA1_5_1_: Guids
QUESTION2_5_1: Number (order
property)
IDA3_5_1_: Guids
IDA4_5_1: Guids
IDA1_3_0_: Guids
IDA2_3_0_: MOBILEPHONE (type
property)
DESCRIPT3_3_0_: mobiltelefon
(Description property)
VALIDATE4_3_0_: (RangeMin property)
VALIDATE5_3_0_: (RangeMax property)
The complete exception is:
[InvalidCastException: Cant use object type Questionnaires.Core.QuestionnaireQuestion as Questionnaires.Core.Question.]
NHibernate.Collection.Generic.PersistentGenericBag`1.ReadFrom(IDataReader reader, ICollectionPersister persister, ICollectionAliases descriptor, Object owner) +160
NHibernate.Loader.Loader.ReadCollectionElement(Object optionalOwner, Object optionalKey, ICollectionPersister persister, ICollectionAliases descriptor, IDataReader rs, ISessionImplementor session) +407
NHibernate.Loader.Loader.ReadCollectionElements(Object[] row, IDataReader resultSet, ISessionImplementor session) +412
NHibernate.Loader.Loader.GetRowFromResultSet(IDataReader resultSet, ISessionImplementor session, QueryParameters queryParameters, LockMode[] lockModeArray, EntityKey optionalObjectKey, IList hydratedObjects, EntityKey[] keys, Boolean returnProxies) +472
NHibernate.Loader.Loader.DoQuery(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +1010
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +114
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +362
[GenericADOException: could not initialize a collection: [Questionnaires.Core.Questionnaire.Questions#CBDEDAFC183B4CD7AF1422423A91F589][SQL: SELECT questions0_.ida_questionnaire_id as ida4_2_, questions0_.ida_questionnaire_question_id as ida1_2_, questions0_.ida_questionnaire_question_id as ida1_5_1_, questions0_.question_no as question2_5_1_, questions0_.ida_question_id as ida3_5_1_, questions0_.ida_questionnaire_id as ida4_5_1_, question1_.ida_question_id as ida1_3_0_, question1_.ida_question_type_id as ida2_3_0_, question1_.description as descript3_3_0_, question1_.validate_max as validate4_3_0_, question1_.validate_min as validate5_3_0_ FROM ida_questionnaire_question questions0_ left outer join ida_question question1_ on questions0_.ida_question_id=question1_.ida_question_id WHERE questions0_.ida_questionnaire_id=?]]
NHibernate.Loader.Loader.LoadCollection(ISessionImplementor session, Object id, IType type) +528
NHibernate.Loader.Collection.CollectionLoader.Initialize(Object id, ISessionImplementor session) +74
NHibernate.Persister.Collection.AbstractCollectionPersister.Initialize(Object key, ISessionImplementor session) +59
NHibernate.Event.Default.DefaultInitializeCollectionEventListener.OnInitializeCollection(InitializeCollectionEvent event) +573
NHibernate.Impl.SessionImpl.InitializeCollection(IPersistentCollection collection, Boolean writing) +150
NHibernate.Collection.AbstractPersistentCollection.ForceInitialization() +287
NHibernate.Engine.StatefulPersistenceContext.InitializeNonLazyCollections() +213
NHibernate.Loader.Loader.DoQueryAndInitializeNonLazyCollections(ISessionImplementor session, QueryParameters queryParameters, Boolean returnProxies) +171
NHibernate.Loader.Loader.LoadEntity(ISessionImplementor session, Object id, IType identifierType, Object optionalObject, String optionalEntityName, Object optionalIdentifier, IEntityPersister persister) +493
NHibernate.Loader.Entity.AbstractEntityLoader.Load(ISessionImplementor session, Object id, Object optionalObject, Object optionalId) +82
NHibernate.Loader.Entity.AbstractEntityLoader.Load(Object id, Object optionalObject, ISessionImplementor session) +54
NHibernate.Persister.Entity.AbstractEntityPersister.Load(Object id, Object optionalObject, LockMode lockMode, ISessionImplementor session) +206
NHibernate.Event.Default.DefaultLoadEventListener.LoadFromDatasource(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +133
NHibernate.Event.Default.DefaultLoadEventListener.DoLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +948
NHibernate.Event.Default.DefaultLoadEventListener.Load(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +436
NHibernate.Event.Default.DefaultLoadEventListener.ProxyOrLoad(LoadEvent event, IEntityPersister persister, EntityKey keyToLoad, LoadType options) +236
NHibernate.Event.Default.DefaultLoadEventListener.OnLoad(LoadEvent event, LoadType loadType) +1303
NHibernate.Impl.SessionImpl.FireLoad(LoadEvent event, LoadType loadType) +125
NHibernate.Impl.SessionImpl.Get(String entityName, Object id) +145
NHibernate.Impl.SessionImpl.Get(Type entityClass, Object id) +66
NHibernate.Impl.SessionImpl.Get(Object id) +91
SharpArch.Data.NHibernate.RepositoryWithTypedId`2.Get(IdT id) +152
Questionnaires.Controllers.QuestionnaireController.Create(String username, String id) in C:\Documents and Settings\berbor\Mine dokumenter\Visual Studio 2008\Projects\Questionnaires\Questionnaires.Controllers\QuestionnaireController.cs:40
lambda_method(ExecutionScope , ControllerBase , Object[] ) +205
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +17
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +178
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +24
System.Web.Mvc.<>c__DisplayClassa.b__7() +52
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation) +254
System.Web.Mvc.<>c__DisplayClassc.b__9() +19
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodWithFilters(ControllerContext controllerContext, IList`1 filters, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +192
System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +350
System.Web.Mvc.Controller.ExecuteCore() +110
System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +27
System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +7
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext) +119
System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext) +41
System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext) +7
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +181
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75
As for the reason I'm doing this:
One Questionnaire may have many Questions, One Question may have many Questionnaire.
I want to be able to give Questions some properties dependent on context (which Questionnaire is in), one question may be required in one questionnaire but not another etc. It's more than just order, that was just an example trying to keep it simple.
The exception is when trying to load data into Questionnaire.IList<Question>. And it's still thrown after I modify my IList<Questionnaire> to IList<QuestionnaireQuestion> and the respective mappings.
The problem then would be that Questionnaire.Questions is mapped as containing QuestionnaireQuestion but is of type Question. But if I try to map it as containing QuestionnaireQuestion my SQL does no join at all and it still fails.
Is this what I should do, just that I'm doing it wrong?
In the example I read he does it like I did as far as I can see, only difference is the newer version of FluentNhibernate that now uses Generics. So I need to specify the correct type.
Then, you should not have a List of Questionnaires in your Question class, but a List of QuestionnaireQuestion objects.
Are you sure you receive an ADO.NET Exception ?
Can you execute the generated query against your database ?
I don't understand your situation however, what is this QuestionairreQuestion class ? You're not using it in your Question class ?
I understand that you want to have an order in which your questions should occur.
So, if you have extra properties , I think you should use the QuestionairreQuestion class in your Question class.
But, if you only have this QuestionairreQuestion class in order to enforce an 'order' (and no other attributes), then, you could maybe use another Collection-Type instead of an IList.
There are collections in NHibernate which allow you to have ordered-collections (a map , for instance). So, you could use this collection in your Question class to hold Questionairre objects.
(ps: nhibernate generates an outer join, because you didn't specify in your mapping that the collection should not be null. So, an outer join is used because in some circumstances, it could be possible that you have a Question without Questionaires, as far as nhibernate is concerned).