Exemplo n.º 1
0
        public async Task <IdentityResult> UpdateUser(UserModel userModel)
        {
            IdentityResult result = null;
            // update Users table
            var userList   = _ctx.Users.Where(u => u.UserName == userModel.UserName);
            var userUpdate = userList.FirstOrDefault();

            if (userUpdate != null)
            {
                userUpdate.EmployeeC = userModel.EmployeeC;
                userUpdate.DriverC   = userModel.DriverC;
                if (userUpdate.IsActive != userModel.IsActive)
                {
                    _userManager.UpdateSecurityStamp(userUpdate.Id);
                }
                userUpdate.IsActive = userModel.IsActive;

                result = await _userManager.UpdateAsync(userUpdate);

                var userRoles = await _userManager.GetRolesAsync(userUpdate.Id);

                if (userRoles.Count > 0)
                {
                    await _userManager.RemoveFromRoleAsync(userUpdate.Id, userRoles[0]);

                    await _userManager.AddToRoleAsync(userUpdate.Id, userModel.RoleName);
                }
                else
                {
                    await _userManager.AddToRoleAsync(userUpdate.Id, userModel.RoleName);
                }
            }

            return(result);
        }
Exemplo n.º 2
0
        public JsonResult Ativacao(string id)
        {
            var model = _UserAppSvc.GetById(id);

            if (model == null)
            {
                throw new HttpException(404, "Item não encontrado");
            }



            //verifica se o usuário é superadmin, se for vai retornar uma PUTA EXCEPTION
            if (UserManager.IsInRole(id, "Superadmin"))
            {
                throw new Exception("VOCÊ NÃO PODE DESATIVAR O USUARIO SUPERADMIN!");
            }



            //entidade
            model.Ativo = !model.Ativo;
            _UserAppSvc.Update(model);

            ApplicationUser usuario = UserManager.FindById(id);

            UserManager.UpdateSecurityStamp(usuario.Id);



            return(Json("OK"));
        }
Exemplo n.º 3
0
        public void UpdateUser(ApplicationUser user, string role)
        {
            var oldUser = _userManager.FindById(user.Id);

            if (oldUser == null)
            {
                return;
            }

            var oldRoleId   = oldUser.Roles.SingleOrDefault()?.RoleId;
            var oldRoleName = _roleManager.Roles.SingleOrDefault(r => r.Id == oldRoleId)?.Name;

            if (oldRoleName != null && oldRoleName != role)
            {
                _userManager.RemoveFromRole(user.Id, oldRoleName);
                _userManager.AddToRole(user.Id, role);
            }

            if (string.IsNullOrEmpty(user.PasswordHash))
            {
                return;
            }

            oldUser.PasswordHash = user.PasswordHash;
            oldUser.Email        = user.Email;
            oldUser.UserName     = user.Email;

            _userManager.Update(oldUser);
            _userManager.UpdateSecurityStamp(user.Id);
        }
Exemplo n.º 4
0
        private void seedRoles(Graphics4Teachers.Models.ApplicationDbContext context)
        {
            IdentityResult ir;
            var            rm = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            ir = rm.Create(new IdentityRole("admin"));
            var um   = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            var user = context.Users.Find("165bd383-73a4-450c-9365-a94f362660d8");

            ir = um.AddToRole(user.Id, "admin");
            um.UpdateSecurityStamp("165bd383-73a4-450c-9365-a94f362660d8");
            um.UpdateSecurityStamp("a59aae1c-db79-4dcb-9872-15d1c390b609");
        }
Exemplo n.º 5
0
        protected override void Seed(ApplicationDbContext context)
        {
            var    passwordHash = new PasswordHasher();
            string password     = passwordHash.HashPassword("Password@123");
            var    userManager  = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            context.Users.AddOrUpdate(u => u.UserName,
                                      new ApplicationUser
            {
                Id           = "1",
                UserName     = "******",
                PasswordHash = password,
                Email        = "*****@*****.**",
            });
            userManager.UpdateSecurityStamp("1");
            var RoleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            if (!context.Roles.Any(r => r.Name == "MasterAdmin"))
            {
                var role = new IdentityRole {
                    Name = "MasterAdmin"
                };
                RoleManager.Create(role);
            }
            context.SaveChanges();

            userManager.AddToRole("1", "MasterAdmin");

            password = passwordHash.HashPassword("Password@1234");
            context.Users.AddOrUpdate(u => u.UserName,
                                      new ApplicationUser
            {
                Id           = "2",
                UserName     = "******",
                PasswordHash = password,
                Email        = "*****@*****.**",
            });
            userManager.UpdateSecurityStamp("2");
            password = passwordHash.HashPassword("Password@12345");
            context.Users.AddOrUpdate(u => u.UserName,
                                      new ApplicationUser
            {
                Id           = "3",
                UserName     = "******",
                PasswordHash = password,
                Email        = "*****@*****.**",
            });
            userManager.UpdateSecurityStamp("3");
        }
Exemplo n.º 6
0
        public async Task <User> FindUser(string userName, string password)
        {
            //Phat Nguyen - 14/05/2015
            //Every connection is using singleton design pattern, so when we find one user, the user is cached in this
            //dbcontext. When we change this user from another connection, and get back to previous connection, the user with data changed
            //is not apply
            //Solutio: create new DBcontext everytime we need to get all user information.
            var context = new SGTSVNDBContext();

            using (var userManager = new UserManager <User>(new UserStore <User>(context)))
            {
                var user = await userManager.FindAsync(userName, password);

                //var userId = _userManager.FindByName(userName).Id;
                if (user != null && user.IsActive == "1")
                {
                    if (user.IsLoggedIn != "1")
                    {
                        user.IsLoggedIn = "1";
                        userManager.Update(user);
                    }

                    userManager.UpdateSecurityStamp(user.Id);
                }

                return(user);
            }
        }
Exemplo n.º 7
0
        public static void SeedUsers(HeroicallyRecipesDbContext context)
        {
            if (context.Users.Count() > 1)
            {
                return;
            }

            string[] usernames = new string[] { "jhonDoe", "batman" };
            string[] passwords = new string[] { "jhonDoe123", "batman123" };
            string[] emails = new string[] { "*****@*****.**", "*****@*****.**" };

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

            for (int i = 0; i < usernames.Length; i++)
            {
                var user = new User
                {
                    UserName = emails[i],
                    Email = emails[i],
                    NickName = emails[i],
                    PasswordHash = hasher.HashPassword(passwords[i]),
                    AvatarUrl = "/images/defaultAvatar1.png"
                };

                context.Users.Add(user);
                context.SaveChanges();
                userManager.UpdateSecurityStamp(user.Id);
            }
        }
Exemplo n.º 8
0
        public async Task <ActionResult> SignOutEverywhere()
        {
            UserManager.UpdateSecurityStamp(User.Identity.GetUserId());
            await SignOutAsync();

            return(RedirectToAction("Index", "Home"));
        }
Exemplo n.º 9
0
        public static void SeedUsers(HeroicallyRecipesDbContext context)
        {
            if (context.Users.Count() > 1)
            {
                return;
            }

            string[] usernames = new string[] { "jhonDoe", "batman" };
            string[] passwords = new string[] { "jhonDoe123", "batman123" };
            string[] emails    = new string[] { "*****@*****.**", "*****@*****.**" };

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

            for (int i = 0; i < usernames.Length; i++)
            {
                var user = new User
                {
                    UserName     = emails[i],
                    Email        = emails[i],
                    NickName     = emails[i],
                    PasswordHash = hasher.HashPassword(passwords[i]),
                    AvatarUrl    = "/images/defaultAvatar1.png"
                };

                context.Users.Add(user);
                context.SaveChanges();
                userManager.UpdateSecurityStamp(user.Id);
            }
        }
