IOwinContext context is null - c#

I have moved my mvc4 application into mvc5 by creating a new application and copying the code in - to avoid any conflicts while updating the DLL's
When I debug my new solution, no pages can be loaded as the built in IdentityConfig.cs is throwing a nullreferenceexception on the IOwinContext.
the code is breaking at the following line
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));
As this is practically OOTB mvc5, and I haven't worked with it before, I am not sure why it is throwing null.
any help?

I get that this is old, but I spent a while figuring it out,and I want to spare others the pain.
Make sure there is a Create() method in your DB context.
Make sure in Startup.Auth there is a line similar to: app.CreatePerOwinContext(ApplicationDbContext.Create);
Make sure (and this is critical) that last line is not commented out.

ok, this is an answer and probably a unique scenario. I actually had a dbcontext with exactly the same name as the one I wanted to use (it was legacy code) and I had actually added a Create statement to that same dbcontext by mistake...so, it was calling the wrong dbcontext and the wrong create method!
All sorted now though :-)

Related

Resolving issue: ActionFilterAttribute in Unity

I have found this blogpost: http://blog.bitdiff.com/2012/05/sharing-common-view-model-data-in.html?showComment=1499113088147#c5286707438454380796 about sharing strongly-typed common view model data in asp.net mvc, and it look to me like it would solve of the problems I have with keeping track of some user related data across views.
I’m a complete novice when it comes to DI and Unity as I have never used it before, but I have an understanding of the benefits of using it. The post is from May 2012 but should as far as I can see still be valid, perhaps with some small changes.
I’m using C#, MVC 5, EF, Code First, Migrations, Unity V4.01 and Unity.MVC V4.01 with VS2015 Community Edition.
I have followed the blogpost from start to near finish (lacking the test) and all compiles. I have one problem though, this line causes problems:
GlobalFilters.Filters.Add(container.Resolve<LayoutModelAttribute>(), 1);
As far as I can tell the right place to call place the line is in the FilterConfig.cs file in the App_start folder where I’ve done this:
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
var container = UnityConfig.GetConfiguredContainer();
filters.Add(container.Resolve<LayoutModelAttribute>());
}
The container.Resolve gets a squiggly line beneath it and the project won’t compile. The error description is this:
“The non-generic method 'IUnityContainer.Resolve(Type, string, params
ResolverOverride[])' cannot be used with type arguments”
I’ve tried some other places also, but the result is the same, I now lean towards the notion that Unity itself has changed since 2012, and now must be resolved in a different way.
I’m pretty sure I’m doing something wrong and that it properly is because the blogpost is from 2012 and Unity now works in a different way. Due to my lack of experience with Unity, I’m unable to figure out how to change the line of code that won’t compile or to what extend and how to refactor the blogpost if necessary.
I’m hoping someone out there can point me in the right direction.
It seems you are using container without it having a capability of injecting. Have a look at the following answer
Simple Injector property injection on action filter

EF6 Complaining that unused Model has no Key

I just spent some time resolving the strangest bug, and I can't figure out why it happened. Maybe someone can follow along and shed some light on why...?
tl;dr: lightweight MembershipContext fails due to some completely unrelated object not having and ID field, but only does so when running under MVC: all integration tests that make sure this stuff works correctly... they work correctly.
What I Have:
I have a solution with a number of projects. The pertinent ones are:
LPA.Domain (contains POCOs for business objects/behavior)
LPA.Data (contains EF6 stuff with FluentAPI config and references LPA.Domain)
LPA.Web (contains an MVC project, refs Data and Domain)
This is a very normal setup for us and the project has been in development for some time with no issues.
Within the Data project I have two DbContexts that are used. One, MembershipContext is used only during login and bypasses the user-based audit system to validate the user. The MembershipContext has only three entities: User, UserMembershipDetail and UserRole.
The second, CoreContext has all the normal stuff (including tracking the currently logged in user ID for audit purposes). This has many entities.
What I Did:
Now let's pretend I spend a few days doing some domain-level development. I add handful of classes, set up their db counterparts, build the models (in CoreContext, MembershipContext doesn't change), write integration tests for the models and unit tests for the domain work. All is well. I haven't touched MembershipContext at all.
Part of what I did was add a new class to LPA.Domain to deal with an object called Matter (legal matter). This was to mock up a single method I needed elsewhere, but was not set up in the db (yet). I added an Ignore() on the appropriate entity and will flesh it out later. No biggie, right? All still happening in the CoreContext
What Happened:
I get done with a few days of domain-level development, then go to fire up the LPA.Web project and hit a strange error when trying to log in. Some digging around tells me basically this:
When trying to get from Users in MembershipContext, it's throwing an exception saying that the LPA.Data.Matter EntityType has no key.
A couple confusing things about this:
LPA.Data.Matter is not an object. The Matter object resides in the LPA.Domain.Legal namespace. Presumably this is an internal thing with EF6 as it creates it's own object to deal with things. Ok, I can buy that...
MembershipContext makes no use of Matter at all. The three objects it does make use of have no downstream references (shallow or deep) to the Matter object.
Integration Testing to build/retrieve the MembershipContext.Users works fine! (Users being the offending Entity in the exception) I think this must indicate some different method between how the LPA.Web project is loading the LPA.Data.MembershipContext as opposed to how the test project is, but that doesn't make much sense to me...
This Matter object is used in testing for the domain project and the LPA.Data.CoreContext tests without issue, why does it fail on the Membership and only when using it through an MVC project?
How I Fixed It:
As noted, I added the Matter class as a quick helper on the domain but hadn't fleshed out the storage stuff yet. As such, I had no ID field on the object. The resolution was as simple as adding an ID field.
This resolves the problem, but does not in any way help me understand what went wrong.
For what it's worth, in the MVC project we use a custom user and role provider based on the ExtendedMembershipProvider, which uses a custom repository (that in turn uses the MembershipContext). The instantiation of the MembershipContext is identical between the test and the MVC projects. I can't imagine why they'd act differently.
It's as if something in the MVC project is forcing EF6 to read/validate every object in the Domain class to ensure their validity to a non-existing data model.
Does anyone have the slightest idea why this happened? I'm baffled, myself.

