// GET: Home
        public async Task<ActionResult> Index()
        {
            var context = new ApplicationDbContext(); // DefaultConnection
            var store = new UserStore<CustomUser>(context);
            var manager = new UserManager<CustomUser>(store);

            var email = "*****@*****.**";
            var password = "******";
            var user = await manager.FindByEmailAsync(email);

            if (user == null)
            {
                user = new CustomUser
                {
                    UserName = email,
                    Email = email,
                    FirstName = "Super",
                    LastName = "Admin"
                };

                await manager.CreateAsync(user, password);
            }
            else
            {
                user.FirstName = "Super";
                user.LastName = "Admin";

                await manager.UpdateAsync(user);
            }


            return Content("Hello, Index");
        }
Ejemplo n.º 2
2
        public string AddBlock(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var blockedUser = manager.FindById(userId);

                if (type.Equals("Block"))
                {
                    currentUser.blockedList.Add(blockedUser);

                    //unfollow each person if there was any following
                    UnFollow(currentUser, blockedUser);
                    UnFollow(blockedUser, currentUser);
                }
                else  //unblock user just remove him from the list
                {
                    var block = currentUser.blockedList.Find(user => user.Id == blockedUser.Id);

                    if (block != null)
                    {
                        currentUser.blockedList.Remove(block);
                    }
                }

              //  manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

               // store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
Ejemplo n.º 3
1
        public string AddFollow(string userId, string type)
        {
            using (ApplicationDbContext db = new ApplicationDbContext())
            {
                var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));
                var currentUser = manager.FindById(User.Identity.GetUserId());
                var followedUser = manager.FindById(userId);

                if (type.Equals("Follow"))
                {
                    currentUser.followList.Add(followedUser);
                }
                else
                {
                    UnFollow(currentUser, followedUser);
                }

                //manager.UpdateAsync(currentUser);

                var store = new UserStore<ApplicationUser>(new ApplicationDbContext());

                //store.Context.SaveChanges();
                db.SaveChanges();
                return "success";
            }
        }
        public IIdentityManagerService Create()
        {
            var db = new IdentityDbContext<IdentityUser>(_connString);
            var userstore = new UserStore<IdentityUser>(db);
            var usermgr = new Microsoft.AspNet.Identity.UserManager<IdentityUser>(userstore);
            usermgr.PasswordValidator = new Microsoft.AspNet.Identity.PasswordValidator
            {
                RequiredLength = 3
            };
            var rolestore = new RoleStore<IdentityRole>(db);
            var rolemgr = new Microsoft.AspNet.Identity.RoleManager<IdentityRole>(rolestore);

            var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<IdentityUser, string, IdentityRole, string>(usermgr, rolemgr);

            var dispose = new DisposableIdentityManagerService(svc, db);
            return dispose;

            //var db = new CustomDbContext(_connString);
            //var userstore = new CustomUserStore(db);
            //var usermgr = new CustomUserManager(userstore);
            //var rolestore = new CustomRoleStore(db);
            //var rolemgr = new CustomRoleManager(rolestore);

            //var svc = new Thinktecture.IdentityManager.AspNetIdentity.AspNetIdentityManagerService<CustomUser, int, CustomRole, int>(usermgr, rolemgr);
            //var dispose = new DisposableIdentityManagerService(svc, db);
            //return dispose;
        }
Ejemplo n.º 5
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            IdentityUser user = manager.Find(LoginUser.UserName, LoginUser.Password);

            if (user != null)
            {
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                if (Request.QueryString["ReturnUrl"] == null)
                    Response.Redirect("../Default.aspx");
                else
                    Response.Redirect(Request.QueryString["ReturnUrl"]);

            }
            else
            {
                LoginUser.FailureText = "Invalid User Name or Password";

            }
        }
        public ActionResult Menu()
        {
            ApplicationDbContext userscontext = new ApplicationDbContext();
            var userStore = new UserStore<ApplicationUser>(userscontext);
            var userManager = new UserManager<ApplicationUser>(userStore);

            var roleStore = new RoleStore<IdentityRole>(userscontext);
            var roleManager = new RoleManager<IdentityRole>(roleStore);

            if (User.Identity.IsAuthenticated)
            {

                if (userManager.IsInRole(this.User.Identity.GetUserId(), "Admin"))
                {
                    return PartialView("_AdminMenuView");
                }
                else if (userManager.IsInRole(this.User.Identity.GetUserId(), "Principal"))
                {
                    return PartialView("_PrincipalenuView");
                }
                else
                {
                    return PartialView("_Student");
                }
            }

            return PartialView("_Empty");
        }
Ejemplo n.º 7
0
        protected void CreateUser_Click(object sender, EventArgs e)
        {
            // Default UserStore constructor uses the default connection string named: DefaultConnectionEF
            var userStore = new UserStore<IdentityUser>();
            var manager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser() { UserName = txtUName.Text };
            user.Email = txtEmail.Text;
            user.PhoneNumber = txtPhone.Text;
            IdentityResult result = manager.Create(user, txtPass.Text);

            if (result.Succeeded)
            {
                lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                Response.Redirect("/admin/main.aspx");

            }
            else
            {
                lblStatus.Text = result.Errors.FirstOrDefault();
            }
        }
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // search for and create a new user object
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // if a match is found for the user
            if(user != null)
            {
                // authenticate and login our new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                // Sign the user
                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // Redirect to Main Menu
                Response.Redirect("~/Contoso/MainMenu.aspx");
            }
            else
            {
                // throw an error to the AlertFlash div
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
        protected void getWorkoutLog()
        {
            //Get userID for viewing based off ID
             var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
            var userIdentity = authenticationManager.User.Identity.GetUserId();
             //Try block incase an error is thrown
            try
            {
                //Connect with EF
                using (HealthLogEntities db = new HealthLogEntities())
                {
                    //Select the coloumns we need for the grid, and default sort
                    String SortString = Session["SortColumn"].ToString() + " " + Session["SortDirection"].ToString();
                    var Logs = from c in db.workoutLogs
                               where c.userID == userIdentity
                               select new { c.workoutLogID, c.userID, c.muscleGroup, c.excercise, c.wSets, c.wDate };
                    if (Logs != null)
                    {
                        //Bind the data to the gridview
                        showWorkout.DataSource = Logs.AsQueryable().OrderBy(SortString).ToList();
                        showWorkout.DataBind();
                    }

                }
            }
                //Catch any errors and redirect to the error page
             catch(Exception r)
            {
                Response.Redirect("/error.aspx");
            }
        }
Ejemplo n.º 10
0
 public StatisticsController()
 {
     db = new ApplicationDbContext();
     userStore = new UserStore<ApplicationUser>(db);
     userManager = new ApplicationUserManager(userStore);
     statisticsService = new StatisticsService(db);
 }
Ejemplo n.º 11
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };
                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("/user/index.aspx");

                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                }
            }
            catch (Exception d)
            {
                Response.Redirect("/error.aspx");
            }
        }
Ejemplo n.º 12
0
        protected void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                // Default UserStore constructor uses the default connection string named: DefaultConnection
                var userStore = new UserStore<IdentityUser>();
                var manager = new UserManager<IdentityUser>(userStore);

                var user = new IdentityUser() { UserName = txtUsername.Text };

                IdentityResult result = manager.Create(user, txtPassword.Text);

                if (result.Succeeded)
                {
                    //lblStatus.Text = string.Format("User {0} was created successfully!", user.UserName);
                    //lblStatus.CssClass = "label label-success";
                    var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                    var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);
                    authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);
                    Response.Redirect("admin/main-menu.aspx");
                }
                else
                {
                    lblStatus.Text = result.Errors.FirstOrDefault();
                    lblStatus.CssClass = "label label-danger";
                }
            }
            catch (Exception q)
            {
                Response.Redirect("/error.aspx");
            }
        }
        public HttpResponseMessage Post([FromBody]LoginPasswordUser lp)
        {
            UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();

            userStore.Context.Database.Connection.ConnectionString =
                System.Configuration.ConfigurationManager.
                ConnectionStrings["GarageConnectionString"].ConnectionString;

            UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);

            var user = manager.Find(lp.login, lp.password);

            if (user != null)
            {
                //Call OWIN functionality
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = manager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                //Sign in user
                authenticationManager.SignIn(new AuthenticationProperties
                {
                    IsPersistent = false
                }, userIdentity);

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK, "Bruger er logget ind");
                return response;

            }
            else
            {
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Bruger findes ikke i systemet");
                return response;
            }
        }
Ejemplo n.º 14
0
 public async Task AddRemoveUserClaimTest()
 {
     var db = UnitTestHelper.CreateDefaultDb();
     var store = new UserStore<IdentityUser>(db);
     ;
     var user = new IdentityUser("ClaimsAddRemove");
     await store.CreateAsync(user);
     Claim[] claims = {new Claim("c", "v"), new Claim("c2", "v2"), new Claim("c2", "v3")};
     foreach (Claim c in claims)
     {
         await store.AddClaimAsync(user, c);
     }
     await store.UpdateAsync(user);
     var userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(3, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[0]);
     Assert.Equal(3, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(2, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[1]);
     Assert.Equal(2, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(1, userClaims.Count);
     await store.RemoveClaimAsync(user, claims[2]);
     Assert.Equal(1, userClaims.Count); // No effect until save changes
     db.SaveChanges();
     userClaims = await store.GetClaimsAsync(user);
     Assert.Equal(0, userClaims.Count);
     //Assert.Equal(0, user.Claims.Count);
 }
Ejemplo n.º 15
0
        protected void SignIn(object sender, EventArgs e)
        {
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);
            IdentityUser user = userManager.Find(tbUsername.Text, tbPassword.Text);

            //if user info is found
            if (user != null)
            {
                //create cookie
                IAuthenticationManager authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                ClaimsIdentity userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties {IsPersistent = false}, userIdentity);

                var returnUrl = Request.QueryString["returnUrl"];
                //if user came from different page, redirect to that one. Otherwise redirect to main page.
                Response.Redirect(returnUrl ?? "~/default.aspx");
            }
            //if not, show error message.
            else
            {
                lblConfirmationText.Text = "Invalid username or password.";
            }
        }
Ejemplo n.º 16
0
        protected void RadGridUserList_InsertCommand(object sender, Telerik.Web.UI.GridCommandEventArgs e)
        {
            var editableitem = ((GridEditableItem)e.Item);
            UserControl userControl = (UserControl)e.Item.FindControl(GridEditFormItem.EditFormUserControlID);

            ///
            var useStore = new UserStore<AppUser>(new ApplicationDbContext());
            var manager = new UserManager<AppUser>(useStore);

            string LogInUserName=(editableitem.FindControl("RtxtLoginID") as RadTextBox).Text.Trim();

            var user = new AppUser { UserName = LogInUserName, FName = (editableitem.FindControl("RtxtFirstName") as RadTextBox).Text, LName = (editableitem.FindControl("RtxtLastName") as RadTextBox).Text };
            IdentityResult result = manager.Create(user, (editableitem.FindControl("RtxtPassword") as RadTextBox).Text);

            if (result.Succeeded)
            {
                //Get The Current Created UserInfo
                AppUser CreatedUser = manager.FindByName(LogInUserName);

                var RoleAddResult = manager.AddToRole(CreatedUser.Id.Trim(), (editableitem.FindControl("RDDListRole") as RadDropDownList).SelectedItem.Text.Trim());

                lblMessage.Text = string.Format("User {0} is creted successfully", user.UserName);
            }

            else
            {

                lblMessage.Text = result.Errors.FirstOrDefault();
                e.Canceled = true;
            }
        }
        protected void RegisterButton_Click(object sender, EventArgs e)
        {
            //crete new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            var user = new IdentityUser()
            {
                UserName = UserNameTextBox.Text,
                PhoneNumber = PhoneNumberTextBox.Text,
                Email = EmailTextBox.Text
            };
            //create new user in the dbb and store the resukt
            IdentityResult result = userManager.Create(user, PasswordTextBox.Text);
            //check if succesfully registered
            if (result.Succeeded)
            {
                //authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);//store info in session

                //sign in
                authenticationManager.SignIn(new AuthenticationProperties() { }, userIdentity);

                //redirect to main menu
                Response.Redirect("~/Secured/TodoList.aspx");

            }
            else
            {
                //display error in the AlertFlash div
                StatusLabel.Text = result.Errors.FirstOrDefault();
                AlertFlash.Visible = true;
            }
        }
        public AuthorizationRepository()
        {
            _dataContext = new DataContext();
            var userStore = new UserStore<PropertyManagerUser>(_dataContext);
            _userManager = new UserManager<PropertyManagerUser>(userStore);

        }