Exemplo n.º 10
0
        private void ChangePassword(string userId, string newPassword)
        {
            var user = _userManager.FindById(userId);

            user.PasswordHash = _userManager.PasswordHasher.HashPassword(newPassword);
            PasswordVerificationResult passwordVerificationResult = new PasswordVerificationResult();

            passwordVerificationResult = _userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, newPassword);

            _userManager.UpdateSecurityStamp(userId);

            IdentityResult v = _userManager.Update(user);
        }
Exemplo n.º 11
0
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, int> manager)
        {
            // N2 backward compatibility: generate security stamp when undefined yet
            if (string.IsNullOrEmpty(this.SecurityStamp))
            {
                manager.UpdateSecurityStamp(this.Id);
                this.SecurityStamp = manager.FindById(this.Id).SecurityStamp;
            }

            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            // See also: http://forums.asp.net/t/1973959.aspx?ASP+NET+MVC+5+OWIN+Missing+added+claims
            return userIdentity;
        }
Exemplo n.º 12
0
        public async Task <ClaimsIdentity> GenerateUserIdentityAsync(UserManager <ApplicationUser, int> manager)
        {
            // N2 backward compatibility: generate security stamp when undefined yet
            if (string.IsNullOrEmpty(this.SecurityStamp))
            {
                manager.UpdateSecurityStamp(this.Id);
                this.SecurityStamp = manager.FindById(this.Id).SecurityStamp;
            }

            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);

            // Add custom user claims here
            // See also: http://forums.asp.net/t/1973959.aspx?ASP+NET+MVC+5+OWIN+Missing+added+claims
            return(userIdentity);
        }
Exemplo n.º 13
0
        protected override void Seed(TCC.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.

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

            context.Users.AddOrUpdate(
                x => x.Email,  //Using Email as the Unique Key: If a record exists with the same email, AddOrUpdate skips it.
                new ApplicationUser()
            {
                Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("P@ssw0rd")
            }
                );

            context.Roles.AddOrUpdate(
                new IdentityRole()
            {
                Id = "Administrador", Name = "Administrador"
            },
                new IdentityRole()
            {
                Id = "Usuário", Name = "Usuário"
            }
                );

            context.SaveChanges();

            var user = userManager.FindByName("Administrador");

            userManager.AddToRole(user.Id, "Administrador");

            context.SaveChanges();

            //Get the UserId only if the SecurityStamp is not set yet.
            string userId = context.Users.Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

            //If the userId is not null, then the SecurityStamp needs updating.
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }
        }
Exemplo n.º 14
0
        public ActionResult DeleteUserFromRole(string UserName, string RoleName)
        {
            var             store   = new UserStore <ApplicationUser>(context);
            var             manager = new UserManager <ApplicationUser>(store);
            ApplicationUser user    = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (manager.IsInRole(user.Id, RoleName))
            {
                manager.RemoveFromRole(user.Id, RoleName);
                manager.UpdateSecurityStamp(user.Id);
                ViewBag.ResultMessage = "Role removed for this user.";
            }
            else
            {
                ViewBag.ResultMessage = "This user doesn't belong to selected role.";
            }

            PopulateUsersAndRoles();

            return(View("ManageUserRoles"));
        }
