本文整理汇总了C#中ApplicationUserManager.Create方法的典型用法代码示例。如果您正苦于以下问题:C# ApplicationUserManager.Create方法的具体用法?C# ApplicationUserManager.Create怎么用?C# ApplicationUserManager.Create使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ApplicationUserManager
的用法示例。
在下文中一共展示了ApplicationUserManager.Create方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CreateUser
public bool CreateUser(ApplicationUser user, string password)
{
var um = new ApplicationUserManager(
new UserStore<ApplicationUser>(context));
var idResult = um.Create(user, password);
return idResult.Succeeded;
}
示例2: CreateAccount
public ActionResult CreateAccount(NewUserModel model)
{
if (ModelState.IsValid)
{
ApplicationUserManager um = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()));
var pass = StringHelper.RandomString(8, 10);
var user = new ApplicationUser()
{
Id = Guid.NewGuid().ToString(),
UserName = model.UserName,
Email = model.Email,
Created = DateTime.Now,
LastLogin = null
};
var result = um.Create(user, pass);
if(result.Succeeded)
{
MailHelper.WelcomeSendPassword(user.UserName, user.Email, pass);
return RedirectToAction("Index", "People");
}
else
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
}
return View(model);
}
示例3: Init
public static void Init()
{
using (var context = new AppDbContext())
{
if (!context.Users.Any())
{
var manager = new ApplicationUserManager(new UserStore<User>(context));
manager.Create(new User
{
Email = "[email protected]",
UserName = "Matt Honeycutt",
}, "Password1");
manager.Create(new User
{
Email = "[email protected]",
UserName = "John Doe",
}, "Password1");
manager.Create(new User
{
Email = "[email protected]",
UserName = "Jane Doe",
}, "Password1");
}
if (!context.Customers.Any())
{
AddNewCustomers(context);
AddExistingCustomers(context);
AddTerminatedCustomers(context);
context.SaveChanges();
}
}
}
示例4: SeedIdentityForEF
public static void SeedIdentityForEF(ApplicationDbContext context)
{
if ((!context.Roles.Any()) && (!context.Users.Any()))
{
var roleStore = new ApplicationRoleStore(context);
//var roleManager = new RoleManager<ApplicationRole, int>(roleStore);
var roleManager = new ApplicationRoleManager(roleStore);
var role = new ApplicationRole
{
Name = "Admin",
Description = "Super Admin User group"
};
roleManager.Create(role);
var userStore = new UserStore<ApplicationUser,
ApplicationRole,
int,
ApplicationUserLogin,
ApplicationUserRole,
ApplicationUserClaim>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser
{
Email = "[email protected]",
UserName = "SuperUser",
EmailConfirmed = true
};
user.FirstName = "Jack";
user.LastName = "Smith";
userManager.Create(user, "[email protected]");
var result = userManager.SetLockoutEnabled(user.Id, false);
userManager.AddToRole(user.Id, "Admin");
//added group manager
var groupManager = new ApplicationGroupManager(roleManager,userManager);
var newGroup = new ApplicationGroup("SuperAdmins", "Full Access to All");
groupManager.CreateGroup(newGroup);
groupManager.SetUserGroups(user.Id, new int[] { newGroup.Id });
groupManager.SetGroupRoles(newGroup.Id, new string[] { role.Name });
}
}
示例5: Configuration
public void Configuration(IAppBuilder app)
{
var context = new ApplicationDbContext();
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
var UserManager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
if (!RoleManager.RoleExists("Admin"))
{
RoleManager.Create(new IdentityRole("Admin"));
RoleManager.Create(new IdentityRole("Teacher"));
}
if (UserManager.FindByName("[email protected]") == null)
{
var user = new ApplicationUser { Name = "管理员", UserName = "[email protected]", Email = "[email protected]" };
UserManager.Create(user, "administrator");
UserManager.AddToRole(UserManager.FindByName(user.UserName).Id, "Admin");
}
ConfigureAuth(app);
}
示例6: SeedUsers
public static int SeedUsers(ApplicationDbContext context)
{
var counter = 0;
var seedUsers = new List<ApplicationUser>();
var mgr = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
var reader = File.OpenText(SeedPath + "namesAndEmails.csv");
while (!reader.EndOfStream)
{
var ln = reader.ReadLine().Split('|');
seedUsers.Add(new ApplicationUser(ln[0], ln[1], ln[2]));
}
foreach (
var usr in seedUsers.Where(usr => context.Users.FirstOrDefault(y => y.UserName == usr.UserName) == null)
)
{
mgr.Create(usr, "Password?123");
counter++;
}
context.SaveChanges();
return counter;
}
示例7: Main
static void Main(string[] args)
{
if (args == null || args.Length < 3)
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
string exeName = Path.GetFileName(codeBase);
Console.WriteLine("usage: {0} <username> <password> <role>", exeName);
return;
}
var username = args[0];
var password = args[1];
var role = args[2];
var mongoContext = new MongoContext();
var identityContext = new ApplicationIdentityContext(mongoContext);
var store = new UserStore<ApplicationUser>(identityContext);
var manager = new ApplicationUserManager(store);
var user = new ApplicationUser { UserName = username };
var result = manager.Create(user, password);
if (result.Succeeded)
{
var roles = new[] { role };
var roleResult = manager.AddUserToRolesAsync(user.Id, roles);
roleResult.Wait();
Console.WriteLine("user created!");
Console.ReadKey();
return;
}
foreach (var error in result.Errors)
{
Console.WriteLine(error);
}
Console.ReadKey();
}
示例8: RegisterUser
/// <summary>
/// Registers a new user and also ensures that address is added into the db properly
/// </summary>
/// <param name="model">The RegisterBindingModel with appropriate data</param>
/// <param name="userManager">The UserManager context to perform the add</param>
/// <returns>StatusResult</returns>
public static StatusResult<UserInfoViewModel> RegisterUser(RegisterBindingModel model, ApplicationUserManager userManager)
{
UserInfoViewModel obj = null;
try
{
var user = ApplicationUser.CreateUser(model);
IdentityResult userResult = userManager.Create(user, model.Password);
if (!userResult.Succeeded)
{
return StatusResult<UserInfoViewModel>.Error();
}
model.Address = null;
// add the address
var addressResult = UserAddressManager.InsertUserAddress(model, user.Id);
if (addressResult.Code != StatusCode.OK)
{
//TODO:: Need to handle error where the address was not added successfully, can't find anything to rollback CreateAsync,
// it seems like CreateAsync is set to autocommit or something.
// This is a little quick and dirty and hacky, but here i am just going to delete the user if we dont succeed with adding the address
userManager.Delete(user);
return StatusResult<UserInfoViewModel>.Error(addressResult.Message);
}
obj = new UserInfoViewModel()
{
FirstName = model.FirstName,
LastName = model.LastName,
Email = model.Email,
Id = user.Id
};
}
catch (Exception ex)
{
return StatusResult<UserInfoViewModel>.Error(ex.Message);
}
return StatusResult<UserInfoViewModel>.Success(obj);
}
示例9: Seed
public static void Seed(MedSimDbContext context)
{
#if !DEBUG
throw new NotImplementedException("this should not be being used in a production environment - security changes required");
#endif
try
{
if (!context.Roles.Any())
{
//not in production
//context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction,
// "alter database [" + context.Database.Connection.Database + "] set single_user with rollback immediate");
//
var roleStore = new RoleStore<AspNetRole, Guid, AspNetUserRole>(context);
var roleManager = new RoleManager<AspNetRole, Guid>(roleStore);
var role = new AspNetRole
{
Id = Guid.NewGuid(),
Name = RoleConstants.Admin
};
roleManager.Create(role);
}
if (!context.Users.Any())
{
var userStore = new CustomUserStore(context);
var userManager = new ApplicationUserManager(userStore);
var user = new AspNetUser
{
Email = "[email protected]",
UserName = "admin"
};
var result = userManager.Create(user, password: "Admin_1");
if (result.Succeeded)
{
userManager.AddToRole(user.Id, RoleConstants.Admin);
}
else
{
throw new DbSeedException(result.Errors);
}
}
}
catch (DbEntityValidationException ex)
{
// Retrieve the error messages as a list of strings.
var errorMessages = ex.EntityValidationErrors
.SelectMany(x => x.ValidationErrors)
.Select(x => x.ErrorMessage);
// Join the list to a single string.
var fullErrorMessage = string.Join("; ", errorMessages);
// Combine the original exception message with the new one.
var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage);
// Throw a new DbEntityValidationException with the improved exception message.
throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors);
}
}
示例10: SeedApplicationUser
private static User SeedApplicationUser(DbContext dbContext)
{
const string email = "[email protected]";
const string password = "HakunaMatata-23";
var userManager = new ApplicationUserManager(new UserStore<User>(dbContext));
userManager.UserValidator = new UserValidator<User>(userManager)
{
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = true
};
userManager.PasswordValidator = new PasswordValidator
{
RequiredLength = 6,
RequireNonLetterOrDigit = true,
RequireDigit = true,
RequireLowercase = true,
RequireUppercase = true,
};
var user = new User
{
Email = email,
UserName = email,
FirstName = "John",
LastName = "Doe"
};
var result = userManager.Create(user, password);
if (!result.Succeeded) return null;
userManager.AddToRole(user.Id, "Admin");
return user;
}
示例11: Index
public ActionResult Index()
{
var userM = new ApplicationUserManager();
userM.Create(new ApplicationUser(){UserName = "admin"},"12345678");
return View();
}
示例12: CreatePatient
public ActionResult CreatePatient(CreatePatientViewModel model)
{
ApplicationUser user = UserManager.FindById(User.Identity.GetUserId());
Physician physician = _physicianService.GetPhysician(user.PhysicianId);
// Conversions from the model
int race = (int)Enum.Parse(typeof(PatientRace), model.Race);//convert.GenderRaceStringToInt(model.Race);
int gender = (int)Enum.Parse(typeof(PatientGender), model.Gender);//convert.PatientGenderStringToInt(model.Gender);
int ethnicity = (int)Enum.Parse(typeof(PatientEthnicity), model.Ethnicity);// convert.PatientEthnicityStringToInt(model.Ethnicity);
// Check if the user is already in the database.
if (UserIsInDatabase(model.Username))
{
// User is already in the database
// Display an error and request the physician to enter in a different username.
ModelState.Clear();
ModelState.AddModelError("UsernameExistsError", "Username already exists.");
}
else
{
// User is not in the database.
// Proceed to add the user to the database.
Patient patient = new Patient();
patient.Birthdate = DateTime.Parse(model.Birthdate); //model.Birthdate; // Need to fix this, temporarily putting in 0.
patient.Height = (int)model.Height;
patient.Weight = (int)model.Weight;
patient.Location = (int)Enum.Parse(typeof(Location), model.Location);//model.Location; // Need to fix this. temporarily putting in 12.
patient.Ethnicity = ethnicity;
patient.Gender = gender;
patient.Race = race;
patient.Physician = physician;
var newUser = new ApplicationUser { UserName = model.Username, Status = (int)Account_Status.Active };
if ((newUser != null) && (model.Password != null))
{
//Create a new context to change the user creation validation rules for the patient only.
using (ApplicationDbContext context = new ApplicationDbContext()) {
var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context));
// This user validator is being created only to remove email as a required field for creating a user.
// The email field in the AspNetUsers table is nullable and our requirments state that a patient does not
// have an email address so in order to satisfy that requiremnt we need to remove the required email
// parameter on user creation validation.
manager.UserValidator = new UserValidator<ApplicationUser>(manager) {
AllowOnlyAlphanumericUserNames = false,
RequireUniqueEmail = false
};
var result = manager.Create(newUser, model.Password);
if (result.Succeeded) {
// User added to database successfully.
_patientService.CreatePatient(patient);
_patientService.SaveChanges();
newUser.PatientId = patient.Id;
result = manager.Update(newUser);
//Role must match what is found in the database AspNetRoles table.
result = manager.AddToRole(newUser.Id, "Patient");
physician.Patients.Add(patient);
_physicianService.UpdatePhysician(physician);
_physicianService.SaveChanges();
}
else {
// User failed to add.
ModelState.Clear();
foreach (string error in result.Errors) {
ModelState.AddModelError("ResultError", error);
}
return View(model);
}
}
}
else
{
// Username or password was null if we got here.
}
}
return View(model);
}