app.CreatePerOwinContext and sharing the db context

Identity requires me to use this to create a db context:
app.CreatePerOwinContext(EFDbContext.Create);
So I need to get the Microsoft Unity IOC correct.
The issue I was coming across was that I had accidently made 2 database contexts. One for everything else in my application and one for the user stuff. I started writing functions for the user stuff under the wrong context and made it throw errors.
So I decided to use a lifetime manager for my EFDbContext:
// Database context
container.RegisterType<EFDbContext>(new PerThreadLifetimeManager());
// Microsoft identity stuff
container.RegisterType<ApplicationSignInManager>();
container.RegisterType<ApplicationUserManager>();
container.RegisterType<IAuthenticationManager>(
new InjectionFactory(c => HttpContext.Current.GetOwinContext().Authentication));
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(
new InjectionConstructor(typeof(EFDbContext)));
I am wondering if this will cause issues in the future?
Edit:
I found out that the asynchronous stuff in Identity might have been causing an issue with this set up...
I have now used HierarchicalLifetimeManager, it reads like the kind of thing I need... Still unsure if i'm going to come across any issues?
you should be ok - when you do a Resolve or ResolveAll to get the object back from the container and when you are set on using PerThreadLifeTimeManager then Unity will return the same instance for that thread. So unless you are doing multithreaded apps, then you should be fine.
ref: https://msdn.microsoft.com/en-us/library/ff660872(v=pandp.20).aspx
I found this article which seemed to do exactly what was needed:
http://www.wiktorzychla.com/2013/03/unity-and-http-per-request-lifetime.html
It has a request lifetime instead of thread or container... I was noticing odd problems when using hierarchical and this second one seems to work a charm!

Why am I getting DbContext Has Changed exception when using NUnit?

I'm using Entity Framework 5 in my project. And I wanted to test some new funcionalities.
What happened is that eventhough my db is UPDATED, (when I add a migration it does not add anything else) and eventhough if I run my project it runs just fine. When I try to test the project with NUNIT I get this exception:
System.InvalidOperationException : The model backing the 'DbContext' context has changed since the database was created. Consider using Code First Migrations to update the database
Has any of you have this problem? If so how can I solve it?
Well, my original answer got deleted, guess because it wasn't really an answer as much as a statement that I had the same problem. At this point I have found an answer of sorts, so maybe this one will pass muster.
Of course, I only assume we are having the same issue, but it seems pretty likely since the symptoms are exactly the same. What I discovered is the connection string for my repository was not getting set correctly even though I had set it up "correctly" in a config file using the MyTestProject.dll.config naming convention. Seems like NUnit isn't using the connection string from the config for some reason.
I've set up a temporary solution where I use a different constructor that forces the correct connection string for my repository when creating it for NUnit. Easy to implement this since I'm using DI to create the repository and just need to ask the factory for a different flavor when testing. Working now to figure out why NUnit doesn't use the config file as it seems like it should.
Maybe not a complete answer, but at least this solution got me back to where I can test... We'll see if this one gets deleted.

Mysql C# Connector/Net MembershipProvider seems to be bug - is it a bug or did i do it wrong

I’m learning my way around ASP.NET MVC using vs2010 and .NET4 – nothing for production use, just for my own personal use.
I created a default ASP.NET MVC which comes with pre-existing home page, about page and login and registration pages. In attempting to use the existing login and registration pages I (not having an SQL server) replaced the SQLMembershipProvider with the MySQLMembershipProvider found in Connector/NET in the MySQL.Web.Security.
However this didn’t work straight away, aside from the common issue people seemed to have with autogeneration of the schema (solved by googling) I had two other problems that I noticed.
The first was that if left unset or simply as an empty string, the PasswordStrengthRegularExpression would cause a Null Exception in the MySQLMembershipProvider. I solved that by modifying the providers code to fix the “if” statement where the problem was occurring. (If I recall, it was only checking that the string wasn’t empty, it didn’t check for the string being null)
The second was that the MySQLMembershipProvider has an Initialize method, overridden from the base class, which must be called on each instantiation of the provider. This method was being called only on the very first instantiation but not again afterwards (determined by stepping through the code and use of breakpoints). The provider appears to be instantiated once per page load.
My solution (not the best) has been to modify the MySQLMembershipProvider to create static variables to store the arguments of the call to Initialize and a variable to store whether or not the object has been initialized. I then put a call to the Initialize method at the beginning of every other method. The Initialize method was modified to return instantly if the object had already been initialized.
My query is this: Is the MySQLMembershipProvider flawed and thus the issues I’m describing are bugs or have I misunderstood something and not correctly used the MySQLMembershipProvider?
N.B. If you want to see code, please tell me which bits as 90% of it is auto generated or available from the mysql dev site as source. There is quite a lot.

Categories