Exemplo n.º 15
0
        public ActionResult AddRoleToUser(string UserName, string RoleName)
        {
            var             store   = new UserStore <ApplicationUser>(context);
            var             manager = new UserManager <ApplicationUser>(store);
            ApplicationUser user    = context.Users.Where(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();

            if (!manager.IsInRole(user.Id, RoleName))
            {
                manager.AddToRole(user.Id, RoleName);
                manager.UpdateSecurityStamp(user.Id);
                ViewBag.ResultMessage = "Role added successfully.";
            }
            else
            {
                ViewBag.ResultMessage = "User already in this role.";
            }

            PopulateUsersAndRoles();

            return(View("ManageUserRoles"));
        }
Exemplo n.º 16
0
        private void ChangePassword(string userId, string newPassword)
        {
            var user = _userManager.FindById(userId);

            user.PasswordHash = _userManager.PasswordHasher.HashPassword(newPassword);
            PasswordVerificationResult passwordVerificationResult = new PasswordVerificationResult();

            passwordVerificationResult = _userManager.PasswordHasher.VerifyHashedPassword(user.PasswordHash, newPassword);

            _userManager.UpdateSecurityStamp(userId);

            IdentityResult v = _userManager.Update(user);
            //if (v.Succeeded) {
            //    //success
            //}
            //else {
            //    //failure. Perhaps Loop through v.Errors to find out why.
            //    //Though, the documentation doesn't provide any hints as to what possible values
            //    //v.Errors may contain (it's an IEnumerable)
            //}
        }
Exemplo n.º 17
0
        protected override void Seed(ApplicationDbContext context)
        {
            const string AdministratorUserName = "******";
            const string AdministratorPassword = AdministratorUserName;
            const string SampleUserName        = "******";
            const string SampleUserPassword    = "******";
            const string SampleIpAddress       = "172.16.254.1";

            string[] ideaTitles = new string[]
            {
                "XNA 5",
                "Allow .NET games on Xbox One",
                "Support web.config style Transforms on any file in any project type",
                "Bring back Macros",
                "Open source Silverlight",
                "Native DirectX 11 support for WPF",
                "Make WPF open-source and accept pull-requests from the community",
                "Fix 260 character file name length limitation",
                "Support for ES6 modules",
                "Create a \"remove all remnants of Visual Studio from your system\" program.",
                "Support .NET Builds without requiring Visual Studio on the server",
                "VS IDE should support file patterns in project files",
                "Improve WPF performance",
                "T4 editing",
                "Visual Studio for Mac Os x"
            };

            string[] ideaDescriptions = new string[]
            {
                "Please continue to work on XNA. It's a great way for indie game developers like myself to make games and give them to the world. XNA gave us the ability to put our games, easily, on the most popular platforms, and to just dump XNA would be therefor heartbreaking... I implore you to keep working on XNA so we C# developers can still make amazing games!",
                "Yesterday was announced that Xbox One will allow indie developer to easily publish games on Xbox One." + System.Environment.NewLine + "Lots of indie developers and small game company are using .NET to develop games.Today, we are able to easily target several Windows platforms(Windows Desktop, Windows RT and Windows Phone 8) as well as other platforms thanks to Mono from Xamarin." + System.Environment.NewLine + "As we don't know yet the details about this indie developer program for Xbox One, we would love to use .NET on this platform - with everything accessible, from latest 4.5 with async, to unsafe code and native code access through DLLImport (and not only through WinRT components)" + System.Environment.NewLine + "Please make .NET a compelling game development alternative on Xbox One!",
                "Web.config Transforms offer a great way to handle environment-specific settings. XML and other files frequently warrant similar changes when building for development(Debug), SIT, UAT, and production(Release).It is easy to create additional build configurations to support multiple environments via transforms.Unfortunately, not everything can be handled in web.config files many settings need to be changed in xml or other \"config\" files." + System.Environment.NewLine + "Also, this functionality is needed in other project types - most notably SharePoint 2010 projects.",
                "I am amazed you've decided to remove Macros from Visual Studio. Not only are they useful for general programming, but they're a great way to be introduced to the Visual Studio APIs." + System.Environment.NewLine + "If you are unwilling to put in the development time towards them, please release the source code and let the community maintain it as an extension.",
                "For all intents and purposes Microsoft now views Silverlight as “Done”. While it is no longer in active development it is still being “supported” through to 2021 (source)." + System.Environment.NewLine + "However there is still a section of the .Net community that would like to see further development done on the Silverlight framework. A quick look at some common request lists brings up the following stats:",
                "in 2013 WPF still work on DX9, and this have a lot of inconvenience. First of all it is almost impossible to make interaction with native DX11 C++ and WPF. Axisting D3DImage class support only DX 9, but not higher and for now it is a lot of pain to attach DX 11 engine to WPF." + System.Environment.NewLine + "Please, make nativa support for DX 11 in WOF by default and update D3DImage class to have possibility to work with nativa C++ DX 11 engine and make render directly to WPF control(controls) without pain with C++ dll.",
                "Please follow the footsteps of the ASP .NET team and make WPF open-source with the source code on GitHub, and accept pull-requests from the community.",
                "Same description as here: http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2156195-fix-260-character-file-name-length-limitation",
                "Add support for the new JavaScript ES6 module syntax, including module definition and imports.",
                "I'm writing this on behalf of the thousands of other Visual Studio users out there who have had nightmares trying to uninstall previous versions of VS. Thus cumulatively losing hundreds of thousands of productive work hours." + System.Environment.NewLine + "During this year, I had installed the following programs/components on my system:" + System.Environment.NewLine + "*Visual Studio 2012 Express for Desktop" + System.Environment.NewLine + "* Visual Studio 2012 Express for Web" + System.Environment.NewLine + "* Team Foundation Server Express" + System.Environment.NewLine + "* SQL Server Express" + System.Environment.NewLine + "* SQL Server Data Tools" + System.Environment.NewLine + "* LightSwitch 2011 trial(which created a VS 2010 installation)" + System.Environment.NewLine + "* Visual Studio 2010 Tools for SQL Server Compact 3.5 SP2" + System.Environment.NewLine + "* Entity Framework Designer for Visual Studio 2012" + System.Environment.NewLine + "* Visual Studio Tools for Applications" + System.Environment.NewLine + "* Visual Studio Tools for Office" + System.Environment.NewLine + "* F# Tools for Visual Studio Express 2012 for Web" + System.Environment.NewLine + "Two weeks ago I discovered that third - party controls can't be added to the Express versions of VS. I'm disabled and live on a fixed income, so spending $500 for the Professional version, in order to continue my hobby programming with a third-party control, was a tough decision. But I bought it." + System.Environment.NewLine + "When it arrived, I figured it would take an hour or two to remove the above programs and then I could install the Pro version. I wanted to have a clean file system and Registry for the new install of VS Pro." + System.Environment.NewLine + "It's now SIX DAYS later, and my spending 12-14 hours a day working on this alone. Removing these programs was the biggest nightmare I have ever faced with Microsoft products in my 30 years of being a Microsoft customer. Each one of these products automatically installed 5, 10 or more additional components, along with many thousands of files and individual Registry entries." + System.Environment.NewLine + "It took me four days alone, just to successfully remove the LightSwitch 2011 trial, and the entire VS 2010 product it installed.Restoring a 600 GB disk drive(5 hours) from backup after every removal attempt failed miserably.I finally gave up, spent 6 hours downloading the entire VS 2010 ISO and installed it. Only then, was I able to successfully uninstall LightSwitch 2011 and VS 2010." + System.Environment.NewLine + "As for the remaining products listed above, the uninstall programs do NOT UNinstall everything that they automatically INstall. Every single, automatically INstalled component, had to be removed manually, one at a time.Along with manually creating a System Restore point before each removal attempt, in case it failed. In total, I spent 12 hours uninstalling the remaining products." + System.Environment.NewLine + "I have a Registry search program where I can enter a search string and it will list ALL occurrences it finds in the Registry. I checked \"visual studio\", \"visualstudio\", \"vbexpress\", \"vcexpress\", \"SQL Server\", etc.I never finished searching for all the possible Visual Studio and SQL Server strings because the results being returned were eye - popping.Each search was returning 1, 000, 3, 000, even 7, 000 individual Registry entries that had NOT been removed by the individual uninstall processes.This is TENS of THOUSANDS of never to be used again Registry entries that these programs simply left behind.The size of my Registry file is now a stunning 691 MB!" + System.Environment.NewLine + "All of this frustration and wasted time is completely avoidable!And my case is not \"isolated\".There are hundreds of thousands of hits on Google regarding this problem, that point to Microsoft forums, MS Blog sites, and many independent Windows developer support forums on the web." + System.Environment.NewLine + "Microsoft really should provide an uninstall program that actually works, by UNinstalling everything it INstalls-- for each product it sells-- including Visual Studio.The downloadable(from Microsoft) uninstall program for VS 2010 does not work correctly and does not remove everything that VS 2010 installs." + System.Environment.NewLine + "When a program installs multiple individual components, tens of thousands of files and Registry entries, it SHOULD have an uninstaller that removes ALL of this, automatically, just like the install program.The OS and Registry keep track of dependencies and you folks know what the removal order should be for all of these products.So the team that creates the INstall program for each product, should also create the UNinstall program.And, the product should NOT ship until this program works correctly and fully." + System.Environment.NewLine + "You have ONE install program for each version of Visual Studio, that asks the user what they want to install and then does it ALL automatically.You should also have ONE uninstall program that does the same thing in reverse..." + System.Environment.NewLine + "* Collect info on all the VS - related products and components currently installed" + System.Environment.NewLine + "* Ask the user what they want to remove" + System.Environment.NewLine + "* Determine if their selections make sense" + System.Environment.NewLine + "* Check for dependencies by using your knowledge and experience, along with the computer's stored information, and warn the user as needed" + System.Environment.NewLine + "* Decide on the removal order" + System.Environment.NewLine + "*Then do it ALL automatically-- removing ALL files and ALL Registry entries" + System.Environment.NewLine + "When you release a new product version, ADD the new version and additional decision logic to this existing program, do NOT create a new uninstall program.This way, the user can also remove previous version products, components, etc.ONE uninstall program* should be* able to uninstall every version of Visual Studio released in the past 10 years, along with every single component that was available with it, AND all of the associated files and Registry entries." + System.Environment.NewLine + "Please don't tell us why it CAN'T be done.Rather, figure out a way to do it, and then make it happen, just like every other software company out there has already done for their products. Even FREEware providers have better uninstall processes than Microsoft.This is a sad state for Microsoft and it should be rectified SOON." + System.Environment.NewLine + "Thank you.",
                "To build certain PCL libraries and libraries for Windows 8 RT requires having Visual Studio on the server." + System.Environment.NewLine + "Nick Berardi writes about a workaround that allows running a build server without VS, but it's really just a workaround for functionality that should be easy." + System.Environment.NewLine + "Not to mention there's probably licensing considerations we're just ignoring by doing that." + System.Environment.NewLine + "http://nickberardi.com/a-net-build-server-without-visual-studio/" + System.Environment.NewLine + "Please make it easy(and legal) to build.NET projects on a server without requiring a Visual Studio installation(or license) on that server.",
                "Patterns should be preserved and unmodified when working with *proj files. If I specify a pattern with something like **/*.cs for my code files. If I add a new .cs file that fits that pattern the .csproj file should not be modified." + System.Environment.NewLine + "MSBuild already respects this, but the IDE will always modify the project file." + System.Environment.NewLine + "For numerous scenarios this could simplify the diff / merge process.",
                "I have a high end PC and still WPF is not always fluent. Just compare it with QT 4.6 QML (Declarative UI) it is sooo FAST!",
                "T4 is no longer just a tool used internally by VS, but is being increasingly used by developers for code generation. It would be great to have syntax highlighting, intellisense etc. out of the box." + System.Environment.NewLine + "I appreciate this is probably more of a Visual Studio feature request than an ASP.NET one, but as T4 is used a lot within ASP.NET projects, particularly MVC ones, I figure it's worth a mention.",
                "Dear Madam and sir;" + System.Environment.NewLine + "We need Full Version of Visual Studio for Mac Os x." + System.Environment.NewLine + "And language of programming such as:" + System.Environment.NewLine + "-C" + System.Environment.NewLine + "- C++" + System.Environment.NewLine + "- C#" + System.Environment.NewLine + "- VB" + System.Environment.NewLine + "- F#" + System.Environment.NewLine + "- HTML" + System.Environment.NewLine + "- MHTML" + System.Environment.NewLine + "Thanks,"
            };

            if (!context.Roles.Any())
            {
                // Create admin & user roles
                var roleStore   = new RoleStore <IdentityRole>(context);
                var roleManager = new RoleManager <IdentityRole>(roleStore);
                var adminRole   = new IdentityRole {
                    Name = GlobalConstants.AdministratorRoleName
                };
                roleManager.Create(adminRole);

                // Create admin user
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new UserManager <ApplicationUser>(userStore);
                var admin       = new ApplicationUser {
                    UserName = AdministratorUserName, Email = AdministratorUserName
                };
                userManager.Create(admin, AdministratorPassword);

                // Assign user to admin role
                userManager.AddToRole(admin.Id, GlobalConstants.AdministratorRoleName);

                // Create simple user
                var    passwordHash = new PasswordHasher();
                string password     = passwordHash.HashPassword(SampleUserPassword);
                context.Users.AddOrUpdate(
                    u => u.UserName,
                    new ApplicationUser {
                    UserName = SampleUserName, PasswordHash = password, Email = SampleUserName
                });
                context.SaveChanges();

                string userId = context.Users.Where(x => x.Email == SampleUserName && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

                // If the userId is not null, then the SecurityStamp needs updating.
                if (!string.IsNullOrEmpty(userId))
                {
                    userManager.UpdateSecurityStamp(userId);
                }

                context.SaveChanges();

                // Add sample ideas
                for (int i = 0; i < 15; i++)
                {
                    Idea newIdea = new Idea()
                    {
                        Title       = ideaTitles[i],
                        Description = ideaDescriptions[i],
                        AuthorIp    = SampleIpAddress
                    };

                    context.Ideas.Add(newIdea);
                    context.SaveChanges();
                }

                // Add sample comments
                for (int i = 1; i <= 15; i++)
                {
                    for (int j = 1; j <= 10; j++)
                    {
                        var newComment = new Comment()
                        {
                            IdeaId  = i,
                            Content = "Sample content for comment " + j,
                            Email   = "*****@*****.**"
                        };

                        context.Comments.Add(newComment);
                    }

                    context.SaveChanges();
                }

                // Add sample votes
                for (int i = 1; i <= 15; i++)
                {
                    for (int j = 1; j <= 101; j++)
                    {
                        var newVote = new Vote()
                        {
                            IdeaId     = i,
                            AuthorIp   = RandomGenerator.GetRandomIp(),
                            VotePoints = RandomGenerator.GetRandomVotePoints()
                        };

                        context.Votes.Add(newVote);

                        if (j % 10 == 0)
                        {
                            context.SaveChanges();
                        }
                    }

                    context.SaveChanges();
                }
            }
        }
Exemplo n.º 18
0
        protected override void Seed(ParrotWIngs.Models.ApplicationDbContext context)
        {
            UserStore <ApplicationUser>   userStore   = new UserStore <ApplicationUser>(context);
            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(userStore);

            //  This method will be called after migrating to the latest version.
            context.Users.AddOrUpdate(x => x.Email,
                                      new ApplicationUser()
            {
                PwName = "Robert Jordan", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("T3stPa$$w0rd")
            },
                                      new ApplicationUser()
            {
                PwName = "Jose Miaja", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("T3stPa$$w0rd")
            },
                                      new ApplicationUser()
            {
                PwName = "Ivan Kashkin", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("T3stPa$$w0rd")
            },
                                      new ApplicationUser()
            {
                PwName = "Mihail Koltsov", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("T3stPa$$w0rd")
            },
                                      new ApplicationUser()
            {
                PwName = "Andre Marty", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("T3stPa$$w0rd")
            }
                                      );
            context.SaveChanges();

            foreach (var dbUser in context.Users.ToArray())
            {
                switch (dbUser.Email)
                {
                case "*****@*****.**":
                    context.UserAccounts.AddOrUpdate(x => x.UserId, new UserAccount()
                    {
                        UserId = dbUser.Id, Balance = 400
                    });
                    break;

                case "*****@*****.**":
                    context.UserAccounts.AddOrUpdate(x => x.UserId, new UserAccount()
                    {
                        UserId = dbUser.Id, Balance = 550
                    });
                    break;

                case "*****@*****.**":
                    context.UserAccounts.AddOrUpdate(x => x.UserId, new UserAccount()
                    {
                        UserId = dbUser.Id, Balance = 550
                    });
                    break;

                case "*****@*****.**":
                    context.UserAccounts.AddOrUpdate(x => x.UserId, new UserAccount()
                    {
                        UserId = dbUser.Id, Balance = 550
                    });
                    break;

                case "*****@*****.**":
                    context.UserAccounts.AddOrUpdate(x => x.UserId, new UserAccount()
                    {
                        UserId = dbUser.Id, Balance = 450
                    });
                    break;
                }

                if (string.IsNullOrEmpty(dbUser.SecurityStamp))
                {
                    userManager.UpdateSecurityStamp(dbUser.Id);
                }
            }

            //Reseed "Transactions" table
            context.Database.ExecuteSqlCommand("TRUNCATE TABLE dbo.Transactions");
            context.Database.ExecuteSqlCommand("DBCC CHECKIDENT('dbo.Transactions',RESEED,1)");

            string payeeId     = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();
            string recipientId = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();

            context.Transactions.AddOrUpdate(x => x.Id,
                                             new Transaction()
            {
                Id = 1, PayeeId = payeeId, RecipientId = recipientId, Amount = 100, ResultingPayeeBalance = 400, ResultingRecipientBalance = 600, Date = DateTime.ParseExact("01012016", "ddMMyyyy", CultureInfo.InvariantCulture)
            }
                                             );

            payeeId     = recipientId;
            recipientId = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();
            context.Transactions.AddOrUpdate(x => x.Id,
                                             new Transaction()
            {
                Id = 2, PayeeId = payeeId, RecipientId = recipientId, Amount = 50, ResultingPayeeBalance = 550, ResultingRecipientBalance = 550, Date = DateTime.ParseExact("02012016", "ddMMyyyy", CultureInfo.InvariantCulture)
            }
                                             );

            payeeId     = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();
            recipientId = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();
            context.Transactions.AddOrUpdate(x => x.Id,
                                             new Transaction()
            {
                Id = 3, PayeeId = payeeId, RecipientId = recipientId, Amount = 50, ResultingPayeeBalance = 350, ResultingRecipientBalance = 550, Date = DateTime.ParseExact("03012016", "ddMMyyyy", CultureInfo.InvariantCulture)
            }
                                             );

            recipientId = payeeId;
            payeeId     = context.Users.Where(x => x.Email == "*****@*****.**").Select(x => x.Id).FirstOrDefault();
            context.Transactions.AddOrUpdate(x => x.Id,
                                             new Transaction()
            {
                Id = 4, PayeeId = payeeId, RecipientId = recipientId, Amount = 50, ResultingPayeeBalance = 450, ResultingRecipientBalance = 400, Date = DateTime.ParseExact("04012016", "ddMMyyyy", CultureInfo.InvariantCulture)
            }
                                             );
        }
Exemplo n.º 19
0
        protected override void Seed(ReclamaTche.Models.ApplicationDbContext context)
        {
            context.Roles.AddOrUpdate(r => r.Name,
                                      new IdentityRole
            {
                Name = "Administrador"
            }
                                      );
            context.Roles.AddOrUpdate(r => r.Name,
                                      new IdentityRole
            {
                Name = "Oficial"
            }
                                      );

            context.Roles.AddOrUpdate(r => r.Name,
                                      new IdentityRole
            {
                Name = "Básico"
            }
                                      );

            var hasher = new PasswordHasher();

            context.Users.AddOrUpdate(p => p.Email,
                                      new ApplicationUser
            {
                Email          = "*****@*****.**",
                UserName       = "******",
                PasswordHash   = hasher.HashPassword("Pass@word1"),
                LockoutEnabled = true,
            });
            context.Users.AddOrUpdate(p => p.Email,
                                      new ApplicationUser
            {
                Email          = "*****@*****.**",
                UserName       = "******",
                PasswordHash   = hasher.HashPassword("Pass@word1"),
                LockoutEnabled = true,
            });
            context.Users.AddOrUpdate(p => p.Email,
                                      new ApplicationUser
            {
                Email          = "*****@*****.**",
                UserName       = "******",
                PasswordHash   = hasher.HashPassword("Pass@word1"),
                LockoutEnabled = true,
            });

            context.Users.AddOrUpdate(p => p.Email,
                                      new ApplicationUser
            {
                Email          = "*****@*****.**",
                UserName       = "******",
                PasswordHash   = hasher.HashPassword("Pass@word1"),
                LockoutEnabled = true,
            });
            ApplicationUser user        = context.Users.Where(u => u.UserName.Equals("*****@*****.**", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            var             UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));

            UserManager.AddToRole(user.Id, "Administrador");
            UserManager.UpdateSecurityStamp(user.Id);
            user.LockoutEnabled = true;


            user        = context.Users.Where(u => u.UserName.Equals("*****@*****.**", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            UserManager.AddToRole(user.Id, "Administrador");
            UserManager.UpdateSecurityStamp(user.Id);
            user.LockoutEnabled = true;

            user        = context.Users.Where(u => u.UserName.Equals("*****@*****.**", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            UserManager.AddToRole(user.Id, "Oficial");
            UserManager.UpdateSecurityStamp(user.Id);
            user.LockoutEnabled = true;

            user        = context.Users.Where(u => u.UserName.Equals("*****@*****.**", StringComparison.CurrentCultureIgnoreCase)).FirstOrDefault();
            UserManager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(context));
            UserManager.AddToRole(user.Id, "Básico");
            UserManager.UpdateSecurityStamp(user.Id);
            user.LockoutEnabled = true;
        }
Exemplo n.º 20
0
        protected override void Seed(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.People.AddOrUpdate(
            //      p => p.FullName,
            //      new Person { FullName = "Andrew Peters" },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );


            //The UserStore is ASP Identity's data layer. Wrap context with the UserStore.
            UserStore <ApplicationUser> userStore = new UserStore <ApplicationUser>(context);

            //The UserManager is ASP Identity's implementation layer: contains the methods.
            //The constructor takes the UserStore: how the methods will interact with the database.
            UserManager <ApplicationUser> userManager = new UserManager <ApplicationUser>(userStore);

            //Add or Update the initial Users into the database as normal.

            context.Users.AddOrUpdate(
                x => x.Email,  //Using Email as the Unique Key: If a record exists with the same email, AddOrUpdate skips it.
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), FirstName = "Damon", LastName = "Bailey", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("Som3Pass!")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), FirstName = "Karen", LastName = "Bailey", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("MyPassword")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), FirstName = "Seed", LastName = "User", Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("MyPassword2")
            }
                );

            //Save changes so the Id columns will auto-populate.
            context.SaveChanges();

            //ASP Identity User Id's are Guids stored as nvarchar(128), and exposed as strings.
            //Get the UserId only if the SecurityStamp is not set yet.
            string userId = context.Users.Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

            //If the userId is not null, then the SecurityStamp needs updating.
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            //Repeat for next user: good opportunity to make a helper method.
            userId = context.Users.Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            userId = context.Users.Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            context.SaveChanges();

            context.Books.AddOrUpdate(x => x.Name,
                                      new Book()
            {
                OwnerId = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id), Name = "The Great Gatsby", Author = "F Scott Fitzgerald", Genre = "Mystery", CreatedUtc = DateTimeOffset.Now
            },
                                      new Book()
            {
                OwnerId = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id), Name = "Huckleberry Finn", Author = "Mark Twain", Genre = "Adventure", CreatedUtc = DateTimeOffset.Now
            },
                                      new Book()
            {
                OwnerId = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id), Name = "The Catcher in the Rye", Author = "J D Salinger", Genre = "Adult", CreatedUtc = DateTimeOffset.Now
            }
                                      );

            context.BookClubs.AddOrUpdate(x => x.Name,
                                          new BookClub()
            {
                OwnerId = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id), Name = "Mystery Club", Description = "We love mystery novels.", CreatedUtc = DateTimeOffset.Now
            });

            context.SaveChanges();

            context.UserBookJoins.AddOrUpdate(x => x.ReaderId,
                                              new UserBookJoin()
            {
                OwnerId    = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id),
                ReaderId   = context.Users.Single(e => e.UserName == "*****@*****.**").Id,
                BookId     = context.Books.Single(e => e.Name == "The Great Gatsby").Id,
                Rating     = 5,
                CreatedUtc = DateTimeOffset.Now
            });

            context.SaveChanges();

            context.UserBookClubJoins.AddOrUpdate(x => x.BookClubId,
                                                  new UserBookClubJoin()
            {
                OwnerId    = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id),
                ReaderId   = context.Users.Single(e => e.UserName == "*****@*****.**").Id,
                BookClubId = context.BookClubs.Single(e => e.Name == "Mystery Club").BookClubId,
                CreatedUtc = DateTimeOffset.Now
            });

            context.SaveChanges();

            //context.BookClubBookJoins.AddOrUpdate(x => x.BookClubId,
            //new BookClubBookJoin()
            //{
            //    OwnerId = Guid.Parse(context.Users.Single(e => e.UserName == "*****@*****.**").Id),
            //    BookId = context.Books.Single(e => e.Name == "The Great Gatsby").Id,
            //    BookClubId = context.BookClubs.Single(e => e.Name == "Mystery Club").BookClubId,
            //    BookClubName = "Seed Book Club"
            //});
        }