Ejemplo n.º 19
0
        //Get Index page
        public ActionResult Index()
        {
            var userRoles = new List<RolesViewModel>();
            var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);

            //Get all the usernames
            foreach (var user in userStore.Users)
            {
                var r = new RolesViewModel
                {
                    UserName = user.UserName
                };
                userRoles.Add(r);
            }
            //Get all the Roles for our users
            foreach (var user in userRoles)
            {
                user.RoleNames = userManager.GetRoles(userStore.Users.First(s => s.UserName == user.UserName).Id);

                if (user.RoleNames.Contains("Default"))
                {
                    TempData["ValidationMessageIcon"] = "1";
                }
            }

            return View(db.Indices.ToList());
        }
Ejemplo n.º 20
0
        public async void HasPasswordAsync_GivenAUserWithAPasswordHash_ReturnsTrue()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            var hasPasswordHash = await userStore.HasPasswordAsync(user);

            hasPasswordHash.Should().BeTrue();
        }
 public void SetUp()
 {
     store = new UserStore(new LuceneDataProvider(new RAMDirectory(), Version.LUCENE_30));
     mappings = new NameValueCollection();
     middleware = new RoleMappingAuthenticationMiddleware(next) {Store = store, Settings = new NuGetWebApiSettings(NuGetWebApiSettings.DefaultAppSettingPrefix, new NameValueCollection(), mappings)};
     domainAdminUser = new ApiUserPrincipal(new GenericIdentity("T-Rex"), new [] {"Domain Administrators"});
 }
Ejemplo n.º 22
0
        public void SeedUser(UserSeedModel model, HomeGrownBulgariaDbContext context)
        {
            if (!context.Users.Any(u => u.UserName == model.Username))
            {
                var userStore = new UserStore<User>(context);
                var userManager = new UserManager<User>(userStore);

                var user = new User
                {
                    UserName = model.Username,
                    Email = model.Username,
                    FirstName = model.FirstName,
                    LastName = model.LastName,
                    AverageRatingReceived = ValidationConstants.AverageRatingInitialValue,
                    City = model.City
                };

                IdentityResult result = userManager.Create(user, model.Password);
                if (!result.Succeeded)
                {
                    throw new OperationCanceledException(result.Errors.First());
                }

                if (model.Role != null)
                {
                    userManager.AddToRole(user.Id, model.Role);
                }

                context.SaveChanges();
            }
        }
Ejemplo n.º 23
0
        public async void SetPasswordHashAsync_GivenAUserAndPasswordHash_SetsTheHashForTheUser()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            await userStore.SetPasswordHashAsync(user, "1234");

            var passwordHash = await userStore.GetPasswordHashAsync(user);

            passwordHash.Should().Be("1234");
        }
Ejemplo n.º 24
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            // create new userStore and userManager objects
            var userStore = new UserStore<IdentityUser>();
            var userManager = new UserManager<IdentityUser>(userStore);

            // Find the user
            var user = userManager.Find(UserNameTextBox.Text, PasswordTextBox.Text);

            // check if username and password combo exists
            if (user != null)
            {
                // authenticate and login new user
                var authenticationManager = HttpContext.Current.GetOwinContext().Authentication;
                var userIdentity = userManager.CreateIdentity(user, DefaultAuthenticationTypes.ApplicationCookie);

                authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, userIdentity);

                // redirect to the Main Menu page
                Response.Redirect("~/game.aspx");
            }
            else
            {
                StatusLabel.Text = "Invalid Username or Password";
                AlertFlash.Visible = true;
            }
        }
Ejemplo n.º 25
0
 //private RoleManager<IdentityRole, Guid> _roleManager;
 public LoginViewModel()
 {
     _client = new CongregatioServiceClient();
     _userStore = new UserStore();
     _userManager = new UserManager<IdentityUser, Guid>(new UserStore());
        // _roleManager = new RoleManager<IdentityRole, Guid>(new RoleStore());
 }
Ejemplo n.º 26
0
        public async void CreateAsync_GivenNewUser_CreatesNewUserAndAssignsUserId()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            var insertedUser = await userStore.FindByIdAsync(user.Id);

            insertedUser.Should().NotBeNull();
            insertedUser.Email.Should().Be("*****@*****.**");
        }
Ejemplo n.º 27
0
        public async void UpdateAsync_GivenAnUpdate_UpdatesTheUser()
        {
            var applicationDatabaseConfiguration = new ApplicationDatabaseConfiguration();
            var userStore = new UserStore<User>(applicationDatabaseConfiguration);

            var user = new User
            {
                Email = "*****@*****.**",
                IsEmailConfirmed = true,
                PasswordHash = "PasswordHash",
                PhoneNumber = "PhoneNumber",
                IsPhoneNumberConfirmed = true,
                IsTwoFactorEnabled = false,
                LockoutEndDateUtc = null,
                IsLockoutEnabled = true,
                AccessFailedCount = 0,
                UserName = "******",
                IsAccountActive = true
            };

            await userStore.CreateAsync(user);

            var existingUser = await userStore.FindByNameAsync("UserName");
            existingUser.Email = "*****@*****.**";
            existingUser.PhoneNumber = "1234";

            await userStore.UpdateAsync(existingUser);

            var updatedUser = await userStore.FindByNameAsync("UserName");

            updatedUser.Should().NotBeNull();
            updatedUser.Email.Should().Be("*****@*****.**");
            updatedUser.PhoneNumber.Should().Be("1234");
        }
 public void SetUp()
 {
     DatabaseHelper.Reset();
     TestData.AddUsers();
     TestData.AdLoginsForUsers();
     _target = new UserStore<IdentityUser>();
 }
            public ActionResult Index(Login login)
            {
                // UserStore and UserManager manages data retreival. 
                UserStore<IdentityUser> userStore = new UserStore<IdentityUser>();
                UserManager<IdentityUser> manager = new UserManager<IdentityUser>(userStore);
                IdentityUser identityUser = manager.Find(login.UserName,
                                                                 login.Password);

                if (ModelState.IsValid)
                {
                    if (ValidLogin(login))
                    {
                        IAuthenticationManager authenticationManager
                                               = HttpContext.GetOwinContext().Authentication;
                        authenticationManager
                       .SignOut(DefaultAuthenticationTypes.ExternalCookie);

                        var identity = new ClaimsIdentity(new[] {
                                            new Claim(ClaimTypes.Name, login.UserName),
                                        },
                                            DefaultAuthenticationTypes.ApplicationCookie,
                                            ClaimTypes.Name, ClaimTypes.Role);
                        // SignIn() accepts ClaimsIdentity and issues logged in cookie.  
                        authenticationManager.SignIn(new AuthenticationProperties
                        {
                            IsPersistent = false
                        }, identity);
                        return RedirectToAction("SecureArea", "Home");
                    }
                }
                return View();
            }
Ejemplo n.º 30
0
        protected override void Seed(WebApplication1.Models.MyDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
            context.Markets.AddOrUpdate(
                m => m.Id,
                new Market()
            {
                Id = 1, Name = "Binance", Description = "Day la san Binance"
            },
                new Market()
            {
                Id = 2, Name = "Huobi", Description = "Day la san Huobi"
            },
                new Market()
            {
                Id = 3, Name = "Bitmex", Description = "Day la san Bitmex"
            }
                );
            context.Coins.AddOrUpdate(
                c => c.Id,
                new Coin()
            {
                Id = "BNB_BTC_1", Name = "BNB", BaseAsset = "BNB", QuoteAsset = "BTC", LastPrice = 55.84, Volumn24h = 12245.49, MarketId = 1
            },
                new Coin()
            {
                Id = "ETH_BTC_1", Name = "Ethereum", BaseAsset = "ETH", QuoteAsset = "BTC", LastPrice = 14.47, Volumn24h = 14244.47, MarketId = 1
            },
                new Coin()
            {
                Id = "XRP_BTC_2", Name = "Ripple", BaseAsset = "XRP", QuoteAsset = "BTC", LastPrice = 141.11, Volumn24h = 141121.11, MarketId = 2
            },
                new Coin()
            {
                Id = "BCH_BTC_2", Name = "Bitcoin Cash", BaseAsset = "BCH", QuoteAsset = "BTC", LastPrice = 235.85, Volumn24h = 234235.85, MarketId = 2
            },
                new Coin()
            {
                Id = "DASH_BTC_3", Name = "Dash", BaseAsset = "DASH", QuoteAsset = "BTC", LastPrice = 2.79, Volumn24h = 11235.23, MarketId = 3
            },
                new Coin()
            {
                Id = "DLT_BTC_3", Name = "Agrello", BaseAsset = "DLT", QuoteAsset = "BTC", LastPrice = 5.04, Volumn24h = 231342.35, MarketId = 3
            }
                );
            var roleStore   = new RoleStore <AppRole>(context);
            var roleManager = new RoleManager <AppRole>(roleStore);

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                var role = new AppRole("Admin");
                roleManager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "User"))
            {
                var role = new AppRole("User");
                roleManager.Create(role);
            }
            var store   = new UserStore <AppUser>(context);
            var manager = new UserManager <AppUser>(store);

            if (!context.Users.Any(u => u.UserName == "adminne"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "Admin");
            }
            if (!context.Users.Any(u => u.UserName == "userne"))
            {
                var user = new AppUser()
                {
                    UserName = "******"
                };
                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "User");
            }
        }
Ejemplo n.º 31
0
        public async Task <ActionResult> Register(ExtendedIdentityModel model)

        {
            using (var context = new ApplicationDbContext())
            {
                if (ModelState.IsValid)
                {
                    if (model.UserProfilePicture != null)
                    {
                        if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }
                    }
                    byte[] data = new byte[model.UserProfilePicture.ContentLength];
                    model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);

                    var user = new ApplicationUser()
                    {
                        UserName  = model.Email,
                        Email     = model.Email,
                        BirthDate = model.BirthDate,
                        Firstname = model.Firstname,
                        Surname   = model.Surname,
                        Photo     = data
                    };

                    var result = await UserManager.CreateAsync(user, model.Password);


                    var roleStore   = new RoleStore <IdentityRole>(context);
                    var roleManager = new RoleManager <IdentityRole>(roleStore);

                    var userStore   = new UserStore <ApplicationUser>(context);
                    var userManager = new UserManager <ApplicationUser>(userStore);
                    userManager.AddToRole(user.Id, "Employee");

                    if (result.Succeeded)
                    {
                        // Send an email with this link
                        //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                        //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                        //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                        string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                        ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                          + "before you can log in.";

                        return(View("Info"));
                    }
                    AddErrors(result);
                }

                // If we got this far, something failed, redisplay form
                return(View(model));
            }
        }
Ejemplo n.º 32
0
        protected override void Seed(WebAppCarRoles.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            context.Cars.AddOrUpdate(
                p => p.Name,
                new Car {
                Name = "R8", Brand = "Audi"
            },
                new Car {
                Name = "900", Brand = "Saab"
            },
                new Car {
                Name = "740", Brand = "Volvo"
            }
                );


            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);


            roleManager.Create(new IdentityRole("CreateCar"));
            roleManager.Create(new IdentityRole("ReadCar"));
            roleManager.Create(new IdentityRole("UpdateCar"));
            roleManager.Create(new IdentityRole("DeleteCar"));


            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);


            userManager.Create(new ApplicationUser()
            {
                Email = "*****@*****.**", UserName = "******"
            }, "Password!1");
            userManager.Create(new ApplicationUser()
            {
                Email = "*****@*****.**", UserName = "******"
            }, "Password!1");
            userManager.Create(new ApplicationUser()
            {
                Email = "*****@*****.**", UserName = "******"
            }, "Password!1");
            userManager.Create(new ApplicationUser()
            {
                Email = "*****@*****.**", UserName = "******"
            }, "Password!1");


            ApplicationUser createUser = userManager.FindByEmail("*****@*****.**");
            ApplicationUser readUser   = userManager.FindByEmail("*****@*****.**");
            ApplicationUser updateUser = userManager.FindByEmail("*****@*****.**");
            ApplicationUser deleteUser = userManager.FindByEmail("*****@*****.**");


            userManager.AddToRole(createUser.Id, "Create");
            userManager.AddToRole(readUser.Id, "Read");
            userManager.AddToRole(updateUser.Id, "Update");
            userManager.AddToRole(deleteUser.Id, "Delete");
        }
Ejemplo n.º 33
0
        public static UserManager <AppUser> GetUserManager(ApplicationDbContext _context)
        {
            var userStored = new UserStore <AppUser>(_context);

            return(new UserManager <AppUser>(userStored));
        }
