本文整理汇总了C#中ApplicationUserManager.CreateAsync方法的典型用法代码示例。如果您正苦于以下问题:C# ApplicationUserManager.CreateAsync方法的具体用法?C# ApplicationUserManager.CreateAsync怎么用?C# ApplicationUserManager.CreateAsync使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ApplicationUserManager
的用法示例。
在下文中一共展示了ApplicationUserManager.CreateAsync方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Application_Start
protected async void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
// ユーザーとロールの初期化
// ロールの作成
var roleManager = new ApplicationRoleManager(new UserStore());
await roleManager.CreateAsync(new ApplicationRole { Name = "admin" });
await roleManager.CreateAsync(new ApplicationRole { Name = "users" });
var userManager = new ApplicationUserManager(new UserStore());
// 一般ユーザーの作成
await userManager.CreateAsync(new ApplicationUser { UserName = "tanaka" }, "[email protected]");
await userManager.AddToRoleAsync(
(await userManager.FindByNameAsync("tanaka")).Id,
"users");
// 管理者の作成
await userManager.CreateAsync(new ApplicationUser { UserName = "super_tanaka" }, "[email protected]");
await userManager.AddToRoleAsync(
(await userManager.FindByNameAsync("super_tanaka")).Id,
"users");
await userManager.AddToRoleAsync(
(await userManager.FindByNameAsync("super_tanaka")).Id,
"admin");
Debug.WriteLine("-----------");
}
示例2: InitializeAppEnvironment
private void InitializeAppEnvironment()
{
//app environment configuration
using (var db = new ApplicationDbContext())
{
db.Database.CreateIfNotExists();
var roleStore = new RoleStore<IdentityRole>(db);
var role = roleStore.FindByNameAsync("Admin").Result;
if (role == null)
{
roleStore.CreateAsync(new IdentityRole("Admin")).Wait();
}
var userStore = new UserStore<ApplicationUser>(db);
var manager = new ApplicationUserManager(userStore);
var admin = manager.FindByName("admin");
if (admin == null)
{
admin = new ApplicationUser
{
UserName = "admin",
Email = "[email protected]",
EmailConfirmed = true,
CreateDate = DateTime.Now
};
var r = manager.CreateAsync(admin, "~Pwd123456").Result;
}
if (!manager.IsInRole(admin.Id, role.Name))
{
manager.AddToRole(admin.Id, role.Name);
}
}
}
示例3: SeedDatabase
private static void SeedDatabase()
{
var context = new OnlineShopContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser()
{
UserName = "Test",
Email = "[email protected]"
};
var result = userManager.CreateAsync(user, "Test123%").Result;
if (!result.Succeeded)
{
Assert.Fail(string.Join(Environment.NewLine, result.Errors));
}
context.Categories.Add(new Category() { Name = "Auto" });
context.Categories.Add(new Category() { Name = "Education" });
context.Categories.Add(new Category() { Name = "home and Family" });
context.AdTypes.Add(new AdType() { Name = "Economy", PricePerDay = 10 });
context.AdTypes.Add(new AdType() { Name = "Normal", PricePerDay = 20 });
context.AdTypes.Add(new AdType() { Name = "Lux", PricePerDay = 40 });
context.SaveChanges();
}
示例4: Seed
private static void Seed()
{
var context = new NewsContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser()
{
UserName = "TestUser",
Email = "[email protected]"
};
var result = userManager.CreateAsync(user, "Pass123$").Result;
if (!result.Succeeded)
{
Assert.Fail(string.Join(Environment.NewLine, result.Errors));
}
var news = new News.Models.News()
{
Title = "First news",
Content = "first news content",
PublishDate = DateTime.Now,
Author = user
};
var news2 = new News.Models.News()
{
Title = "Second news",
Content = "second news content",
PublishDate = DateTime.Now,
Author = user
};
context.News.Add(news2);
context.SaveChanges();
}
示例5: CreateAgency
public async Task<bool> CreateAgency(Users dbUser)
{
ApplicationUserManager manager = null;
if (!CurrentLoginUser.Permission.CREATE_USER)
{
throw new KMBitException("没有权限创建代理商");
}
int total = 0;
List<BUser> existedUsers = FindAgencies(0, dbUser.Email, null, 0, 0,out total);
if(existedUsers.Count>0)
{
throw new KMBitException(string.Format("Email:{0}已经注册过"));
}
bool ret = false;
try
{
manager = new ApplicationUserManager(new ApplicationUserStore(new chargebitEntities()));
ApplicationUser appUser = new ApplicationUser();
appUser.Address = dbUser.Address;
appUser.AccessFailedCount = 0;
appUser.City_id = dbUser.City_id;
appUser.CreatedBy = dbUser.CreatedBy;
appUser.Credit_amount = dbUser.Credit_amount;
appUser.Description = dbUser.Description;
appUser.Email = dbUser.Email;
appUser.UserName = dbUser.Email;
appUser.Name = dbUser.Name;
appUser.PasswordHash = dbUser.PasswordHash;
appUser.Pay_type = dbUser.Pay_type;
appUser.PhoneNumber = dbUser.PhoneNumber;
appUser.Province_id = dbUser.Province_id;
appUser.Regtime = dbUser.Regtime;
appUser.Enabled = dbUser.Enabled;
appUser.AccessToken =UrlSignUtil.GetMD5(Guid.NewGuid().ToString());
if (appUser.Regtime == 0)
{
appUser.Regtime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
}
appUser.Type = dbUser.Type;
appUser.Update_time = appUser.Regtime;
appUser.UserName = dbUser.Email;
var result = await manager.CreateAsync(appUser, dbUser.PasswordHash);
if (result.Succeeded)
{
ret = true;
}
}
catch { }
finally
{
if(manager!=null)
{
manager.Dispose();
}
}
return ret;
}
示例6: CreateAdministrator
public async Task<Users> CreateAdministrator(Users dbUser)
{
if(dbUser==null)
{
throw new KMBitException("参数不正确");
}
if (string.IsNullOrEmpty(dbUser.Email))
{
throw new KMBitException("邮箱地址不能为空");
}
if (string.IsNullOrEmpty(dbUser.PasswordHash))
{
throw new KMBitException("用户密码不能为空");
}
if (!CurrentLoginUser.Permission.CREATE_USER)
{
throw new KMBitException("没有权限创建用户");
}
using (chargebitEntities db = new chargebitEntities())
{
Users u = (from usr in db.Users where usr.Email==dbUser.Email select usr).FirstOrDefault<Users>();
if(u!=null)
{
throw new KMBitException("此邮箱已经注册过,不能重复注册");
}
ApplicationUserManager manager = new ApplicationUserManager(new ApplicationUserStore(new chargebitEntities()));
ApplicationUser appUser = new ApplicationUser();
appUser.Address = "";
appUser.AccessFailedCount = 0;
appUser.City_id = 0;
appUser.CreatedBy = CurrentLoginUser.User.Id;
appUser.Credit_amount = 0;
appUser.Description = "";
appUser.Email = dbUser.Email;
appUser.UserName = dbUser.Email;
appUser.Name = dbUser.Name;
appUser.PasswordHash = dbUser.PasswordHash;
appUser.Pay_type = 0;
appUser.PhoneNumber = dbUser.PhoneNumber;
appUser.Province_id = 0;
appUser.Regtime = DateTimeUtil.ConvertDateTimeToInt(DateTime.Now);
appUser.Enabled = dbUser.Enabled;
appUser.Type = 1;
appUser.Update_time = appUser.Regtime;
appUser.AccessToken = UrlSignUtil.GetMD5(Guid.NewGuid().ToString());
var result = await manager.CreateAsync(appUser, dbUser.PasswordHash);
if (result.Succeeded)
{
u = (from usr in db.Users where usr.Email == dbUser.Email select usr).FirstOrDefault<Users>();
Admin_Users au = new Admin_Users() { Description = "管理员", IsSuperAdmin = false, IsWebMaster = false, User_Id = u.Id };
db.Admin_Users.Add(au);
db.SaveChanges();
}
return u;
}
}
示例7: Seed
public async static void Seed(IRepositoryFactory repoFactory)
{
var users = repoFactory.GetRepository<User>("AspNetUsers");
var allUsers = await users.All();
if (!allUsers.Any())
{
var john = new User("[email protected]");
var userStore = new MongoUserStore<User>(repoFactory);
var userManager = new ApplicationUserManager(userStore);
var jimi = new User("[email protected]");
var johnResult = await userManager.CreateAsync(john, "JohnsPassword");
var jimiResult = await userManager.CreateAsync(jimi, "JimisPassword");
await userManager.AddClaimAsync(john.Id, new Claim(ClaimTypes.Name, "[email protected]"));
await userManager.AddClaimAsync(john.Id, new Claim(ClaimTypes.Role, "Admin"));
await userManager.AddClaimAsync(jimi.Id, new Claim(ClaimTypes.Name, "[email protected]"));
await userManager.AddClaimAsync(jimi.Id, new Claim(ClaimTypes.Role, "User"));
}
}
示例8: SeedUsers
private void SeedUsers(MessagesDbContext context)
{
var userStore = new UserStore<User>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new User()
{
UserName = TestUserUsername,
Email = string.Format("{0}@gmail.com", TestUserUsername)
};
var userResult = userManager.CreateAsync(user, TestUserPassword).Result;
if (!userResult.Succeeded)
{
Assert.Fail(string.Join("\n", userResult.Errors));
}
}
示例9: Post
public async Task<IHttpActionResult> Post([FromBody]RegisterUserModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var manager = new ApplicationUserManager(new MySqlUserStore<ApplicationUser>());
var user = new ApplicationUser() { UserName = model.UserName, Email = model.Email, PhoneNumber = model.PhoneNumber };
IdentityResult result = await manager.CreateAsync(user, model.Password);
if (!result.Succeeded)
return GetErrorResult(result);
result = await manager.AddToRoleAsync(model.UserName, model.Role);
if (!result.Succeeded)
return GetErrorResult(result);
return Ok();
}
示例10: SeedDatabase
private static void SeedDatabase()
{
var context = new OnlineShopContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser()
{
UserName = TestUserUsername,
Email = "[email protected]"
};
var result = userManager.CreateAsync(user, TestUserPassword).Result;
if (!result.Succeeded)
{
Assert.Fail(string.Join(Environment.NewLine, result.Errors));
}
SeedCategories(context);
SeedAdTypes(context);
}
示例11: CreateUserIfNotExists
public static async Task<UserTuple> CreateUserIfNotExists(string id, ApplicationUserManager um)
{
var response = new UserTuple();
//-- Create User if it Doesn't exist
response.User = await um.FindByNameAsync(id);
if (null == response.User)
{
response.IsNewUser = true;
response.User = new ApplicationUser { UserName = id, Email = string.Format("{0:N}@email.com", Guid.NewGuid()) };
var result = await um.CreateAsync(response.User);
if (!result.Succeeded)
throw new Exception("Ooops. Something went really wrong");
//-- Make sure that if we're using the Watched Videos, it's set and not null
response.User.WatchedVideos = new List<WatchedVideo>();
}
return response;
}
示例12: RegisterUserAsync
/// <summary>
/// Registers a new user and also ensures that address is added into the db properly asyncronously
/// </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 async Task<StatusResult<UserInfoViewModel>> RegisterUserAsync(RegisterBindingModel model, ApplicationUserManager userManager)
{
UserInfoViewModel obj = null;
try
{
var user = ApplicationUser.CreateUser(model);
IdentityResult userResult = await userManager.CreateAsync(user, model.Password);
if (!userResult.Succeeded)
{
return StatusResult<UserInfoViewModel>.Error();
}
// add the address
var addressResult = await UserAddressManager.InsertUserAddressAsync(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
await userManager.DeleteAsync(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);
}
示例13: ApplicationUserManager
public void Registrar_Obterer_CambiarContraseña_Borrar_Uasuario()
{
var servicioUsuario = new ApplicationUserManager(new UserStore<Usuario>(new ContextoBaseDatos()));
// Crear
var modeloRegistro = new RegisterViewModel {
Email = "[email protected]",
Password ="password!",
ConfirmPassword = "password!",
};
var usuario = new Usuario {
UserName = modeloRegistro.Email,
Email = modeloRegistro.Email
};
// Registrar
var resultadoAccion = servicioUsuario.CreateAsync(usuario, modeloRegistro.Password).Result;
Assert.IsTrue(resultadoAccion.Succeeded);
// Obtener
var usuarioCreado = servicioUsuario.FindByNameAsync(modeloRegistro.Email).Result;
Assert.AreEqual(modeloRegistro.Email, usuarioCreado.Email);
// Cambiar contraseña
resultadoAccion = servicioUsuario.ChangePasswordAsync(usuarioCreado.Id, modeloRegistro.Password, "nuevoPassword!").Result;
Assert.IsTrue(resultadoAccion.Succeeded);
// Borrar
resultadoAccion = servicioUsuario.DeleteAsync(usuarioCreado).Result;
Assert.IsTrue(resultadoAccion.Succeeded);
var usuarioEliminado = servicioUsuario.FindByNameAsync(modeloRegistro.Email).Result;
Assert.IsNull(usuarioEliminado);
}
示例14: SeedDatabase
private static void SeedDatabase()
{
var context = new TweeterLikeContext();
var userStore = new UserStore<ApplicationUser>(context);
var userManager = new ApplicationUserManager(userStore);
var user = new ApplicationUser()
{
UserName = Username,
Email = Username
};
var result = userManager.CreateAsync(user, Password).Result;
if (!result.Succeeded)
{
Assert.Fail(string.Join(Environment.NewLine, result.Errors));
}
SeedPosts(context);
}
示例15: Create
public async Task<ActionResult> Create(SupplierViewModel model, FormCollection collect)
{
#region Cathing model errors
var error = ModelState.Values.SelectMany(e => e.Errors);
var errors = ModelState
.Where(x => x.Value.Errors.Count > 0)
.Select(x => new { x.Key, x.Value.Errors })
.ToArray();
#endregion
#region Prep Utilities
SupplierContext dataSocket = new SupplierContext();
ApplicationDbContext context = new ApplicationDbContext();
var roleStore = new RoleStore<IdentityRole>(context);
UserStore<ApplicationUser> myStore = new UserStore<ApplicationUser>(context);
ApplicationUserManager userMgr = new ApplicationUserManager(myStore);
var roleManager = new RoleManager<IdentityRole>(roleStore);
#endregion
#region Bend the rules
try
{
if(collect.GetValue("SupplierType").AttemptedValue == "0")
{ /*Book Supplier*/ model.RegisterNewSupplier.SupplierType = true; }
else if (collect.GetValue("SupplierType").AttemptedValue == "1")
{ /*Technology Supplier*/ model.RegisterNewSupplier.SupplierType = false; }
if (ModelState.ContainsKey("SupplierType"))
ModelState["SupplierType"].Errors.Clear();
}
catch
{ ModelState.AddModelError("SupplierType", "Please select a valid supplier type from dropdown !"); }
#endregion
try
{
if (ModelState.IsValid)
{
#region Register Supplier
var user = new ApplicationUser() { UserName = model.RegisterNewSupplier.Email, Email = model.RegisterNewSupplier.Email, Address = model.RegisterNewSupplier.Address, PhoneNumber = model.RegisterNewSupplier.ContactPersonNumber };
Models.Supplier supplier = new Models.Supplier { Name = model.RegisterNewSupplier.Name, ContactPerson = model.RegisterNewSupplier.ContactPerson, Fax = model.RegisterNewSupplier.Fax, ContactPersonNumber = model.RegisterNewSupplier.ContactPersonNumber, LastName = model.RegisterNewSupplier.LastName, User_Id = user.Id, IsBookSupplier = model.RegisterNewSupplier.SupplierType };
user.Carts = new Cart { DateLastModified = DateTime.Now };
user.Wishlists = new Wishlist { Status = false };
IdentityResult result = await userMgr.CreateAsync(user, model.RegisterNewSupplier.Password);
roleManager.Create(new IdentityRole { Name = "supplier" });
userMgr.AddToRole(user.Id, "supplier");
//dataSocket.Suppliers.Add(supplier);
dataSocket.Suppliers.Add(supplier);
dataSocket.SaveChanges();
#endregion
return RedirectToAction("Index", "Admin", null);
}
#region Set Up dropdown
model.SupplierType = new List<SelectListItem>();
model.SupplierType.Add(
new SelectListItem { Text = "Please Select Supplier Type", Value = "", Selected = true }
);
model.SupplierType.Add(
new SelectListItem { Text = "Book Supplier", Value = "0" }
);
model.SupplierType.Add(
new SelectListItem { Text = "Technology Supplier", Value = "1" }
);
ViewData["SupplierType"] = model.SupplierType;
#endregion
return View(model);
}
catch
{
#region Set Up dropdown
model.SupplierType = new List<SelectListItem>();
model.SupplierType.Add(
new SelectListItem { Text = "Please Select Supplier Type", Value = "", Selected = true }
);
model.SupplierType.Add(
new SelectListItem { Text = "Book Supplier", Value = "0" }
);
model.SupplierType.Add(
new SelectListItem { Text = "Technology Supplier", Value = "1" }
);
ViewData["SupplierType"] = model.SupplierType;
#endregion
return View(model);
}
}