Exemplo n.º 21
0
        protected override void Seed(AuctionExpress.Data.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.Product.AddOrUpdate(
            //      p => p.ProductStartTime,
            //      new Product { ProductStartTime = DateTimeOffset.Now.AddDays(5) },
            //      new Person { FullName = "Brice Lambson" },
            //      new Person { FullName = "Rowan Miller" }
            //    );
            //

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

            context.Users.AddOrUpdate(
                x => x.UserName,
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("@dmin1")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("TestActiveUser")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("User1")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("User2")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("User3")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", PasswordHash = new PasswordHasher().HashPassword("TestActiveUser")
            },
                new ApplicationUser()
            {
                Id = Guid.NewGuid().ToString(), Email = "*****@*****.**", UserName = "******", BusinessName = "AuctionExpress", IsActive = false, PasswordHash = new PasswordHasher().HashPassword("TestInActiveUser")
            });

            context.SaveChanges();

            context.Roles.AddOrUpdate(
                x => x.Name,
                new IdentityRole()
            {
                Name = "Admin"
            },
                new IdentityRole()
            {
                Name = "ActiveUser"
            },
                new IdentityRole()
            {
                Name = "InActiveUser"
            }
                );

            context.SaveChanges();

            userManager.AddToRole(context.Users.Single(e => e.UserName == "Admin").Id, "Admin");

            List <string> userNames = new List <string>()
            {
                "Admin", "TestActiveUser", "TestInActiveUser"
            };

            foreach (var user in userNames)
            {
                string userId = context.Users.Where(x => x.UserName == user && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

                if (!string.IsNullOrEmpty(userId))
                {
                    userManager.UpdateSecurityStamp(userId);
                }

                context.SaveChanges();
            }

            context.Category.AddOrUpdate(

                x => x.CategoryName,
                new Category()
            {
                CategoryName = "Office Chairs"
            },
                new Category()
            {
                CategoryName = "Desks"
            },
                new Category()
            {
                CategoryName = "Tables"
            },
                new Category()
            {
                CategoryName = "Filing Cabinets"
            });
            context.SaveChanges();

            context.Product.AddOrUpdate(
                x => x.ProductName,
                new Product()
            {
                ProductName         = "Executive Leather Office Chairs",
                ProductDescription  = "Like new black leather swivel chairs with armrests.",
                ProductQuantity     = 10,
                ProductStartTime    = DateTimeOffset.Now.AddDays(-4),
                ProductCloseTime    = DateTimeOffset.Now.AddDays(+5),
                ProductCategoryId   = context.Category.Single(e => e.CategoryName == "Office Chairs").CategoryId,
                MinimumSellingPrice = 50.00,
                ProductSeller       = context.Users.Single(e => e.UserName == "User1").Id
            },
                new Product()
            {
                ProductName         = "Oak Desks",
                ProductDescription  = "Brand new oak desk",
                ProductQuantity     = 5,
                ProductStartTime    = DateTimeOffset.Now.AddDays(-10),
                ProductCloseTime    = DateTimeOffset.Now.AddDays(-5),
                ProductCategoryId   = context.Category.Single(e => e.CategoryName == "Desks").CategoryId,
                MinimumSellingPrice = 200.00,
                ProductSeller       = context.Users.Single(e => e.UserName == "User2").Id
            },
                new Product()
            {
                ProductName         = "White Folding Tables",
                ProductDescription  = "Standard folding tables, ideal for break room",
                ProductQuantity     = 50,
                ProductStartTime    = DateTimeOffset.Now.AddDays(+3),
                ProductCloseTime    = DateTimeOffset.Now.AddDays(+8),
                ProductCategoryId   = context.Category.Single(e => e.CategoryName == "Tables").CategoryId,
                MinimumSellingPrice = 14.00,
                ProductSeller       = context.Users.Single(e => e.UserName == "User3").Id
            },
                new Product()
            {
                ProductName         = "Four drawer filing cabinet",
                ProductDescription  = "Used filing cabinet, 60 inches high",
                ProductQuantity     = 5,
                ProductStartTime    = DateTimeOffset.Now.AddDays(-2),
                ProductCloseTime    = DateTimeOffset.Now.AddDays(+2),
                ProductCategoryId   = context.Category.Single(e => e.CategoryName == "Filing Cabinets").CategoryId,
                MinimumSellingPrice = 45.00,
                ProductSeller       = context.Users.Single(e => e.UserName == "User2").Id
            }

                );
            context.SaveChanges();
        }
 public ActionResult LogoutUser(string id)
 {
     UserManager.UpdateSecurityStamp(id);
     return(new EmptyResult());
 }
Exemplo n.º 23
0
        protected override void Seed(WebChatContext context)
        {
            if (!context.Users.Any())
            {
                var userStore   = new UserStore <ApplicationUser>(context);
                var userManager = new UserManager <ApplicationUser>(userStore);

                var userA = new ApplicationUser
                {
                    Email        = "*****@*****.**",
                    UserName     = "******",
                    PasswordHash = new PasswordHasher().HashPassword("Password1!")
                };
                var userB = new ApplicationUser
                {
                    Email        = "*****@*****.**",
                    UserName     = "******",
                    PasswordHash = new PasswordHasher().HashPassword("Password1!")
                };

                context.Users.Add(userA);
                context.Users.Add(userB);
                context.SaveChanges();

                userManager.UpdateSecurityStamp(userA.Id);
                userManager.UpdateSecurityStamp(userB.Id);
                context.SaveChanges();

                var messages = new List <ChannelMessage>
                {
                    new ChannelMessage
                    {
                        Text   = "Wassup Bats!?",
                        Date   = DateTime.Now,
                        Sender =
                            context.Users.FirstOrDefault(
                                u => u.UserName == "Robin")
                    },
                    new ChannelMessage
                    {
                        Text   = "I'm Batman!",
                        Date   = DateTime.Now,
                        Sender =
                            context.Users.FirstOrDefault(
                                u => u.UserName == "Batman")
                    }
                };

                var channel = new Channel
                {
                    Name  = "Channel-1",
                    Users =
                        context.Users.Where(
                            u => u.UserName == "Batman" || u.UserName == "Robin").ToList(),
                    Messages = messages
                };

                context.Channels.Add(channel);
                context.SaveChanges();
            }
        }
Exemplo n.º 24
0
 public ActionResult LogOut()
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.TwoFactorCookie);
     UserManager.UpdateSecurityStamp(User.Identity.GetUserId());
     return(RedirectToAction("Index", "Support"));
 }