Ejemplo n.º 34
0
        protected override void Seed(BlogTest.Models.ApplicationDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data.

            var roleManger = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!context.Roles.Any(r => r.Name == "Admin"))
            {
                roleManger.Create(new IdentityRole {
                    Name = "Admin"
                });
            }

            if (!context.Roles.Any(r => r.Name == "Moderator"))
            {
                roleManger.Create(new IdentityRole {
                    Name = "Moderator"
                });
            }

            #region Add User creation and role assignment
            var userStore  = new UserStore <ApplicationUser>(context);
            var userManger = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Benjamin",
                    LastName    = "Yarema",
                    DisplayName = "BenLee"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Admin");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Jason",
                    LastName    = "Twichell",
                    DisplayName = "Prof"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Moderator");
            }

            if (!context.Users.Any(u => u.Email == "*****@*****.**"))
            {
                var user = new ApplicationUser
                {
                    UserName    = "******",
                    Email       = "*****@*****.**",
                    FirstName   = "Andrew",
                    LastName    = "Russell",
                    DisplayName = "Prof's SideKick"
                };
                //Creates the user in the DB
                userManger.Create(user, "Abc&123!");

                //here we attach the admin role to this user
                userManger.AddToRoles(user.Id, "Moderator");
            }

            #endregion

            #region



            #endregion
        }
        // TODO: Move this code when seed data is implemented in EF 7

        /// <summary>
        /// This is a workaround for missing seed data functionality in EF 7.0-rc1
        /// More info: https://github.com/aspnet/EntityFramework/issues/629
        /// </summary>
        /// <param name="app">
        /// An instance that provides the mechanisms to get instance of the database context.
        /// </param>
        public static async Task SeedData(this IApplicationBuilder app)
        {
            var context = app.ApplicationServices.GetService <ApplicationDbContext>();

            // Migrate and seed the database during startup. Must be synchronous.
            //context.Database.EnsureCreated();
            context.Database.Migrate();
            // TODO: Add seed logic here
            var owner = context.Users.FirstOrDefault(p => p.UserName == "Owner");
            var roles = EnumExtensions.GetListOfDescription <RoleNameEnum>();
            //if (owner != null&&!owner.Roles.Any())
            //{
            //  await AssignRoles(app, owner.Email, roles);
            //}
            var roleStore        = new RoleStore <AppRole>(context);
            var deletetRoleNames = context.Roles.Where(p => !roles.Contains(p.Name));

            foreach (var item in deletetRoleNames)
            {
                Console.WriteLine(item);
                // roleStore.DeleteAsync(item).Wait();
            }
            foreach (string role in roles)
            {
                if (!context.Roles.Any(r => r.Name == role))
                {
                    await roleStore.CreateAsync(new AppRole()
                    {
                        NormalizedName = role.ToUpper(), Name = role
                    });
                }
            }
            if (!context.Users.Any())
            {
                var user = new AppUser
                {
                    FirstName            = "Bobur",
                    LastName             = "Sunnatov",
                    Email                = "*****@*****.**",
                    NormalizedEmail      = "*****@*****.**",
                    UserName             = "******",
                    NormalizedUserName   = "******",
                    PhoneNumber          = "+998946410388",
                    EmailConfirmed       = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp        = Guid.NewGuid().ToString("D")
                };

                var password = new PasswordHasher <AppUser>();
                var hashed   = password.HashPassword(user, "secret");
                user.PasswordHash = hashed;

                var userStore = new UserStore <AppUser>(context);
                var result    = userStore.CreateAsync(user);


                await AssignRoles(app, user.Email, roles.ToArray());

                await context.SaveChangesAsync();
            }
            if (!context.ProductCategories.Any())
            {
            }
        }
Ejemplo n.º 36
0
        protected override void Seed(WebApplication5.Models.ApplicationDbContext context)
        {
            // ADD 3 TEST USERS WITH DIFFERENT ROLES
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole {
                    Name = "TCAdmin"
                });
                context.SaveChanges();

                userManager.AddToRole(user.Id, "TCAdmin");
            }

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole {
                    Name = "TCManager"
                });
                context.SaveChanges();

                userManager.AddToRole(user.Id, "TCManager");
            }

            if (!context.Users.Any(t => t.UserName == "*****@*****.**"))
            {
                var user = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**"
                };
                userManager.Create(user, "Passw0rd!");

                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole {
                    Name = "TCAgent"
                });
                context.SaveChanges();

                userManager.AddToRole(user.Id, "TCAgent");
            }
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
        protected override void Seed(SAS_LMS.Models.ApplicationDbContext context)
        {
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);
            var roleName    = "Teacher";

            if (!context.Roles.Any(r => r.Name == roleName))
            {
                var role = new IdentityRole {
                    Name = roleName
                };
                var result = roleManager.Create(role);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }

            roleName = "Student";
            if (!context.Roles.Any(r => r.Name == roleName))
            {
                var role = new IdentityRole {
                    Name = roleName
                };
                var result = roleManager.Create(role);
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }

            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            var email = "*****@*****.**";

            if (!context.Users.Any(u => u.UserName == email))
            {
                var user = new ApplicationUser
                {
                    UserName       = email,
                    Email          = email,
                    EnrollmentDate = DateTime.Now
                };
                var result = userManager.Create(user, "Admin123!");
                if (!result.Succeeded)
                {
                    throw new Exception(string.Join("\n", result.Errors));
                }
            }

            var adminUser = userManager.FindByName("*****@*****.**");

            userManager.AddToRole(adminUser.Id, "Teacher");

            context.ActivityTypes.AddOrUpdate(
                p => p.Name,
                new ActivityType {
                Name = "e-Learning"
            },
                new ActivityType {
                Name = "Lecture"
            },
                new ActivityType {
                Name = "Exercise"
            },
                new ActivityType {
                Name = "Submission"
            }
                );
        }
