Identity 2.1 - UserId not found but was working before - c#

This code worked before numerous times but after adding in a couple new properties for a user in Identity 2.1 it has ceased to work suddenly. I am getting a UserId not found error, despite there being a value visible in the debugger for UserId. Anyone have an idea on why this has suddenly happened? It's very frustrating to see the least.
Here's code:
(Controller)
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
model.BackgroundOnFile = false;
if (ModelState.IsValid)
{
var userDetails = new ApplicationUser { UserName = model.Email, Title = model.Title, Email = model.Email, FirstName = model.FirstName, LastName = model.LastName, LEAID = model.LEAID, SchoolID = model.SchoolID, Address1 = model.Address1, Address2 = model.Address2, City = model.City, State = model.State, PostCode = model.PostCode, BackgroundOnFile = model.BackgroundOnFile, BoardStart = model.BoardStart, BoardEnd = model.BoardEnd, PhoneNumber = model.PhoneNumber };
var result = await UserManager.CreateAsync(userDetails, model.Password);
//Assign Role
UserManager.AddToRole(userDetails.Id, "User");
if (result.Succeeded)
{
await SignInManager.SignInAsync(userDetails, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking here");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
And the Model:
public class ApplicationUser : IdentityUser
{
//Extra items required to register
public string Title { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public int LEAID { get; set; }
public int SchoolID { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
//Post Code is a string to accomodate future possible Canadian style post codes
public string PostCode { get; set; }
public bool BackgroundOnFile { get; set; }
public System.DateTime BoardStart { get; set; }
public System.DateTime BoardEnd { get; set; }
public string NominatedBy { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Add custom user claims here
return userIdentity;
}
}
And the error:
UserId not found.
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.InvalidOperationException: UserId not found.
Source Error:
Line 168:
Line 169: //Assign Role
Line 170: UserManager.AddToRole(userDetails.Id, "User");
Line 171:
Line 172: if (result.Succeeded)
Source File: h:\app\Controllers\AccountController.cs Line: 170
Stack Trace:
[InvalidOperationException: UserId not found.]
Microsoft.AspNet.Identity.<AddToRoleAsync>d__83.MoveNext() +871
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Microsoft.AspNet.Identity.AsyncHelper.RunSync(Func`1 func) +409
Microsoft.AspNet.Identity.UserManagerExtensions.AddToRole(UserManager`2 manager, TKey userId, String role) +260
UCAP.Controllers.<Register>d__7.MoveNext() in h:\Laptop Transfer\Training Code\1\CSMapAlpha3\CSMapAlpha3\Controllers\AccountController.cs:170
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Having the same error right now!
The only relevant recent action I've made is the update of packages
through NuGet:
EntityFramework 6.1.1 to 6.1.3
Microsoft ASP.NET IdentityCore 2.1.0to 2.2.1
Microsoft ASP.NET Identity EntityFramework 2.1.0 to 2.2.1
Microsoft ASP.NET Identity Owin 2.1.0 to 2.2.1
Still investigating anyway...
UPDATE
In my case I was trying to generate the confirmation token before saving the user. I learned that UserManager.GenerateEmailConfirmationTokenAsync(userID) generates the token upon a saved ID, not the one you have in memory.
Hope this helps, somehow.

This exception is not generated by Application User class, there is no property named UserID in this class. (its Id not UserId)
So there are two Tables in Identity database contains column with UserID
IdentityRole
IdentityUserRole
Therefore exception is being raised during insert in these tables, there is nothing wrong with ApplicationUser.Id. Make sure that role with name "User" exists. also check for name case i.e. "User"/"user"

If, like me, you struggle to get identity framework working without fully appreciating all the ins and outs, this may help. I was using this line to get a reference to the user:
var user = new ApplicationUser { UserName = ...
This creates a new user. What I should have done is use this line:
var user = UserManager.FindByEmail( ...
You can then reset the password like this:
string code = UserManager.GeneratePasswordResetToken(user.Id);
var result = UserManager.ResetPassword(user.Id, code, model.Password);
Note that this has no error-checking.

Related

Server cannot set status after HTTP headers have been sent with MVC custom Authorize Attribute

I am using ASP.NET MVC5 with my custom AuthorizeAttribute as below
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
var httpContext = filterContext.HttpContext;
var request = httpContext.Request;
var response = httpContext.Response;
var user = httpContext.User;
if (request.IsAjaxRequest())
{
if (user.Identity.IsAuthenticated == false)
{
response.StatusCode = (int)HttpStatusCode.Unauthorized;
response.StatusDescription = "You must be Login to process this request!";
}
else
{
response.StatusCode = (int)HttpStatusCode.Forbidden;
response.StatusDescription = "Permission Denied! Please contact your Administrator";
}
response.SuppressFormsAuthenticationRedirect = true;
response.End();
}
base.HandleUnauthorizedRequest(filterContext);
}
When i am trying to send a responce code of 403 from above code i always got an exception from Application_Error method of Global.asax.cs having
System.Web.HttpException (0x80004005): Server cannot set status after HTTP headers have been sent.
Below is the Stack trace
System.Web.HttpException (0x80004005): Server cannot set status after HTTP headers have been sent.
at System.Web.HttpResponse.set_StatusCode(Int32 value)
at System.Web.HttpResponseWrapper.set_StatusCode(Int32 value)
at DevOdeeERP.Web.Support.SharedMVC.DodBaseController.OnException(ExceptionContext filterContext)
at System.Web.Mvc.Controller.System.Web.Mvc.IExceptionFilter.OnException(ExceptionContext filterContext)
at System.Web.Mvc.ControllerActionInvoker.InvokeExceptionFilters(ControllerContext controllerContext, IList1 filters, Exception exception)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase1.End()
at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
at System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult)
at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
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)

Entity Framework 6 Update where foreign key references NULL

I have a table DivorceCases which has many fields and it's model is like:
[Key]
[Required]
public string case_id { get; set; }
public string user_id { get; set; }
public DateTime case_date { get; set; }
public virtual Transactions t { get; set; }
I am trying to add transaction details to an existing row but I am getting a [NullReferenceException: Object reference not set to an instance of an object.] error. In the DivorceCases table EF6 has created a column t_id for foreign key reference of Transactions Table.
I used :
public static void UpdatePayment(string cid,string txnno)
{
DivorceCasesContext db = new DivorceCasesContext();
DivorceCases dc = db.DivorceCase.Where(x => x.case_id == cid).Include(x => x.t).SingleOrDefault();
if (dc.t == null || dc.t.txn_id1 == null || dc.t.txn_id1 == "")
{
dc.t.txn_id1 = txnno;
dc.t.amount1 = amount.ToString();
dc.t.date1 = DateTime.Now.ToString();
}
else
{
dc.t.txn_id2 = txnno;
dc.t.amount2 = amount.ToString();
dc.t.date2 = DateTime.Now.ToString();
}
db.Set<DivorceCases>().Attach(dc);
db.Entry(dc).State = EntityState.Modified;
db.SaveChanges();
}
}
The Error I'm getting is:
[NullReferenceException: Object reference not set to an instance of an object.]
gonylaw.Helpers.Amounts.UpdatePayment(String cid, String txnno) +425
gonylaw.Controllers.PaymentController.PaymentProcessor(CreditCard c) +461
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() +9644037
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
You are accessing properties of dc.t without ensuring dc.t is not null. If the if statement short circuits on the first condition, dc.t is null, yet you attempt to assign a value to dc.t.txn_id:
if( dc.t == null || ... )
{
dc.t.txn_id1 = txnno; // null ref exception here
}
Asside from that, there are other improvements I suggest:
public static void UpdatePayment(string cid,string txnno)
{
// add using block to dispose of DbContext after you're done with it
using( DivorceCasesContext db = new DivorceCasesContext() )
{
DivorceCases dc = db.DivorceCase.Include(x => x.t)
.Where( x => x.case_id == cid )
.SingleOrDefault();
// take care of your null ref problem
if( dc.t == null )
{
dc.t = new Transactions();
}
// simplify null/empty string check
if( string.IsNullOrEmpty( dc.t.txn_id1 ) )
{
dc.t.txn_id1 = txnno;
dc.t.amount1 = amount.ToString();
dc.t.date1 = DateTime.Now.ToString();
}
else
{
dc.t.txn_id2 = txnno;
dc.t.amount2 = amount.ToString();
dc.t.date2 = DateTime.Now.ToString();
}
// this is not needed - dc is already attached to the context
// (unless you're doing something nonstandard by default
// within your DbContext)
//db.Set<DivorceCases>().Attach(dc);
//db.Entry(dc).State = EntityState.Modified;
db.SaveChanges();
}
}
}

Can't update a foreign key on an attached graph

I have an attached graph object and I can't figure out how to change the foreign key on a record. I have a Load record saved in my db. I retrieve said record by id with tracking on. I
public partial class Load
{
[Key]
public virtual int Id {get;set;}
[Required]
public virtual int AccountId { get; set; }
public virtual Account Account { get; set; }
[Required]
public virtual int CustomerId { get; set; }
[ForeignKey("CustomerId")]
public virtual Customer Customer { get; set; }
}
I then retrieve the customer record that I want to associate with the Load record
public partial class Customer
{
[Key]
public virtual int Id {get;set;}
[Required]
[MaxLength(100)]
public virtual string Name { get; set; }
}
No matter what I do, I get some sort of exception is thrown.
var customer = context.Customers.Where(x => x.Id == customerId).SingleOrDefault();
load.Customer = customer;
load.CustomerId = customer.Id;
load.ModifiedByApplicationUserId = userId;
load.ModifiedDateTime = DateTime.Now;
context.Entry(load).State = EntityState.Modified;
context.SaveChanges();
What is the proper way to go about changing the foreign key relationship on an attached graph object?
Edit. I have added the exception.
[InvalidOperationException: Attaching an entity of type 'Triton.Core.Models.Identity.ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate.]
System.Data.Entity.Core.Objects.ObjectContext.AttachSingleObject(IEntityWrapper wrappedEntity, EntitySet entitySet) +690
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +130
System.Data.Entity.Core.Objects.DataClasses.EntityReference.AddEntityToObjectStateManager(IEntityWrapper wrappedEntity, Boolean doAttach) +65
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach) +67
System.Data.Entity.Core.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach) +340
System.Data.Entity.Core.Objects.DataClasses.EntityReference1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach) +209
System.Data.Entity.Core.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach) +164
System.Data.Entity.Core.Objects.ObjectContext.AttachTo(String entitySetName, Object entity) +510
System.Data.Entity.Internal.Linq.<>c__DisplayClassa.<Attach>b__9() +97
System.Data.Entity.Internal.Linq.InternalSet1.ActOnSet(Action action, EntityState newState, Object entity, String methodName) +354
System.Data.Entity.Internal.Linq.InternalSet1.Attach(Object entity) +200
System.Data.Entity.Internal.InternalEntityEntry.set_State(EntityState value) +357
System.Data.Entity.Infrastructure.DbEntityEntry1.set_State(EntityState value) +42
Triton.Service.LoadService.UpdateCustomer(Load load, Int32 customerId, Int32 userId) in d:\BitBucket\trunk\Triton\Triton.Service\LoadService.cs:73
Triton.Web.Controllers.LoadsController.Customer(LoadViewModel model) in d:\BitBucket\trunk\Triton\Triton.Web\Controllers\LoadsController.cs:138
lambda_method(Closure , ControllerBase , Object[] ) +180
System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters) +59
System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary2 parameters) +434
System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary2 parameters) +60
System.Web.Mvc.Async.ActionInvocation.InvokeSynchronousActionMethod() +76
System.Web.Mvc.Async.AsyncControllerActionInvoker.b__39(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +36
System.Web.Mvc.Async.WrappedAsyncResult2.CallEndDelegate(IAsyncResult asyncResult) +73
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod_callback(IAsyncResult asyncResult) +42
Castle.Proxies.Invocations.AsyncControllerActionInvoker_EndInvokeActionMethod.InvokeMethodOnTarget() +103
Castle.DynamicProxy.AbstractInvocation.Proceed() +117
Glimpse.Core.Extensibility.CastleInvocationToAlternateMethodContextAdapter.Proceed() +48
Glimpse.Mvc.AlternateType.EndInvokeActionMethod.NewImplementation(IAlternateMethodContext context) +152
Glimpse.Core.Extensibility.AlternateTypeToCastleInterceptorAdapter.Intercept(IInvocation invocation) +183
Castle.DynamicProxy.AbstractInvocation.Proceed() +483
Castle.Proxies.AsyncControllerActionInvokerProxy.EndInvokeActionMethod(IAsyncResult asyncResult) +203
System.Web.Mvc.Async.AsyncInvocationWithFilters.b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass46.b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.b__1e(IAsyncResult asyncResult) +184
System.Web.Mvc.Async.WrappedAsyncResult1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651688
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
It turned out I had an object in a sub class that was being referenced so EF was trying to add it to the graph. Once I nullified that object, everything worked properly.

Value cannot be null. Parameter name: value, CreateIdentityAsync?

I created a ViewModel(UserModel) that implement IUser<int> (for customizing ASP.NET Identity 2.0)
public class UserModel : IUser<int>
{
public int Id { get; set; }
public string SecurityStamp { get; set; }
[Display(Name = "Name")]
public string FirstName { get; set; }
[Display(Name = "Last Name")]
public string LastName { get; set; }
public string FullName { get; set; }
[Display(Name = "Username")]
public string UserName { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[Display(Name = "E-Mail")]
public string Email { get; set; }
[Display(Name = "Photo")]
public string PhotoPath { get; set; }
public List<Claim> Claims { get; set; }
[IgnoreMapping]
public List<CommentModel> Comments { get; set; }
}
Everything is well, but GenerateUserIdentityAsync method.
The following code is my GenerateUserIdentityAsync in UserModel:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<UserModel, int> manager)
{
this.SecurityStamp = Guid.NewGuid().ToString();
this.Claims = new List<Claim>();
ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);//Exception : Value cannot be null. Parameter name: value
return userIdentity;
}
An exception has occurred in CreateIdentityAsync method with the following stack trace
ArgumentNullException: Value cannot be null.
Parameter name: value]
System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue) +10798181
System.Security.Claims.Claim..ctor(String type, String value) +34
Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +1458
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Smartiz.UI.Models.<GenerateUserIdentityAsync>d__2.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Models\UserModels.cs:215
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
Smartiz.UI.Controllers.<SignInAsync>d__58.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Controllers\AccountController.cs:448
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
Smartiz.UI.Controllers.<ExternalLoginCallback>d__3c.MoveNext() in e:\Works\Smartiz\Smartiz.UI\Controllers\AccountController.cs:315
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9651188
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Could you please guide me where my wrong is ?
I faced the same issue while upgrading from ASP.NET Identity 1 to ASP.NET Identity 2 and I solved it by putting a random string in the field SecurityStamp.
I found this solution here.
I hope it works for you too.
As Sam mentioned in his comment for the previous answer, my solution to this problem was to make sure that the user I was creating in in the Seed method of the EF Migration had something in the SecurityStamp. Once I did that and did a update-database -force, I was able to log in just fine.
context.Users.AddOrUpdate(u => u.UserName,
new ApplicationUser
{
UserName = "demo",
Email = "demo#demo.com",
EmailConfirmed = true,
PhoneNumberConfirmed = true,
PasswordHash = password,
PhoneNumber = "111-222-3344",
SecurityStamp = Guid.NewGuid().ToString() //THIS IS WHAT I NEEDED
});
If you created your user through some other means, you should be able to fix it by putting a string in the users db column via sql and have the same success.
In a similar way to Kevin, we were also experiencing this issue. It turns out that when seeding the database someone had forgotten to set the UserName property which produced this same error.
I had a more generic issue - some of my claims had Null values in the AspNetUserClaims table after a sql upgrade routine had run.
I solved the issue by setting the ClaimValues to an empty string.
For me it was overriding UserName field, in order to use my own Display attribute. I was using the following in my ApplicationUser class:
[Display(Name = "Whatever")]
public new string UserName { get; set; }
When I remove this, signin works as expected. I have also overriden Email and PhoneNumber but UserName causes the issue.
This problem kicked me around the office for a few hours.
This was the line causing the problem:
result = signinManager.PasswordSignIn(txtthecrmusername.Text, txtthecrmpassword.Text, RememberMe.Checked, shouldLockout:=False)
In the end, I'd added a custom field to AspNetUsers and left it null. In my haste I'd also forgotten to set it to nothing when creating users.
Custom user claims cannot be null but standard claims can.
I have stucked with the SignInManager failing to sign in the newly created user with the same error.
Solution:
I have found out that just assiging a role to the user upon creation solved the issue. Hope it helps somebody else.
await userManager.AddToRoleAsync(user, UserRoles.Basic.ToString());
For others who came here after searching for the cause of "Value cannot be null. Parameter name: value" without "CreateIdentityAsync" error, The problem may be a null value in DataAnnotations like: [Display(Name = "")]
the reason for this error is due to the empty value in on of the validation attributes
[Display(Name = " ")]