Exemplo n.º 25
0
        protected override void Seed(WebChatContext context)
        {
            var userStore   = new UserStore <ApplicationUser>(context);
            var userManager = new UserManager <ApplicationUser>(userStore);

            if (!context.Users.Any())
            {
                List <ApplicationUser> users = SeedUsers(context);
                foreach (var applicationUser in users)
                {
                    context.Users.Add(applicationUser);
                    context.SaveChanges();
                    var userId = context.Users.Where(u => u.Email == applicationUser.Email).Select(u => u.Id).FirstOrDefault();
                    userManager.UpdateSecurityStamp(userId);
                }
            }

            if (!context.ChatRooms.Any())
            {
                var rooms = new string[]
                {
                    "gaming",
                    "programming",
                    "lifestyle",
                    "football",
                    "cooking"
                };
                foreach (var room in rooms)
                {
                    context.ChatRooms.Add(new ChatRoom()
                    {
                        Name = room
                    });
                }

                context.SaveChanges();
            }
            if (!context.Messages.Any())
            {
                var messages = new Message[]
                {
                    new Message()
                    {
                        Content         = "Hi! How are you?",
                        MessageDateTime = DateTime.Now.AddDays(-1),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "I'm fine, just a bit tired.",
                        MessageDateTime = DateTime.Now,
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "Did you watched the latest lecture about advanced tree structures?",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-3),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "Yes I did!",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-2),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "Wow! Feeling so special.",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-4),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "Nananananananananna!!!",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-3),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id,
                    },
                    new Message()
                    {
                        Content         = "What a game it was yesterday! Did you watched Valencia against Deportivo?",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(0),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "I was too tired and went to sleep :(!!",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(0),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "I cooked musaka yesterday. What have you cooked lately?",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-10),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "I cooked cream brulle.",
                        ChatRoomId      = null,
                        MessageDateTime = DateTime.Now.AddDays(-9),
                        SenderId        = context.Users.First().Id,
                        ReceiverId      = context.Users.OrderBy(u => u.Id).Skip(2).FirstOrDefault().Id
                    },
                    new Message()
                    {
                        Content         = "Wassup dudes",
                        ChatRoomId      = 1,
                        MessageDateTime = DateTime.Now.AddDays(-9),
                        SenderId        = context.Users.First().Id,
                    }
                };

                foreach (var message in messages)
                {
                    context.Messages.Add(message);
                }

                context.SaveChanges();
            }
        }