Ejemplo n.º 38
0
        public async Task UserStorePublicNullCheckTest()
        {
            Assert.Throws <ArgumentNullException>("context", () => new UserStore(null));
            var store = new UserStore(new IdentityDbContext(new DbContextOptionsBuilder <IdentityDbContext>().Options));
            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserIdAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetUserNameAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetUserNameAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.CreateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.UpdateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.DeleteAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ReplaceClaimAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveClaimsAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetClaimsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLoginsAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetRolesAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddLoginAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.RemoveLoginAsync(null, null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.AddToRoleAsync(null, null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.RemoveFromRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.IsInRoleAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPasswordHashAsync(null));

            await
            Assert.ThrowsAsync <ArgumentNullException>("user",
                                                       async() => await store.SetPasswordHashAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetSecurityStampAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetSecurityStampAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("login", async() => await store.AddLoginAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.AddClaimsAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("claims",
                                                             async() => await store.RemoveClaimsAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetEmailConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetEmailAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetEmailAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetPhoneNumberAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetPhoneNumberAsync(null, null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.GetPhoneNumberConfirmedAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetPhoneNumberConfirmedAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetTwoFactorEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user",
                                                             async() => await store.SetTwoFactorEnabledAsync(null, true));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEnabledAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetLockoutEnabledAsync(null, false));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.GetLockoutEndDateAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.SetLockoutEndDateAsync(null, new DateTimeOffset()));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.ResetAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentNullException>("user", async() => await store.IncrementAccessFailedCountAsync(null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.AddToRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.RemoveFromRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.IsInRoleAsync(new IdentityUser("fake"), null));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.AddToRoleAsync(new IdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.RemoveFromRoleAsync(new IdentityUser("fake"), ""));

            await Assert.ThrowsAsync <ArgumentException>("normalizedRoleName", async() => await store.IsInRoleAsync(new IdentityUser("fake"), ""));
        }
Ejemplo n.º 39
0
 public UsersApiController(WebStoreDB db, ILogger <UsersApiController> Logger)
 {
     _Logger    = Logger;
     _UserStore = new UserStore <User, Role, WebStoreDB>(db);
 }
        protected override void Seed(DataAccessContext context)
        {
            #region AddingRoles

            using (var store = new RoleStore <IdentityRole>(context))
            {
                using (var manager = new RoleManager <IdentityRole>(store))
                {
                    manager.Create(new IdentityRole("admin"));
                    manager.Create(new IdentityRole("teacher"));
                    manager.Create(new IdentityRole("parent"));
                    manager.Create(new IdentityRole("student"));
                }
            }

            #endregion

            context.SaveChanges();

            #region AddingSchoolSubjects

            SchoolSubject geography5 = new SchoolSubject()
            {
                Id            = 1,
                Name          = "Geografija 5",
                WeeklyClasses = 3
            };
            context.SchoolSubjects.Add(geography5);

            SchoolSubject geography6 = new SchoolSubject()
            {
                Id            = 2,
                Name          = "Geografija 6",
                WeeklyClasses = 4
            };
            context.SchoolSubjects.Add(geography6);

            SchoolSubject biology5 = new SchoolSubject()
            {
                Id            = 3,
                Name          = "Biologija 5",
                WeeklyClasses = 2,
            };
            context.SchoolSubjects.Add(biology5);

            SchoolSubject biology6 = new SchoolSubject()
            {
                Id            = 4,
                Name          = "Biologija 6",
                WeeklyClasses = 3
            };
            context.SchoolSubjects.Add(biology6);

            SchoolSubject serbian5 = new SchoolSubject()
            {
                Id            = 5,
                Name          = "Srpski 5",
                WeeklyClasses = 4
            };
            context.SchoolSubjects.Add(serbian5);

            SchoolSubject serbian6 = new SchoolSubject()
            {
                Id            = 6,
                Name          = "Srpski 6",
                WeeklyClasses = 4
            };
            context.SchoolSubjects.Add(serbian6);

            #endregion

            context.SaveChanges();

            #region AddingSchoolClasses

            SchoolClass petiA = new SchoolClass()
            {
                Id          = 1,
                SchoolGrade = 5,
                Name        = "A"
            };
            context.SchoolClasses.Add(petiA);

            SchoolClass petiB = new SchoolClass()
            {
                Id          = 2,
                SchoolGrade = 5,
                Name        = "B"
            };
            context.SchoolClasses.Add(petiB);

            SchoolClass sestiA = new SchoolClass()
            {
                Id          = 3,
                SchoolGrade = 6,
                Name        = "A"
            };
            context.SchoolClasses.Add(sestiA);

            SchoolClass sestiB = new SchoolClass()
            {
                Id          = 4,
                SchoolGrade = 6,
                Name        = "B"
            };
            context.SchoolClasses.Add(sestiB);

            #endregion

            context.SaveChanges();

            using (var userStore = new UserStore <ApplicationUser>(context))
            {
                using (var userManager = new UserManager <ApplicationUser>(userStore))
                {
                    #region AddingAdmins

                    Admin admin1 = new Admin()
                    {
                        FirstName = "Chuck",
                        LastName  = "Norris",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(admin1, "qwerty");
                    userManager.AddToRole(admin1.Id, "admin");

                    #endregion

                    #region AddingTeachers

                    Teacher peca = new Teacher()
                    {
                        FirstName = "Petar",
                        LastName  = "Stojakovic",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(peca, "pecaa1");
                    userManager.AddToRole(peca.Id, "teacher");

                    Teacher eugen = new Teacher()
                    {
                        FirstName = "Eugen",
                        LastName  = "Plancak",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(eugen, "eugen1");
                    userManager.AddToRole(eugen.Id, "teacher");

                    Teacher kolarov = new Teacher()
                    {
                        FirstName = "Milos",
                        LastName  = "Kolarov",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(kolarov, "kolarov1");
                    userManager.AddToRole(kolarov.Id, "teacher");

                    Teacher obrad = new Teacher()
                    {
                        FirstName = "Obrad",
                        LastName  = "Stojkovic",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(obrad, "obrad1");
                    userManager.AddToRole(obrad.Id, "teacher");

                    #endregion

                    #region AddingParents

                    Parent parent1 = new Parent()
                    {
                        FirstName = "Gordana",
                        LastName  = "Alasov",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent1, "gordana1");
                    userManager.AddToRole(parent1.Id, "parent");

                    Parent parent2 = new Parent()
                    {
                        FirstName = "Vidosava",
                        LastName  = "Maodus",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent2, "vidaa1");
                    userManager.AddToRole(parent2.Id, "parent");

                    Parent parent3 = new Parent()
                    {
                        FirstName = "Djordje",
                        LastName  = "Atanackovic",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent3, "djole1");
                    userManager.AddToRole(parent3.Id, "parent");

                    Parent parent4 = new Parent()
                    {
                        FirstName = "Snezana",
                        LastName  = "Stojsic",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent4, "sneza1");
                    userManager.AddToRole(parent4.Id, "parent");

                    Parent parent5 = new Parent()
                    {
                        FirstName = "Tatjana",
                        LastName  = "Lekic",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent5, "tanja1");
                    userManager.AddToRole(parent5.Id, "parent");

                    Parent parent6 = new Parent()
                    {
                        FirstName = "Macone",
                        LastName  = "Nedeljkov",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent6, "macaa1");
                    userManager.AddToRole(parent6.Id, "parent");

                    Parent parent7 = new Parent()
                    {
                        FirstName = "Mile",
                        LastName  = "Etinski",
                        UserName  = "******",
                        Email     = "*****@*****.**",
                    };
                    userManager.Create(parent7, "milee1");
                    userManager.AddToRole(parent7.Id, "parent");

                    #endregion

                    #region AddingStudents

                    Student goran = new Student()
                    {
                        FirstName   = "Goran",
                        LastName    = "Alasov",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent1,
                        SchoolClass = sestiA,
                    };

                    userManager.Create(goran, "alasov1");
                    userManager.AddToRole(goran.Id, "student");

                    Student mao = new Student()
                    {
                        FirstName   = "Milan",
                        LastName    = "Maodus",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent2,
                        SchoolClass = sestiA
                    };
                    userManager.Create(mao, "maodus1");
                    userManager.AddToRole(mao.Id, "student");

                    Student roki = new Student()
                    {
                        FirstName   = "Nenad",
                        LastName    = "Maodus",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent2,
                        SchoolClass = petiB
                    };
                    userManager.Create(roki, "rokii1");
                    userManager.AddToRole(roki.Id, "student");

                    Student facan = new Student()
                    {
                        FirstName   = "Bojan",
                        LastName    = "Atanackovic",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent3,
                        SchoolClass = sestiA
                    };
                    userManager.Create(facan, "facan1");
                    userManager.AddToRole(facan.Id, "student");

                    Student jebac = new Student()
                    {
                        FirstName   = "Aleksandar",
                        LastName    = "Atanackovic",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent3,
                        SchoolClass = petiA
                    };
                    userManager.Create(jebac, "jebac1");
                    userManager.AddToRole(jebac.Id, "student");

                    Student doca = new Student()
                    {
                        FirstName   = "Vladimir",
                        LastName    = "Stojsic",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent4,
                        SchoolClass = sestiB
                    };
                    userManager.Create(doca, "doktor1");
                    userManager.AddToRole(doca.Id, "student");

                    Student bogdan = new Student()
                    {
                        FirstName   = "Bogdan",
                        LastName    = "Stojsic",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent4,
                        SchoolClass = petiA
                    };
                    userManager.Create(bogdan, "bogdan1");
                    userManager.AddToRole(bogdan.Id, "student");

                    Student sveta = new Student()
                    {
                        FirstName   = "Svetozar",
                        LastName    = "Lekic",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent5,
                        SchoolClass = sestiB
                    };
                    userManager.Create(sveta, "sveta1");
                    userManager.AddToRole(sveta.Id, "student");

                    Student seba = new Student()
                    {
                        FirstName   = "Nebojsa",
                        LastName    = "Nedeljkov",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent6,
                        SchoolClass = sestiB
                    };
                    userManager.Create(seba, "nebojsa1");
                    userManager.AddToRole(seba.Id, "student");

                    Student tanatelo = new Student()
                    {
                        FirstName   = "Marko",
                        LastName    = "Nedeljkov",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent6,
                        SchoolClass = petiB
                    };
                    userManager.Create(tanatelo, "marko1");
                    userManager.AddToRole(tanatelo.Id, "student");

                    Student pista = new Student()
                    {
                        FirstName   = "Dragan",
                        LastName    = "Etinski",
                        UserName    = "******",
                        Email       = "*****@*****.**",
                        Parent      = parent7,
                        SchoolClass = petiB
                    };
                    userManager.Create(pista, "pista1");
                    userManager.AddToRole(pista.Id, "student");

                    #endregion

                    context.SaveChanges();

                    #region AddingTeacherSchoolSubjects

                    TeacherSchoolSubject pecaGeo5 = new TeacherSchoolSubject()
                    {
                        Id            = 1,
                        Teacher       = peca,
                        SchoolSubject = geography5
                    };
                    context.TeacherSchoolSubjects.Add(pecaGeo5);

                    TeacherSchoolSubject pecaGeo6 = new TeacherSchoolSubject()
                    {
                        Id            = 2,
                        Teacher       = peca,
                        SchoolSubject = geography6
                    };
                    context.TeacherSchoolSubjects.Add(pecaGeo6);

                    TeacherSchoolSubject eugenBio5 = new TeacherSchoolSubject()
                    {
                        Id            = 3,
                        Teacher       = eugen,
                        SchoolSubject = biology5
                    };
                    context.TeacherSchoolSubjects.Add(eugenBio5);

                    TeacherSchoolSubject eugenBio6 = new TeacherSchoolSubject()
                    {
                        Id            = 4,
                        Teacher       = eugen,
                        SchoolSubject = biology6
                    };
                    context.TeacherSchoolSubjects.Add(eugenBio6);

                    TeacherSchoolSubject kolarovSrp5 = new TeacherSchoolSubject()
                    {
                        Id            = 5,
                        Teacher       = kolarov,
                        SchoolSubject = serbian5
                    };
                    context.TeacherSchoolSubjects.Add(kolarovSrp5);

                    TeacherSchoolSubject obradSrp6 = new TeacherSchoolSubject()
                    {
                        Id            = 6,
                        Teacher       = obrad,
                        SchoolSubject = serbian6
                    };
                    context.TeacherSchoolSubjects.Add(obradSrp6);

                    #endregion

                    context.SaveChanges();

                    #region AddingSchoolClassTeacherSchoolSubjects

                    SchoolClassTeacherSchoolSubject pecaGeo5PetiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = pecaGeo5,
                        SchoolClass          = petiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(pecaGeo5PetiA);

                    SchoolClassTeacherSchoolSubject pecaGeo5PetiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = pecaGeo5,
                        SchoolClass          = petiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(pecaGeo5PetiB);

                    SchoolClassTeacherSchoolSubject pecaGeo6SestiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = pecaGeo6,
                        SchoolClass          = sestiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(pecaGeo6SestiA);

                    SchoolClassTeacherSchoolSubject pecaGeo6SestiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = pecaGeo6,
                        SchoolClass          = sestiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(pecaGeo6SestiB);

                    SchoolClassTeacherSchoolSubject eugenBio5PetiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = eugenBio5,
                        SchoolClass          = petiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(eugenBio5PetiA);

                    SchoolClassTeacherSchoolSubject eugenBio5PetiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = eugenBio5,
                        SchoolClass          = petiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(eugenBio5PetiB);

                    SchoolClassTeacherSchoolSubject eugenBio6SestiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = eugenBio6,
                        SchoolClass          = sestiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(eugenBio6SestiA);

                    SchoolClassTeacherSchoolSubject eugenBio6SestiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = eugenBio6,
                        SchoolClass          = sestiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(eugenBio6SestiB);

                    SchoolClassTeacherSchoolSubject kolarovSrp5PetiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = kolarovSrp5,
                        SchoolClass          = petiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(kolarovSrp5PetiA);

                    SchoolClassTeacherSchoolSubject kolarovSrp5PetiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = kolarovSrp5,
                        SchoolClass          = petiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(kolarovSrp5PetiB);

                    SchoolClassTeacherSchoolSubject obradSrp6SestiA = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = obradSrp6,
                        SchoolClass          = sestiA
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(obradSrp6SestiA);

                    SchoolClassTeacherSchoolSubject obradSrp6SestiB = new SchoolClassTeacherSchoolSubject()
                    {
                        TeacherSchoolSubject = obradSrp6,
                        SchoolClass          = sestiB
                    };
                    context.SchoolClassTeacherSchoolSubjects.Add(obradSrp6SestiB);

                    #endregion

                    Grade g1 = new Grade()
                    {
                        Id            = 1,
                        Value         = 4,
                        DateOfGrading = new DateTime(2000, 12, 21),
                        Student       = goran,
                        SchoolClassTeacherSchoolSubject = pecaGeo6SestiA
                    };
                    context.Grades.Add(g1);

                    Grade g2 = new Grade()
                    {
                        Id            = 2,
                        Value         = 3,
                        DateOfGrading = new DateTime(1998, 5, 8),
                        Student       = mao,
                        SchoolClassTeacherSchoolSubject = obradSrp6SestiA
                    };
                    context.Grades.Add(g2);

                    Grade g3 = new Grade()
                    {
                        Id            = 2,
                        Value         = 3,
                        DateOfGrading = new DateTime(1997, 1, 27),
                        Student       = mao,
                        SchoolClassTeacherSchoolSubject = eugenBio6SestiA
                    };
                    context.Grades.Add(g3);

                    Grade g4 = new Grade()
                    {
                        Id            = 2,
                        Value         = 1,
                        DateOfGrading = new DateTime(1997, 9, 11),
                        Student       = roki,
                        SchoolClassTeacherSchoolSubject = eugenBio5PetiB
                    };
                    context.Grades.Add(g4);

                    context.SaveChanges();
                }
            }



            //context.Roles.Add(new IdentityRole() { Id = Guid.NewGuid().ToString(), Name = "admins" });
            //context.Roles.Add(new IdentityRole() { Id = Guid.NewGuid().ToString(), Name = "teachers" });
            //context.Roles.Add(new IdentityRole() { Id = Guid.NewGuid().ToString(), Name= "parents" });
            //context.Roles.Add(new IdentityRole() { Id = Guid.NewGuid().ToString(), Name = "students" });

            //context.SaveChanges();

            //List<ApplicationUser> allUsers = new List<ApplicationUser>();

            //allUsers.Add(admin1);
            //allUsers.Add(teacher1);

            //context.Users.Add(admin1);
            //context.Users.Add(teacher1);

            //context.SaveChanges();
            //SetAllRoles(allUsers, context);


            context.SaveChanges();

            //Admin admin1 = new Admin()
            //{
            //    FirstName = "Goran",
            //    LastName = "Alasov",
            //    UserName = "******",
            //    Email = "*****@*****.**"
            //};

            //Admin admin2 = new Admin()
            //{
            //    FirstName = "Goran1",
            //    LastName = "Alasov1",
            //    UserName = "******",
            //    Email = "[email protected]"
            //};

            //admins.Add(admin1);
            //admins.Add(admin2);

            //context.SaveChanges();
        }
Ejemplo n.º 41
0
        protected override void Seed(BlogContext context)
        {
            var roleStore   = new RoleStore <IdentityRole>(context);
            var roleManager = new RoleManager <IdentityRole>(roleStore);

            List <IdentityRole> identityRoles = new List <IdentityRole>();

            identityRoles.Add(new IdentityRole()
            {
                Name = "Admin"
            });
            identityRoles.Add(new IdentityRole()
            {
                Name = "Guest"
            });
            identityRoles.Add(new IdentityRole()
            {
                Name = "User"
            });

            foreach (IdentityRole role in identityRoles)
            {
                roleManager.Create(role);
            }

            var userStore   = new UserStore <User>(context);
            var userManager = new UserManager <User>(userStore);

            CreateUser(userManager, "*****@*****.**", "user1", "user111", "User");
            CreateUser(userManager, "*****@*****.**", "user2", "user222", "User");
            CreateUser(userManager, "*****@*****.**", "user3", "user333", "User");

            CreateUser(userManager, "*****@*****.**", "admin", "admin123", "Admin");


            context.Posts.Add(new Post
            {
                Title       = "Дэвид Хэй - о возможном бое Усик - Беллью",
                Description = "Экс-чемпион мира Дэвид Хэй поделился ожиданиями от возможного боя между Александром Усиком и Тони Беллью.",
                Text        = "<p>«Усик отличный боец, отличный технарь. Беллью на самом деле не настоящий супертяж. </p>"
                              + "<p>Усик доказал, что он лучший в мире тяжеловес, выиграв турнир.</p>"
                              + "<p>Единственное оставшееся имя в тяжелом весе — это бывший чемпион Тони Беллью», — цитирует Хэя издание vringe.com.</p>",
                UserId   = context.Users.Where(u => u.UserName.Equals("user1")).First().Id,
                PostedAt = new DateTime(2018, 7, 31, 7, 28, 0),
                Tags     = new List <Tag> {
                    new Tag {
                        Id = 1, Name = "Sport"
                    }, new Tag {
                        Id = 2, Name = "Boxing"
                    }
                }
            });

            context.Posts.Add(new Post
            {
                Title       = "5 главных цитат Коко Шанель ",
                Description = "Главные цитаты Коко Шанель, которые нужно знать каждому",
                Text        = "<p>1. В двадцать лет женщина имеет лицо, которое дала ей природа, в тридцать — которое она сделала себе сама, в сорок — то, которое она заслуживает.</p>"
                              + "<p>2. Чтобы быть незаменимой, нужно все время меняться.</p>"
                              + "<p>3. Уход за собой должен начаться с сердца, иначе никакая косметика не поможет.</p>"
                              + "<p>4. Кокетство — это победа разума над чувствами.</p>"
                              + "<p>5. Если вы хотите иметь то, что никогда не имели, вам придется делать то, что никогда не делали.</p>",
                UserId   = context.Users.Where(u => u.UserName.Equals("user2")).First().Id,
                PostedAt = DateTime.Now,
                Tags     = new List <Tag> {
                    new Tag {
                        Id = 3, Name = "Fashion"
                    }, new Tag {
                        Id = 4, Name = "France"
                    }
                }
            });

            context.Posts.Add(new Post
            {
                Title       = "Принципы SOLID",
                Description = "<p>Термин SOLID описывает набор практик проектирования программного кода и построения гибкой и адаптивной программы. <br/>"
                              + "Данный термин был введен 15 лет назад известным американским специалистом в области программирования Робертом Мартином (Robert Martin),<br/>"
                              + " более известным как Uncle Bob (Bob - сокращение от имени Robert)</p>",
                Text = "<p>Single Responsibility Principle (Принцип единственной обязанности)<br/>"
                       + "У класса должна быть только одна причина для изменения.</p>"
                       + "<p>Open/Closed Principle(Принцип открытости / закрытости)<br/>"
                       + "Сущности должны быть открыты для расширения, но закрыты для изменения.</p>"
                       + "<p>Liskov Substitution Principle(Принцип подстановки Лисков)<br/>"
                       + "Объекты в программе могут быть заменены их наследниками без изменения свойств программы.</p>"
                       + "<p>Interface Segregation Principle(Принцип разделения интерфейсов)<br/>"
                       + "Много специализированных интерфейсов лучше, чем один универсальный.</p>"
                       + "<p>Dependency Inversion Principle(Принцип инверсии зависимостей)<br/>"
                       + "Зависимости должны строится относительно абстракций, а не деталей</p>",
                UserId   = context.Users.Where(u => u.UserName.Equals("user2")).First().Id,
                PostedAt = new DateTime(2018, 7, 31, 7, 28, 0),
                Tags     = new List <Tag> {
                    new Tag {
                        Id = 5, Name = "IT"
                    }
                }
            });
            context.SaveChanges();
        }
Ejemplo n.º 42
0
        public ResponseModel EmployeeLoginAsync(EmployeeLoginDto requestParam)
        {
            ResponseModel res       = new ResponseModel();
            var           userStore = new UserStore <ApplicationUser>(_db);
            var           manager   = new UserManager <ApplicationUser>(userStore);

            var result       = manager.Find(requestParam.Email, requestParam.Password);
            var employeeData = _db2.Employees.FirstOrDefault(o => o.EmployeeId == result.Id);
            var uploadInfo   = _db2.Uploads.Where(o => o.UploadId == result.Id).ToList();


            //check if user login successfully
            if (result == null)
            {
                return(res);
            }
            var roleId = _db3.AspNetUserRoles.FirstOrDefault(o => o.UserId == result.Id);
            var role   = _db2.AspNetRoles.FirstOrDefault(o => o.Id == roleId.RoleId);

            IList <UploadDto> uploadDtos = new List <UploadDto>();

            foreach (var item in uploadInfo)
            {
                var uploadId = new UploadDto()
                {
                    UploadId = item.UploadId
                };
                uploadDtos.Add(uploadId);
            }

            //check if account is activated
            if (result.AccountStatus == StatusType.Pending)
            {
                res.Data = "pending";
                return(res);
            }

            var user = new EmployeeLoginDto()
            {
                Address       = result.Address,
                DateOfBirth   = result.DateOfBirth,
                Email         = result.Email,
                FirstName     = result.FirstName,
                LastName      = result.LastName,
                MiddleName    = result.MiddleName,
                Password      = requestParam.Password,
                PhoneNumber   = result.PhoneNumber,
                PlaceOfBirth  = result.PlaceOfBirth,
                StateOfOrigin = result.StateOfOrigin,
            };

            user.Upload = uploadDtos;
            if (employeeData != null)
            {
                user.BVN  = employeeData.BVN;
                user.NIMC = employeeData.NIMC;
            }
            if (result.Sex == SexType.Male)
            {
                user.Sex = "Male";
            }
            else
            {
                user.Sex = "Female";
            }

            res.Data = user;
            return(res);
        }
Ejemplo n.º 43
0
        protected override void Seed(GesNaturaMVC.DAL.GesNaturaDbContext context)
        {
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //

            //Roles
            const string roleName = "Admin";
            const string userName = "******";
            const string password = "******";

            // Antes de adicionar o role verifica se existe
            if (!context.Roles.Any(r => r.Name == roleName))
            {
                context.Roles.Add(new IdentityRole(roleName));
                context.SaveChanges();
            }
            var             userStore   = new UserStore <ApplicationUser>(context);
            var             userManager = new UserManager <ApplicationUser>(userStore);
            ApplicationUser user        = null;

            // Antes de adicionar o utilizador verifica se existe
            if (!context.Users.Any(u => u.UserName == userName))
            {
                user = new ApplicationUser {
                    UserName = userName
                };
                userManager.Create(user, password);
                context.SaveChanges();
            }
            else
            { // Se o utilizador já existe
                user = context.Users.Single(u => u.UserName.Equals(userName,
                                                                   StringComparison.CurrentCultureIgnoreCase));
            }
            userManager.AddToRole(user.Id, roleName);
            context.SaveChanges();


            //context.Percursos.AddOrUpdate(x => x.ID,
            //    new Percurso()
            //    {
            //        ID = 1,
            //        Nome = "Caminho do Paço",
            //        Descricao = "Percurso junto ao Rio Germinade, onde podemos observar várias " +
            //        "espécies de aves. Inserido em pleno parque N. Sra de Lurdes",
            //        Dificuldade = "Baixa",
            //        Distancia = 2,
            //        DuracaoAproximada = 2,
            //        Tipologia = "Circular",
            //        GPS_Lat_Inicio = 41.002450F,
            //        GPS_Long_Inicio = -8.162835F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBcmdCOW9YMFNTLWM"

            //    },
            //    new Percurso()
            //    {
            //        ID = 2,
            //        Nome = "Caminho do Loureiro",
            //        Descricao = "Rumo ao monte. Subir ao cimo do monte, e respirar ar puro",
            //        Dificuldade = "Media",
            //        Distancia = 2,
            //        DuracaoAproximada = 2,
            //        Tipologia = "Circular",
            //        GPS_Lat_Inicio = 40.997354F,
            //        GPS_Long_Inicio = -8.161707F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBdWc5NGRUUmNzRHc"

            //    },
            //    new Percurso()
            //    {
            //        ID = 3,
            //        Nome = "Caminho da Balsa",
            //        Descricao = "Percurso entre 2 maravilhas da Natureza: Parque N. Sra Lurdes" +
            //        " e a ponte da Balsa",
            //        Dificuldade = "Baixa",
            //        Distancia = 2,
            //        DuracaoAproximada = 1,
            //        Tipologia = "Linear",
            //        GPS_Lat_Inicio = 40.998240F,
            //        GPS_Long_Inicio = -8.171382F,
            //        KmlPath = "https://docs.google.com/uc?export=download&id=0Bxc0V7hINajBdEcwcWpzNXZHb2c"

            //    });

            //context.POIs.AddOrUpdate(x => x.ID,
            //     new POI() {
            //         ID =1,
            //         Nome ="Miradouro de Aves",
            //         Descricao ="Local onde é possivel admirar aves de Rapina",
            //         GPS_Lat=40.995009F,
            //         GPS_Long=-8.159134F,
            //         PercursoId=2
            //     },
            //     new POI()
            //     {
            //         ID = 2,
            //         Nome = "Antiga Azenha",
            //         Descricao = "Local de grandes recordações com uma envolvência natural soberba",
            //         GPS_Lat = 41.000737F,
            //         GPS_Long = -8.163427F,
            //         PercursoId = 3
            //     });

            //context.Reinoes.AddOrUpdate(x=>x.ID,
            //    new Reino() { ID = 1, Nome="Animal"},
            //    new Reino() { ID = 2, Nome="Vegetal"});

            //context.Classes.AddOrUpdate(x => x.ID,
            //    new Classe() { ID = 1, Nome = "Aves", ReinoID=1 },
            //    new Classe() { ID = 2, Nome = "Insetos", ReinoID=1 },
            //    new Classe() { ID = 3, Nome = "Arvores", ReinoID = 2 },
            //    new Classe() { ID = 4, Nome = "Repteis", ReinoID = 1 });

            //context.Ordems.AddOrUpdate(x => x.ID,
            //    new Ordem() { ID = 1, Nome = "Passeriformes", ClasseID = 1 },
            //    new Ordem() { ID = 2, Nome = "Fagales", ClasseID = 2 },
            //    new Ordem() { ID = 3, Nome = "Accipitriformes", ClasseID = 1 },
            //    new Ordem() { ID = 4, Nome = "Bucerotiformes", ClasseID = 1 });

            //context.Familias.AddOrUpdate(x => x.ID,
            //    new Familia() { ID = 1, Nome = "Motacillidae", OrdemID = 1 },
            //    new Familia() { ID = 2, Nome = "Paridae", OrdemID = 1 },
            //    new Familia() { ID = 3, Nome = "Passeridae", OrdemID = 1 });

            //context.Generoes.AddOrUpdate(x => x.ID,
            //    new Genero() { ID = 1, Nome = "Motacilla", FamiliaID = 1 },
            //    new Genero() { ID = 2, Nome = "Parus",     FamiliaID = 2 },
            //    new Genero() { ID = 3, Nome = "Passer",    FamiliaID = 3 });

            //context.Especies.AddOrUpdate(x => x.ID,
            //    new Especie() { ID = 1, Nome = "Alvéola branca", NomeCientifico = "Motacilla alba", GeneroID = 1 },
            //    new Especie() { ID = 2, Nome = "Chapim-real", NomeCientifico = "Parus major", GeneroID = 2 },
            //    new Especie() { ID = 3, Nome = "Pardal-comum", NomeCientifico = "Passer domesticus", GeneroID = 3 });
        }
Ejemplo n.º 44
0
        public static void Initialize()
        {
            using (var db = new MySqlIdentityDbContext())
            {
                // add "Ressenti" field in Application
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'Ressenti') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[Ressenti] NVARCHAR(Max)
                                                        END");
                // add table template email
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='EmailTemplates' and xtype='U')
                                                CREATE TABLE EmailTemplates
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Name NVARCHAR(max) null,
		                                                [Type] NVARCHAR(max) null,
                                                        [Subject] NVARCHAR(max) null,
		                                                Body NVARCHAR(max) null,
		                                                DynamicField NVARCHAR(max) null,
		                                                CONSTRAINT [PK_dbo.Emails] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");
                // Add table Contact Linkedin
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='ContactLinkedins' and xtype='U')
                                                CREATE TABLE ContactLinkedins
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Title NVARCHAR(max) null,
		                                                Firstname NVARCHAR(max) null,
                                                        Middlename NVARCHAR(max) null,
                                                        Lastname NVARCHAR(max) null,
                                                        Suffix NVARCHAR(max) null,
                                                        Email NVARCHAR(max) null,
		                                                Company NVARCHAR(max) null,
                                                        Position NVARCHAR(max) null,
		                                                DynamicField NVARCHAR(max) null,
		                                                CONSTRAINT [PK_dbo.ContactLinkedins] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // Add table Customers
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Customers' and xtype='U')
                                                CREATE TABLE Customers
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Title NVARCHAR(max) null,
		                                                Firstname NVARCHAR(max) null,
                                                        Middlename NVARCHAR(max) null,
                                                        Lastname NVARCHAR(max) null,
                                                        Suffix NVARCHAR(max) null,
                                                        Email NVARCHAR(max) null,
		                                                Company NVARCHAR(max) null,
                                                        Position NVARCHAR(max) null,
                                                        MobilePhone NVARCHAR(max) null,
		                                                Workphone NVARCHAR(max) null,
                                                        BusinessAddress NVARCHAR(max) null,
		                                                DynamicField NVARCHAR(max) null,
		                                                CONSTRAINT [PK_dbo.Customers] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // Add table Documents
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Documents' and xtype='U')
                                                CREATE TABLE Documents
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Filename NVARCHAR(max) null,
		                                                AbsolutPath NVARCHAR(max) null,
                                                        RelativePath NVARCHAR(max) null,
                                                        Categories NVARCHAR(max) null,
                                                        FolderName NVARCHAR(max) null,                                                       
		                                                CONSTRAINT [PK_dbo.documents] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // add "Version" field in Application
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Documents', 'Version') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Documents
                                                                ADD[Version] int
                                                        END");



                // Add table DocumentVersions
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='DocumentVersions' and xtype='U')
                                                CREATE TABLE DocumentVersions
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
		                                                AbsolutPath NVARCHAR(max) null,
                                                        RelativePath NVARCHAR(max) null,
                                                        Version INT null,        
                                                        DocumentId NVARCHAR(max) null,                                              
		                                                CONSTRAINT [PK_dbo.documentVersions] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");
                // add "Metadata" field in Application
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'Metadata') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[Metadata] NVARCHAR(Max)
                                                        END");

                // Add table Interviews
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Interviews' and xtype='U')
                                                CREATE TABLE Interviews
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Name NVARCHAR(max) null,     
                                                        CandidatId NVARCHAR(128) NULL,
                                                        Commentaire NVARCHAR(128) NULL,
                                                        Skills NVARCHAR(128) NULL,
                                                        Configuration NVARCHAR(max) null,
                                                        Metadata NVARCHAR(max) null,                       
		                                                CONSTRAINT [PK_dbo.interviews] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");
                // Add table Spaces
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Spaces' and xtype='U')
                                                CREATE TABLE Spaces
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        Name NVARCHAR(max) null, 
                                                        Configuration NVARCHAR(max) null,
                                                        Metadata NVARCHAR(max) null,                       
		                                                CONSTRAINT [PK_dbo.spaces] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // add "BlackListed" field in Application
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'BlackListed') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[BlackListed] BIT 
                                                        END");

                // add "Questions" field in interview
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'Questions') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[Questions] NVARCHAR(max) null 
                                                        END");

                // Alter column size of interviews table
                db.Database.ExecuteSqlCommand(@"IF (SELECT TOP 1 CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Interviews' AND COLUMN_NAME = 'Commentaire') = 128
                                                BEGIN
		                                                ALTER TABLE Interviews ALTER COLUMN Commentaire NVARCHAR(max)
                                                END");

                db.Database.ExecuteSqlCommand(@"IF (SELECT TOP 1 CHARACTER_MAXIMUM_LENGTH FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Interviews' AND COLUMN_NAME = 'Skills') = 128
                                                BEGIN
		                                                ALTER TABLE Interviews ALTER COLUMN Skills NVARCHAR(max)
                                                END");

                // add "CustomerId" field in Application
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'CustomerId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[CustomerId] NVARCHAR(max) 
                                                        END");

                // add "SpaceId" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[DeletedOn] datetime
                                                        END");

                // add "SpaceId" field in CurriculumVitaes table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('CurriculumVitaes', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE CurriculumVitaes
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in CurriculumVitaes table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('CurriculumVitaes', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE CurriculumVitaes
                                                                ADD[DeletedOn] datetime
                                                        END");
                // add "SpaceId" field in ContactLinkedins table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('ContactLinkedins', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE ContactLinkedins
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in ContactLinkedins table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('ContactLinkedins', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE ContactLinkedins
                                                                ADD[DeletedOn] datetime
                                                        END");
                // add "SpaceId" field in Customers table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Customers', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Customers
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in Customers table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Customers', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Customers
                                                                ADD[DeletedOn] datetime
                                                        END");

                // add "SpaceId" field in Documents table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Documents', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Documents
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in Documents table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Documents', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Documents
                                                                ADD[DeletedOn] datetime
                                                        END");
                // add "SpaceId" field in DocumentVersions table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('DocumentVersions', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE DocumentVersions
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in DocumentVersions table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('DocumentVersions', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE DocumentVersions
                                                                ADD[DeletedOn] datetime
                                                        END");

                // add "SpaceId" field in EmailTemplates table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('EmailTemplates', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE EmailTemplates
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in EmailTemplates table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('EmailTemplates', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE EmailTemplates
                                                                ADD[DeletedOn] datetime
                                                        END");
                // add "SpaceId" field in Interviews table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'SpaceId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[SpaceId] NVARCHAR(Max)
                                                        END");

                // add "DeletedOn" field in Interviews table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'DeletedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[DeletedOn] datetime
                                                        END");

                // Add table Quizs
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Quizs' and xtype='U')
                                                CREATE TABLE Quizs
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        QuizInfo NVARCHAR(max) null,                                                 
                                                        Metadata NVARCHAR(max) null,
                                                        CreatedBy NVARCHAR(128) NULL,     
                                                        CreatedOn datetime NULL,    
                                                        SpaceId NVARCHAR(128) NULL,
                                                        DeletedBy NVARCHAR(128) NULL,
                                                        DeletedOn datetime NULL,
                                                                               
		                                                CONSTRAINT [PK_dbo.Quizs] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");
                // Add table Quizruns
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Quizruns' and xtype='U')
                                                CREATE TABLE Quizruns
                                                (
		                                                Id NVARCHAR(128) NOT NULL,	  
                                                        QuizId NVARCHAR(128) NULL,
                                                        UserId NVARCHAR(128) NULL,
                                                        QuizRunInfo NVARCHAR(max) null,   
                                                        StartedOn datetime NULL,
                                                        FinishedOn datetime NULL,
                                                        TimeSpent  BIGINT NULL,                                            
                                                        Metadata NVARCHAR(max) null,
                                                        CreatedBy NVARCHAR(128) NULL,     
                                                        CreatedOn datetime NULL,    
                                                        SpaceId NVARCHAR(128) NULL,
                                                        DeletedBy NVARCHAR(128) NULL,
                                                        DeletedOn datetime NULL,
                                                                               
		                                                CONSTRAINT [PK_dbo.Quizruns] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // add "UserId" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'UserId') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[UserId] NVARCHAR(128)
                                                        END");

                // Add table Missions
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Missions' and xtype='U')
                                                CREATE TABLE Missions
                                                (
		                                                Id NVARCHAR(128) NOT NULL,
                                                        Name NVARCHAR(max) null,      
                                                        Info NVARCHAR(max) null,                                                 
                                                        Metadata NVARCHAR(max) null,
                                                        CreatedBy NVARCHAR(128) NULL,     
                                                        CreatedOn datetime NULL,    
                                                        SpaceId NVARCHAR(128) NULL,
                                                        DeletedBy NVARCHAR(128) NULL,
                                                        DeletedOn datetime NULL,
                                                                               
		                                                CONSTRAINT [PK_dbo.Missions] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");


                // add "BodyUrl" field in EmailTemplates table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('EmailTemplates', 'BodyUrl') IS NULL
                                                        BEGIN
                                                                ALTER TABLE EmailTemplates
                                                                ADD[BodyUrl] NVARCHAR(max)
                                                        END");

                // add "Lang" field in EmailTemplates table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('EmailTemplates', 'Lang') IS NULL
                                                        BEGIN
                                                                ALTER TABLE EmailTemplates
                                                                ADD[Lang] NVARCHAR(128)
                                                        END");

                // add "CreatedBy" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'CreatedBy') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[CreatedBy] NVARCHAR(128)
                                                        END");

                // add "DeletedBy" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'DeletedBy') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[DeletedBy] NVARCHAR(128)
                                                        END");

                // add "CreatedOn" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Candidats', 'CreatedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Candidats
                                                                ADD[CreatedOn] datetime
                                                        END");

                // Add table Questions
                db.Database.ExecuteSqlCommand(@"IF not exists (select * from sysobjects where name='Questions' and xtype='U')
                                                CREATE TABLE Questions
                                                (
		                                                Id NVARCHAR(128) NOT NULL,
                                                        Name NVARCHAR(max) null,      
                                                        Info NVARCHAR(max) null,                                                 
                                                        Metadata NVARCHAR(max) null,
                                                        CreatedBy NVARCHAR(128) NULL,     
                                                        CreatedOn datetime NULL,    
                                                        SpaceId NVARCHAR(128) NULL,
                                                        DeletedBy NVARCHAR(128) NULL,
                                                        DeletedOn datetime NULL,
                                                        Description NVARCHAR(max) null, 
                                                        Tags NVARCHAR(max) null, 
                                                                               
		                                                CONSTRAINT [PK_dbo.Questions] PRIMARY KEY CLUSTERED ([Id] ASC)
                                                )");

                // add "DeletedBy" field in Interviews table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'DeletedBy') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[DeletedBy]  NVARCHAR(128)
                                                        END");

                // add "CreatedBy" field in Interviews table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'CreatedBy') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[CreatedBy]  NVARCHAR(128)
                                                        END");

                // add "CreatedOn" field in Interviews table
                db.Database.ExecuteSqlCommand(@"IF COL_LENGTH('Interviews', 'CreatedOn') IS NULL
                                                        BEGIN
                                                                ALTER TABLE Interviews
                                                                ADD[CreatedOn] datetime
                                                        END");

                // Modify "Typerecherche" field in Candidats table
                db.Database.ExecuteSqlCommand(@"IF (SELECT TOP 1 DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'Candidats' AND COLUMN_NAME = 'Typerecherche') = 'int'
                                                BEGIN
                                                        ALTER TABLE Candidats
                                                        ALTER COLUMN Typerecherche NVARCHAR(max) NULL
                                                END");
            }

            using (var dbuser = new ApplicationDbContext())
            {
                IUserStore <ApplicationUser> store       = new UserStore <ApplicationUser>(dbuser);
                ApplicationUserManager       UserManager = new ApplicationUserManager(store);
                var user = UserManager.FindByEmail("*****@*****.**");

                if (!UserManager.IsInRole(user.Id, "Supervisor"))
                {
                    var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(dbuser));

                    if (!RoleManager.RoleExists("Supervisor"))
                    {
                        IdentityRole   newRole = new IdentityRole("Supervisor");
                        IdentityResult result  = RoleManager.Create(newRole);
                        if (result.Succeeded)
                        {
                            UserManager.AddToRole(user.Id, "Supervisor");
                        }
                    }
                    else
                    {
                        UserManager.AddToRole(user.Id, "Supervisor");
                    }
                }

                // Create Supervision space
                var   db = new MySqlIdentityDbContext();
                Space spaceSupervision = new Space();
                if (db.Spaces.Where(a => a.Name == "Root").FirstOrDefault() == null)
                {
                    spaceSupervision.Name = "Root";
                    db.Spaces.Add(spaceSupervision);
                    db.SaveChanges();
                }
                if (user != null)
                {
                    var claims = UserManager.GetClaims(user.Id);
                    var claim  = claims.Where(a => a.Type == "SpaceId").FirstOrDefault();
                    if (claim == null)
                    {
                        UserManager.AddClaim(user.Id, new Claim("SpaceId", spaceSupervision.Id));
                    }
                }
            }
        }
Ejemplo n.º 45
0
        protected override void Seed(ApplicationDbContext context)
        {
            base.Seed(context);

            //Add Role
            //-------------------------------------------------------------------------
            var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            foreach (var role in Enum.GetValues(typeof(Roles)))
            {
                RoleManager.Create(new IdentityRole(Enum.GetName(typeof(Roles), role)));
            }

            context.SaveChanges();

            //Add User
            //-------------------------------------------------------------------------
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            var adminUser = new ApplicationUser
            {
                UserName             = AppSettings["admin:username"],
                Email                = AppSettings["admin:email"],
                EmailConfirmed       = true,
                PhoneNumber          = AppSettings["admin:phone"],
                PhoneNumberConfirmed = true,
            };

            userManager.Create(adminUser, AppSettings["admin:password"]);
            userManager.AddToRole(adminUser.Id, Roles.Admin.ToString());
            userManager.AddToRole(adminUser.Id, Roles.AppUser.ToString());

            context.SaveChanges();

            //Add Setting
            //-------------------------------------------------------------------------
            List <Setting> list = new List <Setting> {
                new Setting {
                    key = "Name", value = "پرنیان"
                },
                new Setting {
                    key = "Slogan", value = "مؤسسه‌ی فرهنگی هنری پرنیان اندیشه هنر"
                },
                new Setting {
                    key = "Description", value = "مؤسسه‌ی فرهنگی هنری پرنیان اندیشه هنر"
                },
                new Setting {
                    key = "Keywords", value = "تبلیغ، مستند، نماهنگ"
                },
                new Setting {
                    key = "Logo", value = "logo.png"
                },
                new Setting {
                    key = "Background", value = "bg.jpg"
                }
            };

            list.ForEach(s => context.Settings.Add(s));

            context.Categories.Add(new Category
            {
                title        = "گروه ویدئو",
                type         = CategoryType.video,
                isMenuItem   = true,
                creatorName  = adminUser.Id,
                creationTime = PersianDateTime.Now.ToLongDateTimeString(),
                priority     = 1,
            });

            context.SaveChanges();

            context.Slides.Add(new Slide
            {
                title        = "اسلاید اول",
                creatorName  = adminUser.Id,
                creationTime = PersianDateTime.Now.ToLongDateTimeString(),
                priority     = 1,
            });

            context.SaveChanges();
        }
Ejemplo n.º 46
0
        // Start chatting loop
        public async Task StartChatAsync(string userId, Dictionary <string, object> payloads = null)
        {
            // Get cancellation token
            var token = GetChatToken();

            // Get user
            var user = await UserStore.GetUserAsync(userId);

            if (user == null || string.IsNullOrEmpty(user.Id))
            {
                Debug.LogError($"Error occured in getting user: {userId}");
                await OnErrorAsync(null, null, token);

                return;
            }

            // Get context
            var context = await ContextStore.GetContextAsync(user.Id);

            if (context == null)
            {
                Debug.LogError($"Error occured in getting context: {user.Id}");
                await OnErrorAsync(null, null, token);

                return;
            }

            // Prompt
            try
            {
                await OnPromptAsync(user, context, token);
            }
            catch (TaskCanceledException)
            {
                return;
            }
            catch (Exception ex)
            {
                Debug.LogError($"Error occured in speaking prompt: {ex.Message}\n{ex.StackTrace}");
                // Restart idling animation and reset face expression
                _ = ModelController.StartIdlingAsync();
                _ = ModelController.SetDefaultFace();
                return;
            }

            // Chat loop. Exit when session ends, canceled or error occures
            while (true)
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                // Get request (microphone / camera / QR code, etc)
                var request = await RequestProviders[context.Topic.RequiredRequestType].GetRequestAsync(user, context, token);

                try
                {
                    if (!request.IsSet())
                    {
                        break;
                    }
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Extract intent
                    var intentResponse = await IntentExtractor.ExtractIntentAsync(request, context, token);

                    if (string.IsNullOrEmpty(request.Intent) && string.IsNullOrEmpty(context.Topic.Name))
                    {
                        await OnNoIntentAsync(request, context, token);

                        break;
                    }
                    else
                    {
                        Debug.Log($"Intent:{request.Intent}({request.IntentPriority.ToString()})");
                        if (request.Entities.Count > 0)
                        {
                            var entitiesString = "Entities:";
                            foreach (var kv in request.Entities)
                            {
                                var v = kv.Value != null?kv.Value.ToString() : "null";

                                entitiesString += $"\n - {kv.Key}: {v}";
                            }
                            Debug.Log(entitiesString);
                        }
                    }
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Start show response
                    var intentResponseTask = IntentExtractor.ShowResponseAsync(intentResponse, request, context, token);
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Get dialog to process intent / topic
                    var dialogProcessor = DialogRouter.Route(request, context, token);
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Process dialog
                    var dialogResponse = await dialogProcessor.ProcessAsync(request, context, token);

                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Wait for intentTask before show response of dialog
                    if (intentResponseTask != null)
                    {
                        await intentResponseTask;
                    }
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Show response of dialog
                    await dialogProcessor.ShowResponseAsync(dialogResponse, request, context, token);

                    if (token.IsCancellationRequested)
                    {
                        return;
                    }

                    // Post process
                    if (context.Topic.ContinueTopic)
                    {
                        // Save context
                        await ContextStore.SaveContextAsync(context);

                        // Update properties for next
                        context.IsNew               = false;
                        context.Topic.IsNew         = false;
                        context.Topic.ContinueTopic = false;
                    }
                    else
                    {
                        // Clear context data and topic then exit
                        context.Clear();
                        await ContextStore.SaveContextAsync(context);

                        break;
                    }
                }
                catch (TaskCanceledException)
                {
                    await ContextStore.DeleteContextAsync(user.Id);

                    return;
                }
                catch (Exception ex)
                {
                    Debug.LogError($"Error occured in processing chat: {ex.Message}\n{ex.StackTrace}");
                    if (!token.IsCancellationRequested)
                    {
                        // Stop running animation and voice then get new token to say error
                        token = GetChatToken();
                        await OnErrorAsync(request, context, token);

                        await ContextStore.DeleteContextAsync(user.Id);
                    }
                    break;
                }
                finally
                {
                    if (!token.IsCancellationRequested)
                    {
                        // Restart idling animation and reset face expression
                        _ = ModelController.StartIdlingAsync();
                        _ = ModelController.SetDefaultFace();
                    }
                }
            }
        }
Ejemplo n.º 47
0
        public static void InitializeMySqlDatabase()
        {
            // Ajout du compte superviseur et creation de la base si pas exister
            using (var context = new ApplicationDbContext())
            {
                var userStore    = new UserStore <ApplicationUser>(context);
                var userManager  = new UserManager <ApplicationUser>(userStore);
                var userToInsert = new ApplicationUser {
                    UserName = "******", Email = "*****@*****.**", PhoneNumber = "0797697898"
                };
                var exist = userManager.FindByEmail("*****@*****.**");
                if (exist == null)
                {
                    userManager.Create(userToInsert, "pti.preu");

                    // ADD ROLE SUPERVISOR TO USER
                    var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));
                    if (!RoleManager.RoleExists("Supervisor"))
                    {
                        IdentityRole   newRole = new IdentityRole("Supervisor");
                        IdentityResult result  = RoleManager.CreateAsync(newRole).Result;
                    }

                    userManager.AddToRoleAsync(userToInsert.Id, "Supervisor");
                }
            }

            // passage du fichier de migration
            Space spaceSupervision = new Space();

            using (var db = new MySqlIdentityDbContext())
            {
                string filPath       = AppDomain.CurrentDomain.BaseDirectory + "/Migration/initializeQuery.sql";
                string creationQuery = File.ReadAllText(filPath);
                db.Database.ExecuteSqlCommand(creationQuery);

                // Create Supervision space
                if (db.Spaces.Where(a => a.Name == "Root").FirstOrDefault() == null)
                {
                    spaceSupervision.Name = "Root";
                    db.Spaces.Add(spaceSupervision);
                    db.SaveChanges();
                }
            }

            // Ajout de l'espace au compte superviseur
            using (var context2 = new ApplicationDbContext())
            {
                var userStore   = new UserStore <ApplicationUser>(context2);
                var userManager = new UserManager <ApplicationUser>(userStore);

                var exist = userManager.FindByEmail("*****@*****.**");
                if (exist != null)
                {
                    var claims = userManager.GetClaims(exist.Id);
                    var claim  = claims.Where(a => a.Type == "SpaceId").FirstOrDefault();
                    if (claim == null)
                    {
                        userManager.AddClaim(exist.Id, new Claim("SpaceId", spaceSupervision.Id));
                    }
                }
            }
        }
Ejemplo n.º 48
0
 /// <summary> Returns users (UserNames) in specified role </summary>
 public override string[] GetUsersInRole(string roleName)
 {
     return(UserStore.GetUsersInRole(roleName));
 }
Ejemplo n.º 49
0
        protected override void Seed(DatabaseContext context)
        {
            if (!context.Roles.Any(r => r.Name == "Administrator"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);

                var role = new ApplicationRole {
                    Name = "Administrator"
                };
                manager.Create(role);
            }
            if (!context.Roles.Any(r => r.Name == "User"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole {
                    Name = "User"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Manager"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole {
                    Name = "Manager"
                };
                manager.Create(role);
            }

            if (!context.Roles.Any(r => r.Name == "Anonymous"))
            {
                var store   = new RoleStore <ApplicationRole>(context);
                var manager = new RoleManager <ApplicationRole>(store);
                var role    = new ApplicationRole {
                    Name = "Anonymous"
                };
                manager.Create(role);
            }

            if (!context.Users.Any(u => u.UserName == "admin"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    Id       = AccountIds.Admin.GetGuid().ToString(),
                    UserName = "******", Name = "Tran Duy", Email = "*****@*****.**", Balance = 0, EmailConfirmed = true
                };

                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "Administrator");
            }
            if (!context.Users.Any(u => u.UserName == "user"))
            {
                var store   = new UserStore <ApplicationUser>(context);
                var manager = new UserManager <ApplicationUser>(store);
                var user    = new ApplicationUser
                {
                    Id             = AccountIds.User1.GetGuid().ToString(),
                    UserName       = "******",
                    Name           = "user",
                    Email          = "*****@*****.**",
                    Balance        = 0,
                    EmailConfirmed = true
                };

                manager.Create(user, "123456");
                manager.AddToRole(user.Id, "User");
            }

            //TestDataSeed(context).GetAwaiter().GetResult();

            base.Seed(context);
        }
Ejemplo n.º 50
0
        protected override void Seed(HMS.Models.ApplicationDbContext context)
        {
            context.Departments.AddOrUpdate(
                d => d.Name,
                new Department
            {
                Name             = "Emergency Care",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-131071"
            },
                new Department
            {
                Name             = "Cardiology",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-12625"
            },
                new Department
            {
                Name             = "ENT",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-105385"
            },
                new Department
            {
                Name             = "Eye Care",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-131019"
            },
                new Department
            {
                Name             = "Diabetes Care",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-131019"
            },
                new Department
            {
                Name             = "Orthopedics",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-105402"
            }
                ,
                new Department
            {
                Name             = "Pulmology",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-45987"
            },
                new Department
            {
                Name             = "Child Care",
                Fee              = 500,
                ShortDescription = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                IconCode         = "ambulance-icon flaticon-icon-49091"
            }
                );
            context.SaveChanges();

            context.Events.AddOrUpdate(
                e => e.Title,
                new ProbableEvent
            {
                Title            = "Free checkup in children day",
                EventDate        = DateTime.Parse("2018-11-14"),
                ShortDescription =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                FeatureImagePath = "~/Images/event-1.jpg"
            },
                new ProbableEvent
            {
                Title            = "Free checkup in victory day",
                EventDate        = DateTime.Parse("2018-12-16"),
                ShortDescription =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                FeatureImagePath = "~/Images/event-2.jpg"
            }
                );
            context.SaveChanges();
            context.Blogs.AddOrUpdate(
                e => e.Title,
                new Blog
            {
                Title     = "Launched Child Care Department",
                AuthorId  = "2e0602e9-d083-42c4-b9ec-b86cf88d4656",
                CreatedAt = DateTime.Today,
                Content   =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                FeatureImagePath = "~/Images/blog-img-4.jpg"
            },
                new Blog
            {
                Title     = "New machines in Eye Care",
                AuthorId  = "2e0602e9-d083-42c4-b9ec-b86cf88d4656",
                CreatedAt = DateTime.Today,
                Content   =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                FeatureImagePath = "~/Images/blog-img-1.jpg"
            }
                );
            context.SaveChanges();

            context.Testimonials.AddOrUpdate(
                t => t.Name,
                new Testimonial
            {
                Name        = "John Doe",
                Designation = "Engineer",
                Message     =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                ProfileImagePath = "~/Images/test-client-1.jpg"
            },
                new Testimonial
            {
                Name        = "Jane Doe",
                Designation = "Reporter",
                Message     =
                    "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever.",
                ProfileImagePath = "~/Images/test-client-2.jpg"
            }
                );

            //Seeding Doctor Users
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName    = "******",
                    FullName    = "John Doe",
                    Gender      = "Male",
                    DateOfBirth = DateTime.Parse("1990-01-01"),
                    Address     = "sample address",
                    Mobile      = "01300111222",
                    Email       = "*****@*****.**",

                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Emergency Care");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName         = "******",
                    FullName         = "John Doe",
                    Mobile           = "01300111222",
                    Email            = "*****@*****.**",
                    Gender           = "Male",
                    DateOfBirth      = DateTime.Parse("1990-01-01"),
                    Address          = "sample address",
                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Cardiology");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }

            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName    = "******",
                    FullName    = "John Doe",
                    Gender      = "Male",
                    DateOfBirth = DateTime.Parse("1990-01-01"),
                    Address     = "sample address",
                    Mobile      = "01300111222",
                    Email       = "*****@*****.**",

                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "ENT");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName         = "******",
                    FullName         = "John Doe",
                    Mobile           = "01300111222",
                    Gender           = "Male",
                    DateOfBirth      = DateTime.Parse("1990-01-01"),
                    Address          = "sample address",
                    Email            = "*****@*****.**",
                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Eye Care");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName         = "******",
                    FullName         = "John Doe",
                    Gender           = "Male",
                    DateOfBirth      = DateTime.Parse("1990-01-01"),
                    Address          = "sample address",
                    Mobile           = "01300111222",
                    Email            = "*****@*****.**",
                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Diabetes Care");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName         = "******",
                    FullName         = "John Doe",
                    Mobile           = "01300111222",
                    Gender           = "Male",
                    DateOfBirth      = DateTime.Parse("1990-01-01"),
                    Address          = "sample address",
                    Email            = "*****@*****.**",
                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Orthopedics");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName         = "******",
                    FullName         = "John Doe",
                    Mobile           = "01300111222",
                    Gender           = "Male",
                    DateOfBirth      = DateTime.Parse("1990-01-01"),
                    Address          = "sample address",
                    Email            = "*****@*****.**",
                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Pulmology");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            if (!(context.Users.Any(u => u.UserName == "*****@*****.**")))
            {
                var userToInsert = new ApplicationUser
                {
                    UserName    = "******",
                    FullName    = "John Doe",
                    Mobile      = "01300111222",
                    Gender      = "Male",
                    DateOfBirth = DateTime.Parse("1990-01-01"),
                    Address     = "sample address",
                    Email       = "*****@*****.**",

                    ProfileImagePath = "~/Images/dr-grid-1.jpg"
                };
                var result = userManager.Create(userToInsert, "Password@123");
                if (result.Succeeded)
                {
                    userManager.AddToRole(userToInsert.Id, "Doctor");
                    var department       = context.Departments.SingleOrDefault(d => d.Name == "Child Care");
                    var doctorDepartment = new DoctorDepartment
                    {
                        DepartmentId = department.DepartmentId,
                        DoctorUserId = userToInsert.Id
                    };
                    context.DoctorDepartments.AddOrUpdate(doctorDepartment);
                    context.SaveChanges();
                }
            }
            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
Ejemplo n.º 51
0
 public override string[] GetRolesForUser(string userName)
 {
     return(UserStore.GetRolesForUser(userName));
 }
Ejemplo n.º 52
0
 public RolesController()
 {
     _context     = new ApplicationDbContext();
     _userStore   = new UserStore <ApplicationUser>(_context);
     _userManager = new UserManager <ApplicationUser>(_userStore);
 }
Ejemplo n.º 53
0
        public async Task <ActionResult> ExternalLoginConfirmation(ExtendedExternalLoginConfirmation model, string returnUrl)
        {
            using (var context = new ApplicationDbContext())
            {
                if (User.Identity.IsAuthenticated)
                {
                    return(RedirectToAction("Index", "Manage"));
                }

                if (ModelState.IsValid)
                {
                    // Get the information about the user from the external login provider
                    var info = await AuthenticationManager.GetExternalLoginInfoAsync();

                    if (info == null)
                    {
                        return(View("ExternalLoginFailure"));
                    }

                    if (model.UserProfilePicture != null)
                    {
                        if (model.UserProfilePicture.ContentLength > (4 * 1024 * 1024))
                        {
                            ModelState.AddModelError("CustomError", "Image can not be lager than 4MB.");
                            return(View());
                        }
                        if (!(model.UserProfilePicture.ContentType == "image/jpeg" || model.UserProfilePicture.ContentType == "image/gif"))
                        {
                            ModelState.AddModelError("CustomError", "Image must be in jpeg or gif format.");
                        }
                    }
                    byte[] data = new byte[model.UserProfilePicture.ContentLength];
                    model.UserProfilePicture.InputStream.Read(data, 0, model.UserProfilePicture.ContentLength);

                    var user = new ApplicationUser
                    {
                        UserName  = model.Email,
                        Email     = model.Email,
                        BirthDate = model.BirthDate,
                        Firstname = model.Firstname,
                        Surname   = model.Surname,
                        Photo     = data
                    };

                    var result = await UserManager.CreateAsync(user);


                    var roleStore   = new RoleStore <IdentityRole>(context);
                    var roleManager = new RoleManager <IdentityRole>(roleStore);

                    var userStore   = new UserStore <ApplicationUser>(context);
                    var userManager = new UserManager <ApplicationUser>(userStore);
                    userManager.AddToRole(user.Id, "Employee");

                    if (result.Succeeded)
                    {
                        result = await UserManager.AddLoginAsync(user.Id, info.Login);

                        if (result.Succeeded)
                        {
                            //await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);

                            // Send an email with this link
                            //string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
                            //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
                            //await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");

                            string callbackUrl = await SendEmailConfirmationTokenAsync(user.Id, "Confirm your account");

                            ViewBag.Message = "Check your email and confirm your account, you must be confirmed "
                                              + "before you can log in.";


                            return(View("Info"));

                            //return RedirectToLocal(returnUrl);
                        }
                    }
                    AddErrors(result);
                }

                ViewBag.ReturnUrl = returnUrl;
                return(View(model));
            }
        }
Ejemplo n.º 54
0
        protected override void Seed(ApplicationDbContext context)
        {
            var             roleStore   = new RoleStore <IdentityRole>(context);
            var             roleManager = new RoleManager <IdentityRole>(roleStore);
            var             userStore   = new UserStore <ApplicationUser>(context);
            var             userManager = new UserManager <ApplicationUser>(userStore);
            ApplicationUser user;

            if (!context.Roles.Any(u => u.Name == "Student"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Student"
                });
            }
            if (!context.Roles.Any(u => u.Name == "Leraar"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Leraar"
                });
            }
            if (!context.Roles.Any(u => u.Name == "Admin"))
            {
                roleManager.Create(new IdentityRole {
                    Name = "Admin"
                });
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Admin0");
                userManager.AddToRole(user.Id, "Admin");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar1");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar2");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Leraar3");
                userManager.AddToRole(user.Id, "Leraar");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student1");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student2");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student3");
                userManager.AddToRole(user.Id, "Student");
            }
            if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            {
                user = new ApplicationUser {
                    UserName = "******"
                };
                userManager.Create(user, "Student4");
                userManager.AddToRole(user.Id, "Student");
            }


            //if (!context.Users.Any(u => u.UserName == "*****@*****.**"))
            //{
            //    var userStore = new UserStore<ApplicationUser>(context);
            //    var userManager = new UserManager<ApplicationUser>(userStore);

            //    var roleStore = new RoleStore<IdentityRole>(context);
            //    var rolemanager = new RoleManager<IdentityRole>(roleStore);

            //    var user = new ApplicationUser { UserName = "******" };
            //    userManager.Create(user, "appelmoes");

            //    var role = new IdentityRole { Name= "Management" };
            //    rolemanager.Create(role);

            //    userManager.AddToRole(user.Id, "Management");
            //}


            //var hasher = new PasswordHasher();
            //context.Users.AddOrUpdate(u => u.UserName,
            //    new ApplicationUser { UserName = "******", PasswordHash = hasher.HashPassword("appelmoes") });


            //  This method will be called after migrating to the latest version.

            //  You can use the DbSet<T>.AddOrUpdate() helper extension method
            //  to avoid creating duplicate seed data. E.g.
            //
            //    context.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //
        }
Ejemplo n.º 55
0
        public static UsuarioManager Create()
        {
            var userStore = new UserStore <Usuario>(new BlogContext());

            return(new UsuarioManager(userStore));
        }
Ejemplo n.º 56
0
        public AdminController()
        {
            var userStore = new UserStore <ApplicationUser>(new IdentityDataContext());

            userManager = new UserManager <ApplicationUser>(userStore);
        }
        private async Task <IHttpActionResult> Register2(AccountRegistrationRequest accountRegistrationRequest, DateTime?registrationDate, bool dummy = false)
        {
            if (accountRegistrationRequest != null)
            {
                if (ModelState.IsValid || IsUserAuthenticated)
                {
                    ApplicationDbContext context = ApplicationDbContext.Create();

                    UserStore <ApplicationUser> userStore = new UserStore <ApplicationUser>(context);

                    ApplicationUserManager userManager = new ApplicationUserManager(userStore);

                    string password = accountRegistrationRequest.Password;

                    string[] addressParts =
                    {
                        accountRegistrationRequest.AddressLine1,
                        accountRegistrationRequest.AddressLine2,
                        accountRegistrationRequest.TownCity
                    };

                    string address = string.Join(",\r\n",
                                                 addressParts.Where(part => !string.IsNullOrWhiteSpace(part)));

                    ApplicationUser newApplicationUser = new ApplicationUser();


                    if (IsUserAuthenticated)
                    {
                        newApplicationUser = await userStore.FindByIdAsync(this.UserId);
                    }


                    if (accountRegistrationRequest.FirstName != null)
                    {
                        newApplicationUser.FirstName = accountRegistrationRequest.FirstName;
                    }
                    if (accountRegistrationRequest.LastName != null)
                    {
                        newApplicationUser.LastName = accountRegistrationRequest.LastName;
                    }

                    newApplicationUser.Address = address;

                    if (accountRegistrationRequest.Postcode != null)
                    {
                        newApplicationUser.Postcode = accountRegistrationRequest.Postcode;
                    }

                    if (accountRegistrationRequest.EmailAddress != null)
                    {
                        newApplicationUser.Email = accountRegistrationRequest.EmailAddress;
                    }

                    if (!IsUserAuthenticated)
                    {
                        if (accountRegistrationRequest.EmailAddress != null)
                        {
                            newApplicationUser.UserName = accountRegistrationRequest.EmailAddress;
                        }
                    }

                    if (accountRegistrationRequest.DateOfBirth != default(DateTime))
                    {
                        newApplicationUser.DateOfBirth = accountRegistrationRequest.DateOfBirth;
                    }



                    if (accountRegistrationRequest.Gender != null)
                    {
                        if (accountRegistrationRequest.Gender.Contains("female"))
                        {
                            newApplicationUser.Gender = Gender.Female;
                        }
                    }


                    if (registrationDate != null)
                    {
                        newApplicationUser.RegistrationDate = registrationDate.Value;
                    }
                    else
                    {
                        newApplicationUser.RegistrationDate = DateTime.Now;
                    }

                    if (accountRegistrationRequest.MobileNumber != null)
                    {
                        newApplicationUser.PhoneNumber = accountRegistrationRequest.MobileNumber;
                    }

                    if (accountRegistrationRequest.Postcode != null)
                    {
                        newApplicationUser.Location = PostcodesService.Lookup(newApplicationUser.Postcode);
                    }


                    if (IsUserAuthenticated)
                    {
                        var result2 = await userManager.UpdateAsync(newApplicationUser);

                        if (result2.Succeeded)
                        {
                            return(Ok());
                        }

                        return(BadRequest(string.Join(", ", result2.Errors)));
                    }


                    var result = await userManager.CreateAsync(newApplicationUser, password);

                    if (result.Succeeded)
                    {
                        return(Ok());
                    }

                    return(BadRequest(string.Join(", ", result.Errors)));
                }

                string validationErrors = string.Join(",",
                                                      ModelState.Values.Where(E => E.Errors.Count > 0)
                                                      .SelectMany(E => E.Errors)
                                                      .Select(E => E.ErrorMessage)
                                                      .ToArray());

                return(BadRequest(validationErrors));
            }

            return(BadRequest("registration data is null."));
        }
Ejemplo n.º 58
0
 /// <summary> Exist one or more users in specified role? </summary>
 public override bool HasUsersInRole(string roleName)
 {
     return(UserStore.HasUsersInRole(roleName));
 }
Ejemplo n.º 59
0
        public IdentityResult AdicionarIdentidade(RegisterViewModel register)
        {
            var store = new UserStore <ApplicationUser>(new ApplicationDbContext())
            {
                AutoSaveChanges = false
            };
            var manager = _userManager;

            var user = new ApplicationUser {
                UserName = register.Login, Email = register.Email
            };
            var result = manager.Create(user, register.Password);

            if (result.Succeeded)
            {
                if (usuario == null)
                {
                    var agencia = RegisterAdapter.ToDomainModel(register);
                    AdicionarAgencia(agencia);
                    var endereco = EnderecoAdapter.ToDomainModel(register);
                    AdicionarEndereco(endereco);
                    var agenciausuario = AgenciaUsuarioAdapter.ToDomainModel(register, user.Id);
                    AdicionarUsuario(agenciausuario);

                    if (Commit())
                    {
                    }
                    else
                    {
                        manager.Delete(user);
                        return(new IdentityResult(Notifications.ToString()));
                    }
                }
                else
                {
                    var agenciausuario = AgenciaUsuarioAdapter.ToDomainModel(register, user.Id);
                    AdicionarUsuario(agenciausuario);
                    AdicionarPermissao(user, register);

                    if (Commit())
                    {
                        DomainEvent.Raise(new AgenciaUsuarioEvent(Guid.Parse(usuario), nomeusuario, agenciausuario.UsuarioId, agenciausuario.Nome, agenciausuario.CPF.Codigo, register.Permissao, "CADASTRAR"));
                    }
                    else
                    {
                        manager.Delete(user);
                        return(new IdentityResult(Notifications.ToString()));
                    }
                }
            }
            else
            {
                var errosBr          = new List <string>();
                var notificationList = new List <DomainNotification>();

                foreach (var erro in result.Errors)
                {
                    string erroBr;
                    if (erro.Contains("As senhas devem ter pelo menos um dígito ('0'-'9')."))
                    {
                        erroBr = "A senha precisa ter ao menos um dígito";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }
                    if (erro.Contains("As senhas devem ter pelo menos um caractere que não seja letra ou um caractere de dígito."))
                    {
                        erroBr = "A senha precisa ter ao menos um caractere especial (@, #, etc...)";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }
                    if (erro.Contains("As senhas devem ter pelo menos um caractere em letra minúscula ('a'-'z')."))
                    {
                        erroBr = "A senha precisa ter ao menos uma letra em minúsculo";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }
                    if (erro.Contains("As senhas devem ter pelo menos um caractere em letra maiúscula ('A'-'Z')."))
                    {
                        erroBr = "A senha precisa ter ao menos uma letra em maiúsculo";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }
                    if (erro.Contains("O nome " + register.Login + " já foi escolhido."))
                    {
                        erroBr = "Login já registrado, esqueceu sua senha?";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }

                    if (erro.Contains("Name " + register.Email + " is already taken"))
                    {
                        erroBr = "E-mail já registrado, esqueceu sua senha?";
                        notificationList.Add(new DomainNotification("IdentityValidation", erroBr));
                        errosBr.Add(erroBr);
                    }
                }
                notificationList.ForEach(DomainEvent.Raise);
                result = new IdentityResult(errosBr);
            }

            return(result);
        }
Ejemplo n.º 60
-1
        static Startup()
        {
            PublicClientId = "self";

            UserManagerFactory = () =>
            {
                var context = new IdentityDbContext();
                System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer());

                var userStore = new UserStore<IdentityUser>(context);
                userStore.DisposeContext = true;

                return new UserManager<IdentityUser>(userStore);
            };

            RoleManagerFactory = () =>
            {
                var context = new IdentityDbContext();
                System.Data.Entity.Database.SetInitializer<IdentityDbContext>(new IdentityDbInitializer());

                var roleStore = new RoleStore<IdentityRole>(context);

                return new RoleManager<IdentityRole>(roleStore);
            };

            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId, UserManagerFactory),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp = true
            };
        }