c# - No users have been created during Seed method using UserManager in ASP .NET MVC applications -
when seed
method runs, records/objects added database.
every object added should till try add users application(at bottom of seed
method). no 1 added. there lot of sql
exceptions thrown posted @ bottom. thrown if seed
method empty.
how add users entity framework managed database? created code following scott allen's tutorial.
protected override void seed(webapplication2.models.applicationdbcontext context) { system.diagnostics.debug.writeline("seed started");//it works if (!context.persons.any()) { var persons = new list<person> { new person{firstname = "john", lastname = "doe", cellnumber = "123-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "312312312", notes = "annoying"}, new person{firstname = "anna", lastname = "doe", cellnumber = "113-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "548555672", notes = "less annoying"} }; persons.foreach(person => context.persons.addorupdate(person)); context.savechanges(); } if (!context.meetings.any()) { var meetings = new list<meeting>{ new meeting{personid = 1, body = "body of meeting", date = datetime.now} }; meetings.foreach(meeting => context.meetings.addorupdate(meeting)); context.savechanges(); } if (!context.statuses.any()) { var statuses = new list<status> { new status{name = "ok"}, new status {name = "not_ok"} }; statuses.foreach(status => context.statuses.addorupdate(status)); context.savechanges(); } //everything till works //users seeding if (!context.users.any()) { system.diagnostics.debug.writeline("user seed"); try { var store = new userstore<applicationuser>(context); var manager = new usermanager<applicationuser>(store); //why user not created var user1 = new applicationuser { username = "admin", email = "informatyka4444@wp.pl" }; var user2 = new applicationuser { username = "emp", email = "informatyka4444@wp.pl" }; manager.create(user1, "admin"); manager.create(user2, "emp"); context.savechanges(); } catch (exception e) { system.diagnostics.debug.writeline("there exception"); } } }
edit:
i added prints section add users posted output sql exceptions.
if (!context.users.any()) { system.diagnostics.debug.writeline("user seed"); try { system.diagnostics.debug.writeline("1"); var store = new userstore<applicationuser>(context); var manager = new usermanager<applicationuser>(store); //why user not created system.diagnostics.debug.writeline("2"); var user1 = new applicationuser { username = "admin", email = "informatyka4444@wp.pl" }; var user2 = new applicationuser { username = "emp", email = "informatyka4444@wp.pl" }; system.diagnostics.debug.writeline("3"); manager.create(user1, "admin"); manager.create(user2, "emp"); system.diagnostics.debug.writeline("4"); context.savechanges(); system.diagnostics.debug.writeline("5"); } catch (exception e) { system.diagnostics.debug.writeline("there exception"); } system.diagnostics.debug.writeline("6");
output:
constrctor constrctor first chance exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll first chance exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll first chance exception of type 'system.data.sqlclient.sqlexception' occurred in system.data.dll first chance exception of type 'system.data.entity.core.entitycommandexecutionexception' occurred in entityframework.dll first chance exception of type 'system.data.entity.core.entitycommandexecutionexception' occurred in entityframework.dll first chance exception of type 'system.data.entity.core.entitycommandexecutionexception' occurred in entityframework.dll first chance exception of type 'system.data.entity.core.entitycommandexecutionexception' occurred in entityframework.sqlserver.dll constrctor seed started user seed 1 2 3 'iisexpress.exe' (clr v4.0.30319: /lm/w3svc/14/root-1-130527942456023568): loaded 'c:\windows\microsoft.net\assembly\gac_msil\mscorlib.resources\v4.0_4.0.0.0_pl_b77a5c561934e089\mscorlib.resources.dll'. module built without symbols. 4 5 6 'iisexpress.exe' (clr v4.0.30319: /lm/w3svc/14/root-1-130527942456023568): loaded 'c:\windows\microsoft.net\assembly\gac_msil\system.servicemodel.internals\v4.0_4.0.0.0__31bf3856ad364e35\system.servicemodel.internals.dll'. symbols loaded.
edit 2
here constructor
:
models.identitymodels.cs
using system.security.claims; using system.threading.tasks; using microsoft.aspnet.identity; using microsoft.aspnet.identity.entityframework; using system.data.entity; using system.data.entity.modelconfiguration.conventions; namespace webapplication2.models { // can add profile data user adding more properties applicationuser class, please visit http://go.microsoft.com/fwlink/?linkid=317594 learn more. public class applicationuser : identityuser { public async task<claimsidentity> generateuseridentityasync(usermanager<applicationuser> manager) { // note authenticationtype must match 1 defined in cookieauthenticationoptions.authenticationtype var useridentity = await manager.createidentityasync(this, defaultauthenticationtypes.applicationcookie); // add custom user claims here return useridentity; } } public class applicationdbcontext : identitydbcontext<applicationuser> { public applicationdbcontext() : base("defaultconnection", throwifv1schema: false) { system.diagnostics.debug.writeline("constrctor"); } public dbset<person> persons { get; set; } public dbset<meeting> meetings { get; set; } public dbset<status> statuses { get; set; } protected override void onmodelcreating(dbmodelbuilder modelbuilder) { base.onmodelcreating(modelbuilder); modelbuilder.conventions.remove<pluralizingtablenameconvention>(); } public static applicationdbcontext create() { return new applicationdbcontext(); } } }
migrations.confriguration.cs
namespace webapplication2.migrations { using microsoft.aspnet.identity; using microsoft.aspnet.identity.entityframework; using system; using system.collections.generic; using system.data.entity; using system.data.entity.migrations; using system.linq; using webapplication2.models; internal sealed class configuration : dbmigrationsconfiguration<webapplication2.models.applicationdbcontext> { public configuration() { automaticmigrationsenabled = true; contextkey = "webapplication2.models.applicationdbcontext"; } protected override void seed(webapplication2.models.applicationdbcontext context) { /* system.diagnostics.debug.writeline("seed started"); if (!context.persons.any()) { var persons = new list<person> { new person{firstname = "john", lastname = "doe", cellnumber = "123-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "312312312", notes = "annoying"}, new person{firstname = "anna", lastname = "doe", cellnumber = "113-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "548555672", notes = "less annoying"} }; persons.foreach(person => context.persons.addorupdate(person)); context.savechanges(); } if (!context.meetings.any()) { var meetings = new list<meeting>{ new meeting{personid = 1, body = "body of meeting", date = datetime.now} }; meetings.foreach(meeting => context.meetings.addorupdate(meeting)); context.savechanges(); } if (!context.statuses.any()) { var statuses = new list<status> { new status{name = "ok"}, new status {name = "not_ok"} }; statuses.foreach(status => context.statuses.addorupdate(status)); context.savechanges(); }*/ //users seeding if (!context.users.any()) { system.diagnostics.debug.writeline("user seed"); try { system.diagnostics.debug.writeline("1"); var store = new userstore<applicationuser>(context); var manager = new usermanager<applicationuser>(store); //why user not created system.diagnostics.debug.writeline("2"); var user1 = new applicationuser { username = "admin", email = "informatyka4444@wp.pl" }; var user2 = new applicationuser { username = "emp", email = "informatyka4444@wp.pl" }; system.diagnostics.debug.writeline("3"); manager.create(user1, "admin"); manager.create(user2, "emp"); system.diagnostics.debug.writeline("4"); context.savechanges(); system.diagnostics.debug.writeline("5"); } catch (exception e) { system.diagnostics.debug.writeline("there exception"); } system.diagnostics.debug.writeline("6"); } } } }
global.asax
using system; using system.collections.generic; using system.data.entity; using system.linq; using system.web; using system.web.mvc; using system.web.optimization; using system.web.routing; using webapplication2.migrations; using webapplication2.models; namespace webapplication2 { public class mvcapplication : system.web.httpapplication { protected void application_start() { system.diagnostics.debug.writeline("application_start"); database.setinitializer(new migratedatabasetolatestversion<applicationdbcontext, configuration>()); new applicationdbcontext().database.initialize(true); arearegistration.registerallareas(); filterconfig.registerglobalfilters(globalfilters.filters); routeconfig.registerroutes(routetable.routes); bundleconfig.registerbundles(bundletable.bundles); } } }
web.config
<?xml version="1.0" encoding="utf-8"?> <!-- more information on how configure asp.net application, please visit http://go.microsoft.com/fwlink/?linkid=301880 --> <configuration> <configsections> <section name="entityframework" type="system.data.entity.internal.configfile.entityframeworksection, entityframework, version=6.0.0.0, culture=neutral, publickeytoken=b77a5c561934e089" requirepermission="false" /> <!-- more information on entity framework configuration, visit http://go.microsoft.com/fwlink/?linkid=237468 --></configsections> <connectionstrings> <add name="defaultconnection" connectionstring="data source=(localdb)\v11.0;attachdbfilename=|datadirectory|\aspnet-webapplication2-20140711041006.mdf;initial catalog=aspnet-webapplication2-20140711041006;integrated security=true" providername="system.data.sqlclient" /> </connectionstrings> <appsettings> <add key="webpages:version" value="3.0.0.0" /> <add key="webpages:enabled" value="false" /> <add key="clientvalidationenabled" value="true" /> <add key="unobtrusivejavascriptenabled" value="true" /> </appsettings> <system.web> <authentication mode="none" /> <compilation debug="true" targetframework="4.5.1" /> <httpruntime targetframework="4.5.1" /> </system.web> <system.webserver> <modules> <remove name="formsauthenticationmodule" /> </modules> </system.webserver> <runtime> <assemblybinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentassembly> <assemblyidentity name="system.web.helpers" publickeytoken="31bf3856ad364e35" /> <bindingredirect oldversion="1.0.0.0-3.0.0.0" newversion="3.0.0.0" /> </dependentassembly> <dependentassembly> <assemblyidentity name="system.web.mvc" publickeytoken="31bf3856ad364e35" /> <bindingredirect oldversion="1.0.0.0-5.1.0.0" newversion="5.1.0.0" /> </dependentassembly> <dependentassembly> <assemblyidentity name="system.web.optimization" publickeytoken="31bf3856ad364e35" /> <bindingredirect oldversion="1.0.0.0-1.1.0.0" newversion="1.1.0.0" /> </dependentassembly> <dependentassembly> <assemblyidentity name="system.web.webpages" publickeytoken="31bf3856ad364e35" /> <bindingredirect oldversion="1.0.0.0-3.0.0.0" newversion="3.0.0.0" /> </dependentassembly> <dependentassembly> <assemblyidentity name="webgrease" publickeytoken="31bf3856ad364e35" /> <bindingredirect oldversion="0.0.0.0-1.5.2.14234" newversion="1.5.2.14234" /> </dependentassembly> </assemblybinding> </runtime> <entityframework> <!-- <contexts> <context type="webapplication2.models.applicationdbcontext, webapplication2"> <databaseinitializer type="webapplication2.migrations.configuration, webapplication2" /> </context> </contexts>--> <defaultconnectionfactory type="system.data.entity.infrastructure.sqlconnectionfactory, entityframework" /> <providers> <provider invariantname="system.data.sqlclient" type="system.data.entity.sqlserver.sqlproviderservices, entityframework.sqlserver" /> </providers> </entityframework> </configuration>
edit 3(partialy solved problem): below did job. why way introduced in mvc 5(user manager above) not work?
system.diagnostics.debug.writeline("before " + !context.users.any()); if (!context.users.any()) { system.diagnostics.debug.writeline("inside"); var hasher = new passwordhasher(); var users = new list<applicationuser> { new applicationuser{username = "admin", passwordhash = hasher.hashpassword("admin")} }; users.foreach(user => context.users.addorupdate(user)); context.savechanges(); }
current version of migrations/(directory)/.configuration.cs seed
method inside:
namespace webapplication2.migrations { using microsoft.aspnet.identity; using system; using system.collections.generic; using system.data.entity.migrations; using system.data.entity.validation; using system.linq; using webapplication2.models; internal sealed class configuration : dbmigrationsconfiguration<webapplication2.models.applicationdbcontext> { public configuration() { automaticmigrationsenabled = true; contextkey = "webapplication2.models.applicationdbcontext"; } protected override void seed(webapplication2.models.applicationdbcontext context) { system.diagnostics.debug.writeline("seed started"); if (!context.persons.any()) { var persons = new list<person> { new person{firstname = "john", lastname = "doe", cellnumber = "123-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "312312312", notes = "annoying"}, new person{firstname = "anna", lastname = "doe", cellnumber = "113-456-789", secondaryphonenumber = "98873213", address = "1street 2",birthdate = datetime.now.date, pesel = "548555672", notes = "less annoying"} }; persons.foreach(person => context.persons.addorupdate(person)); context.savechanges(); } if (!context.meetings.any()) { var meetings = new list<meeting>{ new meeting{personid = 1, body = "body of meeting", date = datetime.now} }; meetings.foreach(meeting => context.meetings.addorupdate(meeting)); context.savechanges(); } if (!context.statuses.any()) { var statuses = new list<status> { new status{name = "ok"}, new status {name = "not_ok"} }; statuses.foreach(status => context.statuses.addorupdate(status)); context.savechanges(); } //users seeding system.diagnostics.debug.writeline("before " + !context.users.any()); if (!context.users.any()) { system.diagnostics.debug.writeline("inside"); var hasher = new passwordhasher(); try { var users = new list<applicationuser> { new applicationuser{passwordhash = hasher.hashpassword("testpass44!"), email = "informatyka4444@wp.pl", username = "informatyka4444@wp.pl"}, new applicationuser{passwordhash = hasher.hashpassword("testpass44!"), email = "informatyka4445@wp.pl", username = "informatyka4445@wp.pl"} }; users.foreach(user => context.users.addorupdate(user)); context.savechanges(); } catch (dbentityvalidationexception e) { system.diagnostics.debug.writeline("exc: "); foreach (dbentityvalidationresult result in e.entityvalidationerrors) { foreach (dbvalidationerror error in result.validationerrors) { system.diagnostics.debug.writeline(error.errormessage); } } } } } } }
you have current manager context:
var manager = httpcontext.current.getowincontext().getusermanager<applicationusermanager>();
be sure inlude namespace this:
using microsoft.aspnet.identity.owin;
using manager instance, should able create user correctly.
Comments
Post a Comment