Static async function returns before its finished

osyris 236 Reputation points
2021-12-07T02:49:06.483+00:00

Any time i run the code it skips 60% of it
And i dont know why that is happening
I think it has to do with the "await" and the "GetAwaiter().GetResult()"

how the code should work:
1.check if Admin role exist, if not create it.
2.check if admin account exist, if not create it,
3.Add admin account to Admin Role.

4.check if Manager Role exist, if not Create it,
5.check if Manager account exist, if not create it,
6.Add Manager account to Manager Role.

the problem:
it skips step: 3,4,5,6

I have used " public static async Task" instead of " public static async void"
since "Async void" seem to be a bad combinated from what i have read.

I have also tried to use "GetAwaiter().GetResult()" instead of "Await"
sometimes that seems to work
but at this point im just guessing because i have no qlue .
A little help would be great.

 public static class SeedAdmin 
    {
        public static async Task Initialize(IServiceProvider serviceProvider)
        {
            //All using function here

    bool AdminRole = roleManager.RoleExistsAsync("AdminRole").Result;
            //Role Admin Creating
            // this part work
                if (!AdminRole)
                {
                    var Role = new ApplicationRole();
                    Role.Name = "Admin";
                    Role.Description = "Acces to all pages";

                roleManager.CreateAsync(Role).GetAwaiter().GetResult();
                }

                //User Admin Creating
                    var findAdmin = _dbcontext.Users.FirstOrDefaultAsync(x => x.Email == "Info@Admin.com").GetAwaiter().GetResult();
            if (findAdmin == null)
                    {
                        var Admin = new ApplicationUser();
                        Admin.Email =     "Info@Admin.com";
                        Admin.PasswordHash = BCrypt.Net.BCrypt.HashPassword("AdminPassword_293@", workFactor:16);
                        Admin.EmailConfirmed = true;
                  // this part work
                _dbcontext.Users.Add(Admin);

                await _dbcontext.SaveChangesAsync();
                // this part does not work
                usermanager.AddToRoleAsync(Admin, "Admin").GetAwaiter().GetResult();
            }

            //Role Manager Creating
                bool ManagerRole = roleManager.RoleExistsAsync("ManagerRole").Result;
                // this part does not work
                if (!ManagerRole)
                {
                    var Role = new ApplicationRole();
                    Role.Name = "Manager";
                    Role.Description = "Acces to all pages except for deleting and adding employeey";

                roleManager.CreateAsync(Role).GetAwaiter().GetResult();
                }

            // User Manager Creating
            var findManager = _dbcontext.Users.FirstOrDefaultAsync(x => x.Email == "Info@Managaer.com").GetAwaiter().GetResult();
             // this part does not work
            if (findManager == null)
            {

                var Manager = new ApplicationUser();
                Manager.Email = "Info@Manager.com";
                Manager.EmailConfirmed = true;
                Manager.PasswordHash = BCrypt.Net.BCrypt.HashPassword("AdminPassword_293@", workFactor: 16);

                _dbcontext.Users.Add(Manager);

                await _dbcontext.SaveChangesAsync();
                usermanager.AddToRoleAsync(Manager, "Manager").GetAwaiter().GetResult();
            }
            return;
        }
    }
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,023 questions
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,186 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 25,761 Reputation points
    2021-12-07T20:29:57.107+00:00

    There are two main issues with the design. The first is the design does not implement async/await properly. The second issue is not following the seeding pattern illustrated in one of your previous threads.

    The following code sample illustrates how to implement async/await, create services, and seed data when the application starts. The example uses Sqlite and default Identity.

    using Microsoft.AspNetCore.Identity;  
    using Microsoft.EntityFrameworkCore;  
    using MvcIdentity.Data;  
      
    var builder = WebApplication.CreateBuilder(args);  
      
    // Add services to the container.  
    var connectionString = builder.Configuration.GetConnectionString("DefaultConnection");  
    builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(connectionString));  
    builder.Services.AddDatabaseDeveloperPageExceptionFilter();  
      
    builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)  
        .AddRoles<IdentityRole>()  
        .AddEntityFrameworkStores<ApplicationDbContext>();  
      
      
    builder.Services.AddControllersWithViews();  
      
    var app = builder.Build();  
      
    using (var scope = app.Services.CreateScope())  
    {  
        var services = scope.ServiceProvider;  
        await SeedData.InitializeAsync(services);  
    }  
      
    // Configure the HTTP request pipeline.  
    if (app.Environment.IsDevelopment())  
    {  
        app.UseMigrationsEndPoint();  
    }  
    else  
    {  
        app.UseExceptionHandler("/Home/Error");  
        // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.  
        app.UseHsts();  
    }  
      
    app.UseHttpsRedirection();  
    app.UseStaticFiles();  
      
    app.UseRouting();  
      
    app.UseAuthentication();  
    app.UseAuthorization();  
      
    app.MapControllerRoute(  
        name: "default",  
        pattern: "{controller=Home}/{action=Index}/{id?}");  
    app.MapRazorPages();  
      
    app.Run();  
    

    The extension method

    public static class SeedData  
        {  
            public static async Task InitializeAsync(IServiceProvider serviceProvider)  
            {  
      
                using (var roleManager = serviceProvider.GetService<RoleManager<IdentityRole>>())  
                {  
                    if(roleManager != null)  
                    {  
                        if (!(await roleManager.RoleExistsAsync("Admin")))  
                        {  
                            await roleManager.CreateAsync(new IdentityRole("Admin"));  
                        }  
      
                        if (!(await roleManager.RoleExistsAsync("Manager")))  
                        {  
                            await roleManager.CreateAsync(new IdentityRole("Manager"));  
                        }  
                    }  
                }  
      
                using (var userManager = serviceProvider.GetService<UserManager<IdentityUser>>())  
                {  
                    if (userManager != null)  
                    {  
                        IdentityUser? user = await userManager.FindByEmailAsync("Info@Admin.com");  
                        if (user == null)  
                        {  
                            var newUser = new IdentityUser()  
                            {  
                                Email = "Info@Admin.com",  
                                UserName = "Info@Admin.com",  
                                EmailConfirmed = true  
                            };  
      
                            var result = await userManager.CreateAsync(newUser, "@Password123");  
      
                            if (result.Succeeded)  
                            {  
                                await userManager.AddToRoleAsync(newUser, "Admin");  
                            }  
                                  
                        }  
                        else  
                        {  
                            if (!(await userManager.IsInRoleAsync(user, "Admin")))  
                            {  
                                await userManager.AddToRoleAsync(user, "Admin");  
                            }  
                        }  
                    }  
                }  
            }  
        }  
    

    Resources
    Asynchronous programming with async and await

    0 comments No comments