Exemplo n.º 26
0
        protected override void Seed(YoutubePlaylistsDbContext context)
        {
            if (context.Users.Any())
            {
                return;
            }

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

            string[] userNames = new string[]
            {
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
                "*****@*****.**",
            };

            string[] userPasswords = new string[]
            {
                "admin",
                "user1",
                "user2",
                "user3",
                "user4",
                "user5",
            };

            for (int i = 0; i < userNames.Length; i++)
            {
                string password = passwordHash.HashPassword(userPasswords[i]);
                context.Users.AddOrUpdate(u => u.UserName,
                                          new User()
                {
                    UserName     = userNames[i],
                    Email        = userNames[i],
                    PasswordHash = password,
                    FirstName    = "Test",
                    LastName     = "User"
                });


                context.SaveChanges();

                string uName  = userNames[i];
                string userId = context.Users.Where(x => x.Email == uName && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

                //If the userId is not null, then the SecurityStamp needs updating.
                if (!string.IsNullOrEmpty(userId))
                {
                    userManager.UpdateSecurityStamp(userId);
                }

                context.SaveChanges();
            }

            for (int i = 0; i < 500; i++)
            {
                var randomCategoryName = RandomString(30);

                if (context.Categories.Any(c => c.Name == randomCategoryName))
                {
                    continue;
                }

                var newCategory = new Category()
                {
                    Name = randomCategoryName
                };

                context.Categories.Add(newCategory);
                context.SaveChanges();
            }

            string[] youtubeVideos = new string[]
            {
                "https://www.youtube.com/embed/oPmKRtWta4E",
                "https://www.youtube.com/embed/XQEBzauVIlA",
                "https://www.youtube.com/embed/FBmkFYym9hE",
                "https://www.youtube.com/embed/cW2bqBhP4AA",
                "https://www.youtube.com/embed/CDl9ZMfj6aE",
                "https://www.youtube.com/embed/04F4xlWSFh0",
                "https://www.youtube.com/embed/UclCCFNG9q4",
                "https://www.youtube.com/embed/Aym9-pzfvbA",
                "https://www.youtube.com/embed/qqrnLkEFxKw",
                "https://www.youtube.com/embed/c18441Eh_WE",
                "https://www.youtube.com/embed/zI339U6GS9s",
                "https://www.youtube.com/embed/9ro0FW9Qt-4",
                "https://www.youtube.com/embed/weRHyjj34ZE",
                "https://www.youtube.com/embed/p47fEXGabaY",
                "https://www.youtube.com/embed/8BkYKwHLXiU",
                "https://www.youtube.com/embed/lBztnahrOFw",
                "https://www.youtube.com/embed/KxcP7TRY178",
                "https://www.youtube.com/embed/Cydzolb0eIs",
                "https://www.youtube.com/embed/q4v1nDa7tLY",
                "https://www.youtube.com/embed/EdP19wnPPoY",
                "https://www.youtube.com/embed/Z2_rwr_qEkA",
                "https://www.youtube.com/embed/l46yY9pGghY",
                "https://www.youtube.com/embed/zWj2N2wp07s",
                "https://www.youtube.com/embed/XAIX2vISe3M",
                "https://www.youtube.com/embed/Q8gi_yLF8r8",
                "https://www.youtube.com/embed/hDy1LyGZmiY",
                "https://www.youtube.com/embed/-Gw1SHWMmDs",
                "https://www.youtube.com/embed/UCCpdI8vd5I",
                "https://www.youtube.com/embed/FMYmzcgZqZw",
                "https://www.youtube.com/embed/yf-rfClPFwA",
                "https://www.youtube.com/embed/Vkt-Ey6Wl8E",
                "https://www.youtube.com/embed/AHXv_IWLmzw",
                "https://www.youtube.com/embed/mek_03oNTeI",
                "https://www.youtube.com/embed/fqcSO0zT2Sg",
                "https://www.youtube.com/embed/mek_03oNTeI",
                "https://www.youtube.com/embed/fqcSO0zT2Sg",
                "https://www.youtube.com/embed/mek_03oNTeI",
                "https://www.youtube.com/embed/fqcSO0zT2Sg",
            };

            int videoCounter = 0;

            for (int i = 0; i < 11; i++)
            {
                var randomCategory = context.Categories.OrderBy(qu => Guid.NewGuid()).First();
                var randomUser     = context.Users.OrderBy(qu => Guid.NewGuid()).First();
                var playList       = new Playlist()
                {
                    Title       = "Playlist " + (i + 1),
                    DateCreated = DateTime.Now,
                    Description = "Description for Playlist" + (i + 1),
                    CategoryId  = randomCategory.Id,
                    CreatorId   = randomUser.Id
                };

                for (int j = 0; j < 3; j++)
                {
                    playList.Videos.Add(new Video()
                    {
                        Url = youtubeVideos[videoCounter]
                    });
                    videoCounter++;
                }

                context.Playlists.Add(playList);
                context.SaveChanges();
            }

            Random rnd = new Random();

            for (int i = 0; i < 300; i++)
            {
                var rating         = rnd.Next(1, 6);
                var randomUser     = context.Users.OrderBy(qu => Guid.NewGuid()).First();
                var randomPlaylist = context.Playlists.OrderBy(qu => Guid.NewGuid()).First();

                if (context.Ratings.Any(r => r.PlaylistId == randomPlaylist.Id && r.UserId == randomUser.Id))
                {
                    continue;
                }

                var createdRating = new Rating()
                {
                    PlaylistId = randomPlaylist.Id,
                    UserId     = randomUser.Id,
                    Value      = rating
                };

                context.Ratings.Add(createdRating);
                context.SaveChanges();
            }
        }
Exemplo n.º 27
0
        protected override void Seed(HeroicallyRecipesDbContext context)
        {
            PasswordHasher hasher      = new PasswordHasher();
            var            userManager = new UserManager <User>(new UserStore <User>(context));
            var            roleManager = new RoleManager <IdentityRole>(new RoleStore <IdentityRole>(context));

            string         roleName = "Admin";
            IdentityResult roleResult;

            if (!roleManager.RoleExists(roleName))
            {
                roleResult = roleManager.Create(new IdentityRole(roleName));
                var admin = new User
                {
                    Email        = "*****@*****.**",
                    PasswordHash = hasher.HashPassword("admin"),
                    UserName     = "******",
                    NickName     = "*****@*****.**",
                    AvatarUrl    = "/images/defaultAvatar3.png"
                };

                context.Users.Add(admin);
                context.SaveChanges();
                userManager.UpdateSecurityStamp(admin.Id);

                userManager.AddToRole(admin.Id, roleName);
            }

            if (!context.Tags.Any())
            {
                string[] tags = new string[]
                {
                    "Appetizers",
                    "Baking",
                    "Beef",
                    "Breakfast",
                    "Chicken",
                    "Desserts",
                    "Drinks",
                    "Fish",
                    "Pasta",
                    "Pizza",
                    "Pork",
                    "Sides",
                    "Apple",
                    "Artichoke",
                    "Arugula",
                    "Asparagus",
                    "Avocado",
                    "Bamboo Shoots",
                    "Bean Sprouts",
                    "Beans- see Bean List",
                    "Beet",
                    "Belgian Endive",
                    "Bell Pepper",
                    "Broccoli",
                    "Brussels Sprouts",
                    "Burdock Root/Gobo",
                    "Cabbage",
                    "Calabash",
                    "Capers",
                    "Carrot",
                    "Cassava/Yuca",
                    "Cauliflower",
                    "Celery",
                    "Celtuce",
                    "Chayote",
                    "Corn/Maize",
                    "Cucumber",
                    "Daikon Radish",
                    "Edamame",
                    "Eggplant/Aubergine",
                    "Elephant Garlic",
                    "Endive",
                    "Fennel",
                    "Fiddlehead",
                    "Galangal",
                    "Garlic",
                    "Ginger",
                    "Grape Leaves",
                    "Green Beans",
                    "Greens",
                    "Hearts of Palm",
                    "Horseradish",
                    "Kale",
                    "Kohlrabi",
                    "Leeks",
                    "Lemongrass",
                    "Lettuce",
                    "Lotus Root",
                    "Lotus Seed",
                    "Mushrooms- see Mushroom List",
                    "Napa Cabbage",
                    "Nopales",
                    "Okra",
                    "Olive",
                    "Onion",
                    "Parsley",
                    "Parsley Root",
                    "Parsnip",
                    "Peas",
                    "Peppers",
                    "Plantain",
                    "Potato",
                    "Pumpkin",
                    "Purslane",
                    "Radicchio",
                    "Radish",
                    "Rutabaga",
                    "Sea Vegetables- see Sea Vegetable List",
                    "Shallots",
                    "Spinach",
                    "Squash- see Squash List",
                    "Sweet Potato",
                    "Swiss Chard",
                    "Taro",
                    "Tomatillo",
                    "Tomato",
                    "Turnip",
                    "Water Chestnut",
                    "Water Spinach",
                    "Watercress",
                    "Winter Melon",
                    "Yams",
                    "Zucchini",
                };

                for (int i = 0; i < tags.Length; i++)
                {
                    context.Tags.Add(new Tag()
                    {
                        Text = tags[i]
                    });
                }

                context.SaveChanges();
            }
        }
Exemplo n.º 28
0
        private void SeedUserWithFarms(RabbitFarmContext context)
        {
            //The UserStore is ASP Identity's data layer. Wrap context with the UserStore.
            UserStore <User> userStore = new UserStore <User>(context);

            //The UserManager is ASP Identity's implementation layer: contains the methods.
            //The constructor takes the UserStore: how the methods will interact with the database.
            UserManager <User> userManager = new UserManager <User>(userStore);

            //Add or Update the initial Users into the database as normal.
            context.Users.AddOrUpdate(
                x => x.Email,  //Using Email as the Unique Key: If a record exists with the same email, AddOrUpdate skips it.
                new User()
            {
                Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("Som3Pass!")
            },
                new User()
            {
                Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("MyPassword")
            },
                new User()
            {
                Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("PenkasPassword")
            },
                new User()
            {
                Email = "*****@*****.**", UserName = "******", PasswordHash = new PasswordHasher().HashPassword("MilkasPassword")
            }
                );

            //Save changes so the Id columns will auto-populate.
            context.SaveChanges();

            //ASP Identity User Id's are Guids stored as nvarchar(128), and exposed as strings.

            //Get the UserId only if the SecurityStamp is not set yet.
            string userId = context.Users.Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp)).Select(x => x.Id).FirstOrDefault();

            //If the userId is not null, then the SecurityStamp needs updating.
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            //Repeat for next user: good opportunity to make a helper method.
            userId = context.Users
                     .Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp))
                     .Select(x => x.Id)
                     .FirstOrDefault();
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            userId = context.Users
                     .Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp))
                     .Select(x => x.Id)
                     .FirstOrDefault();
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            userId = context.Users
                     .Where(x => x.Email == "*****@*****.**" && string.IsNullOrEmpty(x.SecurityStamp))
                     .Select(x => x.Id)
                     .FirstOrDefault();
            if (!string.IsNullOrEmpty(userId))
            {
                userManager.UpdateSecurityStamp(userId);
            }

            //Continue on with Seed.

            var farm1 = new Farm()
            {
                Name  = "My Rabbit Farm",
                Users = context.Users.Where(u => u.Email == "*****@*****.**").ToList()
            };
            var farm2 = new Farm()
            {
                Name  = "Happy easter day",
                Users = context.Users.Where(u => u.Email == "*****@*****.**").ToList()
            };
            var farm3 = new Farm()
            {
                Name  = "Rabbit heaven",
                Users = context.Users.Where(u => u.Email == "*****@*****.**").ToList()
            };
            var farm4 = new Farm()
            {
                Name  = "Farm for rabbit",
                Users = context.Users.Where(u => u.Email == "*****@*****.**").ToList()
            };
            var farm5 = new Farm()
            {
                Name  = "Rabbitlandia",
                Users = context.Users.Where(u => u.Email == "*****@*****.**").ToList()
            };

            context.Farms.AddOrUpdate(farm1);
            context.Farms.AddOrUpdate(farm2);
            context.Farms.AddOrUpdate(farm3);
            context.Farms.AddOrUpdate(farm4);
            context.Farms.AddOrUpdate(farm5);
            context.SaveChanges();
        }