MVC : The view found at '~/.../Index.cshtml' was not created

I have created a modular MVC project to load other special web project within the same runtime.
Other projects are located in a folder at the root of the website called "Modules".
I am using the attribute PreApplicationStartMethod to load the others assemblies inside the sub directories at boot.
I have added special routes to target each modules with the namespace constraints.
I have create a class who implements RazorViewEngine to override the viewPath when a call is made for the element in the module : ~/Views/Home/Index.cshtml -> ~/Modules/ModuleTest/Views/Home/Index.cshtml.
The Index() method inside the dynamically loaded library is successfully called but i got an error when the view is rendered :
See following image : http://i.imgur.com/KoTgxg2.png
The framework tell me basically that the view has been found but he will not render it.
Do anyone has any idea why the framework refuse to render it ?
Server Error in '/' Application.
The view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.
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.InvalidOperationException: The view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.
Exception
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:
[InvalidOperationException: The view found at '~/Modules/ModuleTest/Views/Home/Index.cshtml' was not created.]
System.Web.Mvc.BuildManagerCompiledView.Render(ViewContext viewContext, TextWriter writer) +362
System.Web.Mvc.ViewResultBase.ExecuteResult(ControllerContext context) +431
System.Web.Mvc.ControllerActionInvoker.InvokeActionResult(ControllerContext controllerContext, ActionResult actionResult) +39
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +116
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultFilterRecursive(IList`1 filters, Int32 filterIndex, ResultExecutingContext preContext, ControllerContext controllerContext, ActionResult actionResult) +529
System.Web.Mvc.ControllerActionInvoker.InvokeActionResultWithFilters(ControllerContext controllerContext, IList`1 filters, ActionResult actionResult) +106
System.Web.Mvc.Async.c__DisplayClass28.b__19() +321
System.Web.Mvc.Async.c__DisplayClass1e.b__1b(IAsyncResult asyncResult) +185
System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
System.Web.Mvc.Controller.b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
System.Web.Mvc.Controller.b__15(IAsyncResult asyncResult, Controller controller) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
System.Web.Mvc.MvcHandler.b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +39
System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +9514812
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.18408
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new TestModel() { Value = "Bla" });
}
}
View
#using Easily.ModuleTest.Models;
#{ ViewBag.Title = "Test Index"; }
#model TestModel
#Model.Value
CustomRazorViewEngine
public class CustomRazorViewEngine : RazorViewEngine
{
public CustomRazorViewEngine()
{
List tmpViewLocationFormats = new List(ViewLocationFormats);
List tmpMasterLocationFormats = new List(MasterLocationFormats);
List tmpPartialViewLocationFormats = new List(PartialViewLocationFormats);
foreach (string moduleDirectory in EasilyModulesContainer.Modules.Select(x => x.Directory))
{
foreach (string viewLocationFormat in ViewLocationFormats)
tmpViewLocationFormats.Add(viewLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
foreach (string masterLocationFormat in MasterLocationFormats)
tmpMasterLocationFormats.Add(masterLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
foreach (string partialViewLocationFormat in PartialViewLocationFormats)
tmpPartialViewLocationFormats.Add(partialViewLocationFormat.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, moduleDirectory)));
}
ViewLocationFormats = tmpViewLocationFormats.ToArray();
MasterLocationFormats = tmpMasterLocationFormats.ToArray();
PartialViewLocationFormats = tmpPartialViewLocationFormats.ToArray();
}
protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
{
return base.CreateView(controllerContext, GetPath(controllerContext, viewPath), masterPath);
}
protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
{
return base.CreatePartialView(controllerContext, GetPath(controllerContext, partialPath));
}
private string GetPath(ControllerContext controllerContext, string path)
{
if (!controllerContext.RouteData.Values.ContainsKey("_module"))
return path;
Module module = ModulesContainer.Modules.SingleOrDefault(x => x.Name == controllerContext.RouteData.GetRequiredString("_module"));
return path.Replace("~/", string.Format("~/{0}/{1}/", Constants.ModulesDirectory, module.Directory));
}
}
I found the problem by debugging into http://aspnetwebstack.codeplex.com/.
I actually load the library who contain the controllers from another folder than bin in my ModulesContainer class (see question). But inside System.Web.Mvc.dll, one method try to find my controller type by doing a Assembly.Load() in the default directory, its why the BuildManager.GetCompiledType() return null.
I have found a simple way to override this method with :
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomainAssemblyResolve;
and
private static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
if (args.RequestingAssembly != null)
return args.RequestingAssembly;
Module module = _modules.SingleOrDefault(x => x.Assembly.FullName == args.Name);
if (module != null)
return module.Assembly;
throw new Exception(string.Format("Unable to load assembly {0}", args.Name));
}
I'm just looking inside my pre-built dll cache to find the already loaded assembly.
#Lex2193: I found problem in your answer.
When I was using your code it was working well except for situation, where referenced assembly has another reference on which it depends:
Module [M] => Dependency [D] => DeepDependency [DD]
When you use in module object from [D] that has in it some calls to something in [DD]. It will fail on TypeLoad exception. Because of requesting assembly.
So i edited code to first searhing for module:
public static Assembly CurrentDomainAssemblyResolve(object sender, ResolveEventArgs args)
{
Assembly module = modules.SingleOrDefault(x => x.FullName == args.Name);
if (module != null)
return module;
if (args.RequestingAssembly != null)
return args.RequestingAssembly;
throw new Exception(string.Format("Could not load file or assembly {0}", args.Name));
}

Categories

Resources