Exemplo n.º 29
0
        protected override void Seed(BookShop.Data.BookShopContext context)
        {
            var random = new Random();

            using (var authorReader = new StreamReader("../../../authors.txt"))
            {
                var aurthorLine = authorReader.ReadLine();
                aurthorLine = authorReader.ReadLine();
                while (aurthorLine != null)
                {
                    var authorData = aurthorLine.Split(' ');
                    var author     = new Author()
                    {
                        FirstName = authorData[0], LastName = authorData[1]
                    };
                    context.Authors.Add(author);

                    aurthorLine = authorReader.ReadLine();
                }
            }

            context.SaveChanges();

            var authors = context.Authors.ToList();

            using (var reader = new StreamReader("../../../books.txt"))
            {
                var line = reader.ReadLine();
                line = reader.ReadLine();
                while (line != null)
                {
                    var data           = line.Split(new[] { ' ' }, 6);
                    var authorIndex    = random.Next(0, authors.Count);
                    var author         = authors[authorIndex];
                    var edition        = (EditionType)int.Parse(data[0]);
                    var releaseDate    = DateTime.ParseExact(data[1], "d/M/yyyy", CultureInfo.InvariantCulture);
                    var copies         = int.Parse(data[2]);
                    var price          = decimal.Parse(data[3]);
                    var ageRestriction = (AgeRestriction)int.Parse(data[4]);
                    var title          = data[5];

                    context.Books.Add(new Book()
                    {
                        Author         = author,
                        EditionType    = edition,
                        ReleaseDate    = releaseDate,
                        Copies         = copies,
                        Price          = price,
                        AgeRestriction = ageRestriction,
                        Title          = title
                    });

                    line = reader.ReadLine();
                }
            }

            context.SaveChanges();

            var books = context.Books.ToList();

            using (var categoriesReader = new StreamReader("../../../categories.txt"))
            {
                var categoryName = categoriesReader.ReadLine();
                while (categoryName != null)
                {
                    var bookIndex = random.Next(0, books.Count);
                    var category  = new Category()
                    {
                        Name = categoryName, BookId = bookIndex
                    };
                    context.Categories.Add(category);

                    categoryName = categoriesReader.ReadLine();
                }
            }

            base.Seed(context);

            context.Roles.Add(new IdentityRole()
            {
                Name = "Admin"
            });

            context.Roles.Add(new IdentityRole()
            {
                Name = "Mod"
            });

            context.Users.Add(new ApplicationUser()
            {
                Email        = "Admin",
                UserName     = "******",
                PasswordHash = new PasswordHasher().HashPassword("Admin")
            });

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

            context.SaveChanges();

            var admin = context.Users.First();

            userManager.UpdateSecurityStamp(admin.Id);
            admin.Roles.Add(new IdentityUserRole()
            {
                UserId = context.Users.FirstOrDefault(u => u.UserName == "Admin").Id,
                RoleId = context.Roles.FirstOrDefault(u => u.Name == "Admin").Id
            });

            context.SaveChanges();
        }