private static void SetPasswordData(User user)
 {
     byte[] salt = null;
     byte[] hash = new PasswordHasher().Hash(user.StringPassword, ref salt);
     user.Password = hash;
     user.Salt = salt;
 }
        private static void RunHashLoop(ref byte[] salt, int max)
        {
            var hasher = new PasswordHasher();
            var watch = Stopwatch.StartNew();
            for (int i = 0; i < max; i++)
            {
                hasher.Hash("random password :!/", ref salt);
            }

            watch.Stop();
            Console.WriteLine("{0} s/hash", watch.Elapsed.TotalSeconds / max);
        }
Example #3
0
 /// <summary>
 /// Creates a user model with the specified email address and password.
 /// </summary>
 /// <param name="email">Email address of the user</param>
 /// <param name="password">Password of the user</param>
 /// <returns></returns>
 private static SimpleIdentityUser CreateUser(string email, string password)
 {
     var normalizer = new UpperInvariantLookupNormalizer();
     var user = new SimpleIdentityUser
     {
         Email = email,
         NormalizedUserName = normalizer.Normalize(email),
     };
     var hasher = new PasswordHasher<SimpleIdentityUser>();
     user.PasswordHash = hasher.HashPassword(user, password);
     return user;
 }
Example #4
0
        private void SeedUsers()
        {
            if (!this.context.Users.Any())
            {
                var adminRole = new IdentityRole { Name = GlobalConstants.AdminRoleName, Id = Guid.NewGuid().ToString() };
                this.context.Roles.Add(adminRole);

                var hasher = new PasswordHasher();

                var adminUser = new User
                {
                    UserName = "******",
                    Email = "*****@*****.**",
                    FirstName = "Ivaylo",
                    LastName = "Arnaudov",
                    PasswordHash = hasher.HashPassword("testtest"),
                    EmailConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString()
                };

                adminUser.Roles.Add(new IdentityUserRole { RoleId = adminRole.Id, UserId = adminUser.Id });
                this.context.Users.Add(adminUser);

                for (int i = 1; i <= 5; i++)
                {
                    var currentUser = new User
                    {
                        UserName = string.Format("user{0}@linuxpackages.net", i),
                        Email = string.Format("user{0}@linuxpackages.net", i),
                        FirstName = this.randomGenerator.GenerateRandomString(10),
                        LastName = this.randomGenerator.GenerateRandomString(20),
                        PasswordHash = hasher.HashPassword(string.Format("user{0}", i)),
                        EmailConfirmed = true,
                        SecurityStamp = Guid.NewGuid().ToString()
                    };

                    this.context.Users.Add(currentUser);
                }
            }

            this.context.SaveChanges();
        }
Example #5
0
        static Program()
        {
          //  Database.SetInitializer(new DatabaseInitializer());
            LiverpoolContext db = new LiverpoolContext(new DbContextOptions<LiverpoolContext>());
            //   db.Database.Initialize(true);
            var store = new UserStore<User, Role, LiverpoolContext, int>(db);
            IPasswordHasher<User> hasher = new PasswordHasher<User>();
            //var provider = new MachineKeyProtectionProvider();
            //var userStore = new UserStore<User, Role, int, UserLogin, UserRole, UserClaim>(_context);
            var userManager = new UserManager<User>(store, null, hasher, null, null, null, null, null, null);
            UserRepository = new UserRepository(db, userManager);
            ForumMessageRepository = new ForumMessageRepository(db);
            ForumSectionRepository = new ForumSectionRepository(db);
            ForumSubsectionRepository = new ForumSubsectionRepository(db);
            ForumThemeRepository = new ForumThemeRepository(db);
            MaterialRepository = new MaterialRepository(db);
            MaterialCategoryRepository = new MaterialCategoryRepository(db);
            MaterialCommentRepository = new MaterialCommentRepository(db);

        }
Example #6
0
        public IActionResult Register(TenantModel model)
        {
            if (model == null)
            {
                return(BadRequest(new
                {
                    errors = "Tenant data is required."
                }));
            }

            if (!ModelState.IsValid)
            {
                var errors = new JArray();

                foreach (var k in ModelState.Keys)
                {
                    errors.Add(ModelState[k].Errors.FirstOrDefault().ErrorMessage);
                }

                return(Ok(new
                {
                    errors
                }));
            }

            var sw = Stopwatch.StartNew();

            object error;

            if (string.IsNullOrEmpty(model.PasswordHash) && !string.IsNullOrEmpty(model.Password))
            {
                if (!CheckPasswordPolicy(model.Password, out error))
                {
                    sw.Stop();

                    return(BadRequest(error));
                }
                model.PasswordHash = PasswordHasher.GetClientPassword(model.Password);
            }

            if (!CheckValidName(model.FirstName.Trim() + model.LastName.Trim(), out error))
            {
                sw.Stop();

                return(BadRequest(error));
            }

            var checkTenantBusyPesp = CheckExistingNamePortal(model.PortalName.Trim());

            if (checkTenantBusyPesp != null)
            {
                sw.Stop();

                return(checkTenantBusyPesp);
            }

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CheckExistingNamePortal: {1}", model.PortalName, sw.ElapsedMilliseconds);

            var clientIP = CommonMethods.GetClientIp();

            Log.DebugFormat("clientIP = {0}", clientIP);

            if (CommonMethods.CheckMuchRegistration(model, clientIP, sw))
            {
                return(BadRequest(new
                {
                    errors = new[] { "tooMuchAttempts" }
                }));
            }

            if (CommonConstants.RecaptchaRequired && !CommonMethods.IsTestEmail(model.Email))
            {
                /*** validate recaptcha ***/
                if (!CommonMethods.ValidateRecaptcha(model.RecaptchaResponse, clientIP))
                {
                    Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds);

                    sw.Stop();

                    return(BadRequest(new
                    {
                        errors = new[] { "recaptchaInvalid" },
                        message = "Recaptcha is invalid"
                    }));
                }

                Log.DebugFormat("PortalName = {0}; Elapsed ms. ValidateRecaptcha: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }

            //check payment portal count
            if (Configuration["core:base-domain"] == "localhost")
            {
                var tenants     = HostedSolution.GetTenants(DateTime.MinValue);
                var firstTenant = tenants.FirstOrDefault();

                if (firstTenant != null)
                {
                    var activePortals = tenants.Count(r => r.Status != TenantStatus.Suspended && r.Status != TenantStatus.RemovePending);

                    var quota = HostedSolution.GetTenantQuota(firstTenant.TenantId);

                    if (quota.CountPortals > 0 && quota.CountPortals <= activePortals)
                    {
                        return(BadRequest(new
                        {
                            errors = new[] { "portalsCountTooMuch" },
                            message = "Too much portals registered already",
                        }));
                    }
                }
            }

            var language = model.Language ?? string.Empty;

            var tz = TimeZonesProvider.GetCurrentTimeZoneInfo(language);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.GetCurrentTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);

            if (!string.IsNullOrEmpty(model.TimeZoneName))
            {
                tz = TimeZoneConverter.GetTimeZone(model.TimeZoneName.Trim(), false) ?? tz;

                Log.DebugFormat("PortalName = {0}; Elapsed ms. TimeZonesProvider.OlsonTimeZoneToTimeZoneInfo: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }

            var lang = TimeZonesProvider.GetCurrentCulture(language);

            Log.DebugFormat("PortalName = {0}; model.Language = {1}, resultLang.DisplayName = {2}", model.PortalName, language, lang.DisplayName);

            var info = new TenantRegistrationInfo
            {
                Name                = Configuration["web:portal-name"] ?? "Cloud Office Applications",
                Address             = model.PortalName,
                Culture             = lang,
                FirstName           = model.FirstName.Trim(),
                LastName            = model.LastName.Trim(),
                PasswordHash        = string.IsNullOrEmpty(model.PasswordHash) ? null : model.PasswordHash,
                Email               = model.Email.Trim(),
                TimeZoneInfo        = tz,
                MobilePhone         = string.IsNullOrEmpty(model.Phone) ? null : model.Phone.Trim(),
                Industry            = (TenantIndustry)model.Industry,
                Spam                = model.Spam,
                Calls               = model.Calls,
                LimitedControlPanel = model.LimitedControlPanel
            };

            if (!string.IsNullOrEmpty(model.PartnerId))
            {
                if (Guid.TryParse(model.PartnerId, out var guid))
                {
                    // valid guid
                    info.PartnerId = model.PartnerId;
                }
            }

            if (!string.IsNullOrEmpty(model.AffiliateId))
            {
                info.AffiliateId = model.AffiliateId;
            }

            Tenant t;

            try
            {
                /****REGISTRATION!!!*****/
                if (!string.IsNullOrEmpty(ApiSystemHelper.ApiCacheUrl))
                {
                    ApiSystemHelper.AddTenantToCache(info.Address, SecurityContext.CurrentAccount.ID);

                    Log.DebugFormat("PortalName = {0}; Elapsed ms. CacheController.AddTenantToCache: {1}", model.PortalName, sw.ElapsedMilliseconds);
                }

                HostedSolution.RegisterTenant(info, out t);

                /*********/

                Log.DebugFormat("PortalName = {0}; Elapsed ms. HostedSolution.RegisterTenant: {1}", model.PortalName, sw.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                sw.Stop();

                Log.Error(e);

                return(StatusCode(StatusCodes.Status500InternalServerError, new
                {
                    errors = new[] { "registerNewTenantError" },
                    message = e.Message,
                    stacktrace = e.StackTrace
                }));
            }

            var isFirst = true;

            string sendCongratulationsAddress = null;

            if (!string.IsNullOrEmpty(model.PasswordHash))
            {
                isFirst = !CommonMethods.SendCongratulations(Request.Scheme, t, model.SkipWelcome, out sendCongratulationsAddress);
            }
            else if (Configuration["core:base-domain"] == "localhost")
            {
                try
                {
                    /* set wizard not completed*/
                    TenantManager.SetCurrentTenant(t);

                    var settings = SettingsManager.Load <WizardSettings>();

                    settings.Completed = false;

                    SettingsManager.Save(settings);
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }

            var reference = CommonMethods.CreateReference(Request.Scheme, t.GetTenantDomain(CoreSettings), info.Email, isFirst, model.Module);

            Log.DebugFormat("PortalName = {0}; Elapsed ms. CreateReferenceByCookie...: {1}", model.PortalName, sw.ElapsedMilliseconds);

            sw.Stop();

            return(Ok(new
            {
                errors = "",
                reference,
                tenant = ToTenantWrapper(t),
                referenceWelcome = sendCongratulationsAddress,
            }));
        }
Example #7
0
        private static async Task CreateFirstUser(ApplicationDbContext context)
        {
            var admin = new ApplicationUser
            {
                NormalizedEmail    = "*****@*****.**".ToUpper(),
                NormalizedUserName = "******".ToUpper(),
                Email          = "*****@*****.**",
                FirstName      = "Admin",
                LastName       = "Admin",
                UserName       = "******",
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp  = Guid.NewGuid().ToString()
            };

            var client = new ApplicationUser
            {
                NormalizedEmail    = "*****@*****.**".ToUpper(),
                NormalizedUserName = "******",
                Email          = "*****@*****.**",
                FirstName      = "Andrew",
                LastName       = "Andrew",
                UserName       = "******",
                Balance        = 10m,
                EmailConfirmed = true,
                LockoutEnabled = false,
                SecurityStamp  = Guid.NewGuid().ToString()
            };


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

            var adminRole  = Role.Admin.ToString();
            var clientRole = Role.Client.ToString();

            if (!context.Roles.Any(r => r.Name == adminRole))
            {
                await roleStore.CreateAsync(new IdentityRole { Name = adminRole, NormalizedName = adminRole });
            }

            if (!context.Roles.Any(r => r.Name == clientRole))
            {
                await roleStore
                .CreateAsync(new IdentityRole
                {
                    Name           = clientRole,
                    NormalizedName = clientRole
                });
            }

            if (!context.Users.Any(u => u.UserName == admin.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(admin, "password");
                admin.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(context);
                await userStore.CreateAsync(admin);

                await userStore.AddToRoleAsync(admin, adminRole);
            }

            if (!context.Users.Any(u => u.UserName == client.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(client, "password");
                client.PasswordHash = hashed;
                var userStore = new UserStore <ApplicationUser>(context);
                await userStore.CreateAsync(client);

                await userStore.AddToRoleAsync(client, clientRole);
            }

            await context.SaveChangesAsync();
        }
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <AppConfig>().HasData(
                new AppConfig()
            {
                Key = "HomeTitle", Value = "This is home page of eShopSolution"
            },
                new AppConfig()
            {
                Key = "HomeKeyword", Value = "This is keyword of eShopSolution"
            },
                new AppConfig()
            {
                Key = "HomeDescription", Value = "This is description of eShopSolution"
            }
                );

            modelBuilder.Entity <Language>().HasData(
                new Language()
            {
                Id = "vi-VN", Name = "Tiếng Việt", IsDefault = true
            },
                new Language()
            {
                Id = "en-US", Name = "English", IsDefault = false
            }
                );

            modelBuilder.Entity <Category>().HasData(
                new Category()
            {
                Id = 1, IsShowOnHome = true, ParentId = null, SortOrder = 1, Status = Status.Active,
            },
                new Category()
            {
                Id = 2, IsShowOnHome = true, ParentId = null, SortOrder = 2, Status = Status.Active,
            }
                );

            modelBuilder.Entity <CategoryTranslation>().HasData(
                new CategoryTranslation()
            {
                Id = 1, CategoryId = 1, Name = "Áo nam", LanguageId = "vi-VN", SeoAlias = "ao-nam", SeoDescription = "Sản phẩm áo thời trang nam", SeoTitle = "Sản phẩm áo thời trang nam"
            },
                new CategoryTranslation()
            {
                Id = 2, CategoryId = 1, Name = "Men shirt", LanguageId = "en-US", SeoAlias = "men-shirt", SeoDescription = "The shirt products for men", SeoTitle = "The shirt products for men"
            },
                new CategoryTranslation()
            {
                Id = 3, CategoryId = 2, Name = "Áo nữ", LanguageId = "vi-VN", SeoAlias = "ao-nu", SeoDescription = "Sản phẩm áo thời trang nữ", SeoTitle = "Sản phẩm áo thời trang nữ"
            },
                new CategoryTranslation()
            {
                Id = 4, CategoryId = 2, Name = "Women shirt", LanguageId = "en-US", SeoAlias = "women-shirt", SeoDescription = "The shirt products for women", SeoTitle = "The shirt products for women"
            }
                );

            modelBuilder.Entity <Product>().HasData(
                new Product()
            {
                Id = 1, DateCreated = DateTime.Now, OriginalPrice = 100000, Price = 200000, Stock = 0, ViewCount = 0,
            }
                );

            modelBuilder.Entity <ProductTranslation>().HasData(
                new ProductTranslation()
            {
                Id = 1, ProductId = 1, Name = "Áo sơ mi nam trắng Việt Tiến", LanguageId = "vi-VN", SeoAlias = "ao-so-mi-trang-viet-tien", SeoDescription = "Áo sơ mi nam trắng Việt Tiến", SeoTitle = "Áo sơ mi nam trắng Việt Tiến", Details = "Áo sơ mi nam trắng Việt Tiến", Description = "Áo sơ mi nam trắng Việt Tiến"
            },
                new ProductTranslation()
            {
                Id = 2, ProductId = 1, Name = "Viet Tien Men T-Shirt", LanguageId = "en-US", SeoAlias = "viet-tien-men-t-shirt", SeoDescription = "Viet Tien Men T-Shirt", SeoTitle = "Viet Tien Men T-Shirt", Details = "Viet Tien Men T-Shirt", Description = "Viet Tien Men T-Shirt"
            });

            modelBuilder.Entity <ProductInCategory>().HasData(
                new ProductInCategory()
            {
                ProductId = 1, CategoryId = 1
            }
                );
            // any guid
            var roleId  = new Guid("40FA8CD9-8FCA-46C1-9859-1B11C2E92ADB");
            var adminId = new Guid("408B4B21-707A-40B6-ABE6-DB868E7ADBD9");

            modelBuilder.Entity <AppRole>().HasData(new AppRole
            {
                Id             = roleId,
                Name           = "admin",
                NormalizedName = "admin",
                Description    = "Adminstrator role"
            });

            var hasher = new PasswordHasher <AppUser>();

            modelBuilder.Entity <AppUser>().HasData(new AppUser
            {
                Id                 = adminId,
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                PasswordHash       = hasher.HashPassword(null, "Abcd1234$"),
                SecurityStamp      = string.Empty,
                FirstName          = "Buu",
                LastName           = "Nong",
                Dob                = new DateTime(2020, 01, 31),
            });

            modelBuilder.Entity <IdentityUserRole <Guid> >().HasData(new IdentityUserRole <Guid>
            {
                RoleId = roleId,
                UserId = adminId
            });
        }
Example #9
0
        public static void Main(string[] args)
        {
            /*
            string user_salt = "NyfLZ6RJXWE1aHrrM5JRefMlipdBV0bCp";
            string password = "******";
            var pbkdf2 = new PBKDF2<HMACSHA512>(Encoding.ASCII.GetBytes(password), Encoding.ASCII.GetBytes(user_salt), 50);
            var bytes = pbkdf2.GetBytes(128);

            Console.WriteLine(String.Join("", bytes.Select(x => x.ToString("X2"))));
            return;
             */

            Console.WriteLine(PasswordHasher.GenerateSalt());

            int iterations = 0;
            int memoryBits = 22;

            var chasher = new PasswordHasher("Qq48KGoFOXbZcBXDHZuqyjTP5oBfUy4N2iEHmL2NkIw=", memoryBits, iterations);

            var startTime = DateTime.UtcNow;
            string hash = chasher.Hash("foo1", "NyfLZ6RJXWE1aHrrM5JRefMlipdBV0bCp");
            Console.WriteLine((DateTime.UtcNow - startTime).TotalMilliseconds);
            Console.WriteLine(hash);
            Console.WriteLine(chasher.MemoryUsage);

            var hasher = new TestPasswordHasher("Qq48KGoFOXbZcBXDHZuqyjTP5oBfUy4N2iEHmL2NkIw=", memoryBits, iterations);

            startTime = DateTime.UtcNow;
            hash = hasher.Hash("foo1", "NyfLZ6RJXWE1aHrrM5JRefMlipdBV0bCp");
            Console.WriteLine((DateTime.UtcNow - startTime).TotalMilliseconds);
            Console.WriteLine(hash);
            Console.WriteLine(hasher.MemoryUsage);
            #if DEBUG
            /* cell frequency */
            if (!Directory.Exists("stats"))
                Directory.CreateDirectory("stats");

            CellFrequency(String.Format("cellfreq-{0}-{1}.txt", memoryBits, iterations), hasher.__hashArray);

            /* xored cell frequency */
            byte[] xored = new byte[hasher.MemoryUsage];

            for (int i = 0; i < xored.Length; i++)
                xored[i] = (byte)(hasher.__hashArray[i] ^ hasher._originalArray[i]);

            Console.WriteLine("0 xor bytes: " + xored.Count(x => x == 0));

            CellFrequency(String.Format("xor-cellfreq-{0}-{1}.txt", memoryBits, iterations), xored);

            /* visit counts */
            var chars = "0123456789abcdefghijklmnopqrstuvwxyz".ToCharArray();
            System.IO.File.WriteAllText(String.Format(@"stats\hash-{0}-{1}.txt", memoryBits, iterations), String.Join("", hasher._visitCounts.Select(v => chars[v])));

            /* depth, count, iterations */
            _mixingHashes = hasher._hashes.Skip(1);

            string prevHash = hasher._hashes[0];

            _info[prevHash] = new HashTreeInfo
            {
                depth = 1,
                count = 0,
                iterations = 1
            };

            foreach(string nextHash in _mixingHashes)
            {
                _prevHash[nextHash] = prevHash;
                prevHash = nextHash;
            }

            var depths = _mixingHashes.Select(h => GetTreeInfo(hasher, h).ToString());
            System.IO.File.WriteAllLines(String.Format(@"stats\depths-{0}-{1}.txt", memoryBits, iterations), depths);
            #endif
            Console.ReadLine();
        }
        public static void Seed(this ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <AppConfig>().HasData(
                new AppConfig()
            {
                Key = "HomeTitle", Value = "This is home page of eShopSolution"
            },
                new AppConfig()
            {
                Key = "HomeKeyword", Value = "This is keyword of eShopSolution"
            },
                new AppConfig()
            {
                Key = "HomeDescription", Value = "This is description of eShopSolution"
            }
                );


            modelBuilder.Entity <Product>().HasData(
                new Product()
            {
                Id            = 1,
                DateCreated   = DateTime.Now,
                OriginalPrice = 250000,
                Price         = 39000,
                Stock         = 0,
                ViewCount     = 0,
            });
            modelBuilder.Entity <ProductTranslation>().HasData(
                new ProductTranslation()
            {
                Id         = 1,
                ProductId  = 1,
                Name       = "Samsung Note 10+",
                LanguageId = "vi",
                SeoAlias   = "Samsung Note 10+",

                SeoTitle    = "Samsung Note 10+ new ",
                Details     = "Samsung Note 10+ new",
                Description = "Samsung Note 10+ đên với camera 48MP"
            },
                new ProductTranslation()
            {
                Id         = 2,
                ProductId  = 1,
                Name       = "Samsung Note 10+",
                LanguageId = "en",
                SeoAlias   = "Samsung-Note-10+",

                SeoTitle    = "Samsung-Note-10+",
                Details     = "Samsung-Note-10+",
                Description = "Samsung-Note-10+"
            });
            modelBuilder.Entity <ProductInCategory>().HasData(
                new ProductInCategory()
            {
                ProductId = 1, CategoryId = 1
            }
                );


            modelBuilder.Entity <Language>().HasData(
                new Language()
            {
                Id = "vi", Name = "Tiếng Việt", IsDefault = true
            },
                new Language()
            {
                Id = "en", Name = "English", IsDefault = false
            });

            modelBuilder.Entity <Category>().HasData(
                new Category()
            {
                Id         = 1,
                IsShowHome = 1,
                ParentId   = 1,
                SortOrder  = 1,
                Status     = Status.Active,
            },
                new Category()
            {
                Id         = 2,
                IsShowHome = 1,
                ParentId   = 1,
                SortOrder  = 2,
                Status     = Status.Active
            });

            modelBuilder.Entity <CategoryTranslation>().HasData(
                new CategoryTranslation()
            {
                Id = 1, CategoryId = 1, Name = "Áo nam", LanguageId = "vi", SeoAlias = "ao-nam", SeoDescription = "Sản phẩm áo thời trang nam", SeoTitle = "Sản phẩm áo thời trang nam"
            },
                new CategoryTranslation()
            {
                Id = 2, CategoryId = 1, Name = "Men Shirt", LanguageId = "en", SeoAlias = "men-shirt", SeoDescription = "The shirt products for men", SeoTitle = "The shirt products for men"
            },
                new CategoryTranslation()
            {
                Id = 3, CategoryId = 2, Name = "Áo nữ", LanguageId = "vi", SeoAlias = "ao-nu", SeoDescription = "Sản phẩm áo thời trang nữ", SeoTitle = "Sản phẩm áo thời trang women"
            },
                new CategoryTranslation()
            {
                Id = 4, CategoryId = 2, Name = "Women Shirt", LanguageId = "en", SeoAlias = "women-shirt", SeoDescription = "The shirt products for women", SeoTitle = "The shirt products for women"
            }
                );


            // any guid
            var roleId  = new Guid("B09219DB-8402-414A-8938-60D964AC45FB");
            var adminId = new Guid("82A0B7C3-551B-44A7-8DB2-A7352E41C547");


            // any guid, but nothing is against to use the same one

            // AspNetRole
            modelBuilder.Entity <AppRole>().HasData(new AppRole
            {
                Id             = adminId,
                Name           = "Admin1",
                NormalizedName = "admin 1",
                Description    = "Administrator role"
            });



            // AspNetUser
            var hasher = new PasswordHasher <AppUser>();

            modelBuilder.Entity <AppUser>().HasData(new AppUser
            {
                Id                 = adminId,
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                PasswordHash       = hasher.HashPassword(null, "P@ssword1"),
                SecurityStamp      = string.Empty,
                DisplayName        = " Xuân Lộc",
                Gender             = Gender.Male,
            });
        }
Example #11
0
 public Manejador(CursosOnlineContext context, UserManager <Usuario> userManager, IJwtGenerador jwtGenerator, PasswordHasher <Usuario> passwordHasher)
 {
     _context        = context;
     _userManager    = userManager;
     _jwtGenerator   = jwtGenerator;
     _passwordHasher = passwordHasher;
 }
Example #12
0
        public async Task <IHttpActionResult> PostStudent(Student student)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            db.Students.Add(student);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateException)
            {
                if (StudentExists(student.SID))
                {
                    return(Conflict());
                }
                else
                {
                    throw;
                }
            }

            // Add student to the authdb
            using (ApplicationDbContext autDb = new ApplicationDbContext())
            {
                var exists = await autDb.Users.SingleOrDefaultAsync(
                    s => s.UserName == student.SID);

                if (exists == null)
                {
                    ApplicationRole role = await autDb.Roles.FirstOrDefaultAsync(
                        r => r.Name == "student");

                    PasswordHasher p    = new PasswordHasher();
                    var            user = new ApplicationUser()
                    {
                        FirstName    = student.FirstName,
                        SecondName   = student.SecondName,
                        UserName     = student.SID,
                        Email        = student.SID,
                        Approved     = true,
                        PasswordHash = p.HashPassword(student.SID),
                        // Should only beone
                        ProgrammeStageID = (int)(from ps in student.StudentProgrammeStages
                                                 select new
                                                 { ps.ProgrammeStageID })
                                           .First().ProgrammeStageID
                                           //SecurityStamp = new Guid(model.Email).ToString()
                                           // now done in Application user constructor
                    };
                    autDb.Users.Add(user);
                    user.Roles.Add(new ApplicationUserRole {
                        RoleId = role.Id
                    });
                    try
                    {
                        await autDb.SaveChangesAsync();
                    }
                    catch (System.Data.Entity.Validation.DbEntityValidationException err)
                    {
                        return(BadRequest("Error Adding User login while adding student " + err.Message));
                    }
                }
            }
            return(Ok(student));
        }
Example #13
0
        public static void Seed(this ModelBuilder modelBuilder)
        {
            var roleId  = new Guid("8D04DCE2-969A-435D-BBA4-DF3F325983DC");
            var adminId = new Guid("69BD714F-9576-45BA-B5B7-F00649BE00DE");

            modelBuilder.Entity <Role>().HasData(new Role
            {
                Id             = roleId,
                Name           = "admin",
                NormalizedName = "admin",
                Description    = "Administrator role"
            });

            var hasher = new PasswordHasher <User>();

            modelBuilder.Entity <User>().HasData(new User
            {
                Id                 = adminId,
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                PasswordHash       = hasher.HashPassword(null, "Abcd1234$"),
                SecurityStamp      = string.Empty,
                FirstName          = "Phuong",
                LastName           = "Phuong",
                Dob                = new DateTime(2020, 01, 31)
            });

            modelBuilder.Entity <IdentityUserRole <Guid> >().HasData(new IdentityUserRole <Guid>
            {
                RoleId = roleId,
                UserId = adminId
            });

            modelBuilder.Entity <Product>().HasData(
                new Product()
            {
                Prod_ID     = 1,
                Prod_Name   = "DDU-183 -TROPICAL POCKET",
                Price       = 300000,
                Quantity    = 2,
                DateCreate  = DateTime.Now,
                Description = "Áo tay ngắn xuất xứ Hàn Quốc",
                Status      = Status.Active
            },
                new Product()
            {
                Prod_ID     = 2,
                Prod_Name   = "Sweatshirt Madonna and Child",
                Price       = 450000,
                Quantity    = 1,
                DateCreate  = DateTime.Now,
                Description = "Vivarini",
                Status      = Status.Active
            },
                new Product()
            {
                Prod_ID     = 3,
                Prod_Name   = "CYPERNETIC ANGEL T-SHIRT",
                Price       = 320000,
                Quantity    = 1,
                DateCreate  = DateTime.Now,
                Description = "Chất liệu: 100% cotton Made in Việt Nam",
                Status      = Status.Active
            },
                new Product()
            {
                Prod_ID     = 4,
                Prod_Name   = "ANGRY JUNGLE T-SHIRT",
                Price       = 320000,
                Quantity    = 2,
                DateCreate  = DateTime.Now,
                Description = "Chất liệu: 100% cotton Made in Việt Nam",
                Status      = Status.Active
            },
                new Product()
            {
                Prod_ID     = 5,
                Prod_Name   = "ANGRY JUNGLE T-SHIRT",
                Price       = 320000,
                Quantity    = 2,
                DateCreate  = DateTime.Now,
                Description = "Chất liệu: 100% cotton Made in Việt Nam",
                Status      = Status.Active
            }
                );
            modelBuilder.Entity <ProductInSupplier>().HasData(
                new ProductInSupplier()
            {
                Prod_ID     = 1,
                Supplier_ID = 1
            },
                new ProductInSupplier()
            {
                Prod_ID     = 2,
                Supplier_ID = 1
            },
                new ProductInSupplier()
            {
                Prod_ID     = 3,
                Supplier_ID = 2
            },
                new ProductInSupplier()
            {
                Prod_ID     = 4,
                Supplier_ID = 2
            }
                );
        }
Example #14
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            const string ADMIN_ID = "b4280b6a-0613-4cbd-a9e6-f1701e926e73";
            const string ROLE_ID  = ADMIN_ID;
            const string password = "******";

            //var passwordFromSettings = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build()
            //    .GetSection("AdminCredentials")["Password"];
            //var emailFromSetting = new ConfigurationBuilder()
            //    .AddJsonFile("appsettings.json")
            //    .Build()
            //    .GetSection("AdminCredentials")["Username"];

            modelBuilder.Entity <IdentityRole>().HasData(
                new IdentityRole
            {
                Id             = ROLE_ID,
                Name           = "admin",
                NormalizedName = "ADMIN"
            },
                new IdentityRole
            {
                Id             = "b4280b6a-0613-4cbd-a9e6-f1701e926e74",
                Name           = "editor",
                NormalizedName = "EDITOR"
            },
                new IdentityRole
            {
                Id             = "b4280b6a-0613-4cbd-a9e6-f1701e926e75",
                Name           = "guest",
                NormalizedName = "GUEST"
            }
                );

            var hasher = new PasswordHasher <IdentityUser>();

            modelBuilder.Entity <IdentityUser>().HasData(new IdentityUser
            {
                Id                 = ADMIN_ID,
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                PasswordHash       = hasher.HashPassword(null, password),
                SecurityStamp      = string.Empty,
                ConcurrencyStamp   = "c8554266-b401-4519-9aeb-a9283053fc58"
            });

            modelBuilder.Entity <IdentityUserRole <string> >().HasData(new IdentityUserRole <string>
            {
                RoleId = ROLE_ID,
                UserId = ADMIN_ID
            });

            // Category Seed Data
            modelBuilder.Entity <Category>().HasData(
                new Category
            {
                Id   = 1,
                Name = "Fiction"
            },
                new Category
            {
                Id   = 2,
                Name = "Action"
            },
                new Category
            {
                Id   = 3,
                Name = "Crime"
            },
                new Category
            {
                Id   = 4,
                Name = "Adventure"
            },
                new Category
            {
                Id   = 5,
                Name = "Drama"
            },
                new Category
            {
                Id   = 6,
                Name = "Fantasy"
            },
                new Category
            {
                Id   = 7,
                Name = "Thrillers"
            },
                new Category
            {
                Id   = 8,
                Name = "General"
            },
                new Category
            {
                Id   = 9,
                Name = "Horror"
            },
                new Category
            {
                Id   = 10,
                Name = "Uncategorised"
            }
                );

            // Author Seed Data
            modelBuilder.Entity <Author>().HasData(
                new Author
            {
                Id               = 1,
                Name             = "Agatha Christie",
                ShortDescription = "Dame Agatha Mary Clarissa Christie, Lady Mallowan, DBE (née Miller; 15 September 1890 – 12 January 1976) " +
                                   "was an English writer known for her 66 detective novels and 14 short story collections, particularly those revolving around " +
                                   "fictional detectives Hercule Poirot and Miss Marple. She also wrote the world's longest-running play The Mousetrap and " +
                                   "six romances under the pen name Mary Westmacott. In 1971, she was appointed a Dame Commander of the Order of the British Empire " +
                                   "(DBE) for her contribution to literature",
                Popularity = false
            },
                new Author
            {
                Id               = 2,
                Name             = "Stephen King",
                ShortDescription = "Stephen Edwin King (born September 21, 1947) is an American author of horror, " +
                                   "supernatural fiction, suspense, and fantasy novels. His books have sold more than 350 million copies, " +
                                   "many of which have been adapted into feature films, miniseries, television series, and comic books. " +
                                   "King has published 61 novels (including seven under the pen name Richard Bachman) and six non-fiction books. " +
                                   "He has written approximately 200 short stories, most of which have been published in book collections.",
                Popularity = true
            },
                new Author
            {
                Id               = 3,
                Name             = "William Shakespeare",
                ShortDescription = "William Shakespeare (bapt. 26 April 1564 – 23 April 1616) was an English poet, playwright, and actor, " +
                                   "widely regarded as the greatest writer in the English language and the world's greatest dramatist. He is often called England's " +
                                   "national poet and the \"Bard of Avon\" (or simply \"the Bard\"). His extant works, including collaborations, consist of some " +
                                   "39 plays, 154 sonnets, two long narrative poems, and a few other verses, some of uncertain authorship. " +
                                   "His plays have been translated into every major living language and are performed more often than those of any other playwright",
                Popularity = false
            },
                new Author
            {
                Id               = 4,
                Name             = "J. K. Rowling",
                ShortDescription = "Joanne Rowling CH, OBE, HonFRSE, FRCPE, FRSL, (born 31 July 1965), better known by her pen name J. K. Rowling, " +
                                   "is a British author, film producer, television producer, screenwriter, and philanthropist. She is best known for writing the Harry Potter fantasy series," +
                                   "which has won multiple awards and sold more than 500 million copies, becoming the best-selling book series in history. The books are the basis of a popular " +
                                   "film series, over which Rowling had overall approval on the scripts and was a producer on the final films. She also writes crime fiction under the name Robert Galbraith.",
                Popularity = false
            },
                new Author
            {
                Id               = 5,
                Name             = "Leo Tolstoy",
                ShortDescription = "Count Lev Nikolayevich Tolstoy (9 September [O.S. 28 August] 1828 – 20 November [O.S. 7 November] 1910), usually referred to in English as Leo Tolstoy, " +
                                   "was a Russian writer who is regarded as one of the greatest authors of all time. He received multiple nominations for the Nobel Prize in Literature every year " +
                                   "from 1902 to 1906, and nominations for Nobel Peace Prize in 1901, 1902 and 1910, and the fact that he never won is a major Nobel prize controversy",
                Popularity = false
            },
                new Author
            {
                Id               = 6,
                Name             = "Paulo Coelho",
                ShortDescription = "Paulo Coelho de Souza (born 24 August 1947) is a Brazilian lyricist and novelist, best known for his novel The Alchemist. " +
                                   "In 2014, he uploaded his personal papers online to create a virtual Paulo Coelho Foundation",
                Popularity = false
            },
                new Author
            {
                Id               = 7,
                Name             = "Jeffrey Archer",
                ShortDescription = "Jeffrey Howard Archer (born 15 April 1940) is an English novelist, former politician, convicted perjurer, and peer of the realm. " +
                                   "Before becoming an author,Archer was a Member of Parliament(1969–1974), but did not seek re - election after a financial scandal that left him almost bankrupt." +
                                   "He revived his fortunes as a best - selling novelist; his books have sold around 330 million copies worldwide",
                Popularity = false
            },
                new Author
            {
                Id               = 8,
                Name             = "Ian Fleming",
                ShortDescription = "Ian Lancaster Fleming (28 May 1908 – 12 August 1964) was an English author, journalist and naval intelligence officer who is best known " +
                                   "for his James Bond series of spy novels. Fleming came from a wealthy family connected to the merchant bank Robert Fleming & Co., and his father was the " +
                                   "Member of Parliament for Henley from 1910 until his death on the Western Front in 1917. Educated at Eton, Sandhurst and, briefly, the universities of Munich and Geneva, " +
                                   "Fleming moved through several jobs before he started writing.",
                Popularity = false
            },
                new Author
            {
                Id               = 9,
                Name             = "Nicholas Sparks",
                ShortDescription = "Nicholas Charles Sparks (born December 31, 1965) is an American romance novelist and screenwriter. " +
                                   "He has published twenty novels and two non-fiction books. Several of his novels have become international bestsellers, " +
                                   "and eleven of his romantic-drama novels have been adapted to film all with multimillion-dollar box office grosses." +
                                   "His novels feature stories of tragic love with happy endings.",
                Popularity = false
            },
                new Author
            {
                Id               = 10,
                Name             = "Dan Brown",
                ShortDescription = "Daniel Gerhard Brown (born June 22, 1964) is an American author best known for his thriller novels," +
                                   " including the Robert Langdon novels Angels & Demons (2000), The Da Vinci Code (2003), The Lost Symbol (2009), Inferno (2013) and Origin (2017). " +
                                   "His novels are treasure hunts that usually take place over a period of 24 hours.[2] They feature recurring themes of cryptography, art, " +
                                   "and conspiracy theories. His books have been translated into 57 languages and, as of 2012, have sold over 200 million copies. " +
                                   "Three of them, Angels & Demons, The Da Vinci Code, and Inferno, have been adapted into films.",
                Popularity = false
            }
                );

            // Publisher Seed Data
            modelBuilder.Entity <Publisher>().HasData(
                new Publisher
            {
                Id      = 1,
                Name    = "William Morrow Paperbacks",
                Country = "Ireland"
            },
                new Publisher
            {
                Id      = 2,
                Name    = "Scholastic",
                Country = "USA"
            },
                new Publisher
            {
                Id      = 3,
                Name    = "Penguin Random House",
                Country = "Not known"
            },
                new Publisher
            {
                Id      = 4,
                Name    = "Hachette Livre",
                Country = "France"
            },
                new Publisher
            {
                Id      = 5,
                Name    = "HarperCollins",
                Country = "USA"
            },
                new Publisher
            {
                Id      = 6,
                Name    = "Macmillan Publishers",
                Country = "Germany"
            },
                new Publisher
            {
                Id      = 7,
                Name    = "Simon & Schuster",
                Country = "USA"
            },
                new Publisher
            {
                Id      = 8,
                Name    = "McGraw-Hill Education",
                Country = "USA"
            },
                new Publisher
            {
                Id      = 9,
                Name    = "Houghton Mifflin Harcourt",
                Country = "USA"
            },
                new Publisher
            {
                Id      = 10,
                Name    = "Pearson Education",
                Country = "USA"
            }
                );

            // Book Seed Data
            modelBuilder.Entity <Book>().HasData(
                new Book
            {
                Id            = 1,
                Title         = "Murder On The Orient Express",
                AuthorID      = 1,
                AuthorName    = "Agatha Cristie",
                BookType      = "Paperback",
                CategoryID    = 1,
                CategoryName  = "Fiction",
                Copies        = 100,
                Country       = "UK",
                Description   = "Book seed 1 Description",
                Dimensions    = "12x12x20",
                Genre         = "Fiction",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 586,
                Price         = 9.99,
                PublisherID   = 1,
                PublisherName = "William Morrow Paperbacks",
                Shipping      = "Free",
                Weight        = 0.49,
                YearOfIssue   = new DateTime(2020, 02, 29, 23, 29, 25),
                PhotoURL      = "AgathaCristie_MurderOnTheOrientExpress.jpg",
                SoldItems     = 20
            },
                new Book
            {
                Id           = 2,
                Title        = "The Dark Tower I: The Gunslinger",
                AuthorID     = 2,
                AuthorName   = "Stephen King",
                BookType     = "Paperback",
                CategoryID   = 6,
                CategoryName = "Fantasy",
                Copies       = 50,
                Country      = "",
                Description  = "Now a major motion picture starring Matthew McConaughey and Idris Elba. " +
                               "An impressive work of mythic magnitude that may turn out to be Stephen King's greatest literary " +
                               "achievement (The Atlanta Journal-Constitution), The Gunslinger is the first volume in the epic Dark Tower Series. " +
                               "A #1 national bestseller, The Gunslinger introduces readers to one of Stephen King's most powerful creations, " +
                               "Roland of Gilead: The Last Gunslinger. He is a haunting figure, a loner on a spellbinding journey into good and evil. " +
                               "In his desolate world, which mirrors our own in frightening ways, Roland tracks The Man in Black, encounters an enticing " +
                               "woman named Alice, and begins a friendship with the boy from New York named Jake. Inspired in part by the Robert Browning narrative poem," +
                               "Childe Roland to the Dark Tower Came, The Gunslinger is a compelling whirlpool of a story that draws one irretrievable to its center ( Milwaukee Sentinel ). " +
                               "It is brilliant and fresh...and will leave you panting for more ( Booklist ).",
                Dimensions    = "Not known",
                Genre         = "Fantasy",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 586,
                Price         = 11.48,
                PublisherID   = 2,
                PublisherName = "Scholastic",
                Shipping      = "Free",
                Weight        = 0.60,
                YearOfIssue   = new DateTime(2017, 06, 13, 00, 00, 00),
                PhotoURL      = "StephenKing_The_Dark_Tower.jpg",
                SoldItems     = 19
            },
                new Book
            {
                Id           = 3,
                Title        = "Dreamcatcher",
                AuthorID     = 2,
                AuthorName   = "Stephen King",
                BookType     = "Paperback",
                CategoryID   = 9,
                CategoryName = "Horror",
                Copies       = 20,
                Country      = "USA",
                Description  = "Once upon a time, in the haunted city of Derry (site of the classics \"It\" and \"Insomnia),\" four boys stood together " +
                               "and did a brave thing. Certainly a good thing, perhaps even a great thing. Something that changed them in ways they could never begin to understand. " +
                               "Twenty - five years later, the boys are now men with separate lives and separate troubles. But the ties endure. " +
                               "Each hunting season the foursome reunite in the woods of Maine. This year, a stranger stumbles into their camp, disoriented, " +
                               "mumbling something about lights in the sky. His incoherent ravings prove to be dis - turbingly prescient.Before long, these men will be plunged into a " +
                               "horrifying struggle with a creature from another world. Their only chance of survival is locked in their shared past-- and in the Dreamcatcher.",
                Dimensions    = "6.51 x 9.56 x 2.01 inches",
                Genre         = "Horror",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 624,
                Price         = 13.98,
                PublisherID   = 7,
                PublisherName = "Simon & Schuster",
                Shipping      = "Free",
                Weight        = 2.22,
                YearOfIssue   = new DateTime(2020, 02, 29, 23, 29, 25),
                PhotoURL      = "StephenKing_Dreamcatcher.jpg",
                SoldItems     = 3
            },
                new Book
            {
                Id            = 4,
                Title         = "The Green Mile",
                AuthorID      = 2,
                AuthorName    = "Stephen King",
                BookType      = "Paperback",
                CategoryID    = 8,
                CategoryName  = "General",
                Copies        = 150,
                Country       = "USA",
                Description   = "Stephen King's international bestselling - and highly acclaimed - novel, also a hugely successful film starring Tom Hanks",
                Dimensions    = "5.12 x 7.80 x 1.22 inches",
                Genre         = "Drama",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 480,
                Price         = 23.98,
                PublisherID   = 9,
                PublisherName = "Houghton Mifflin Harcourt",
                Shipping      = "Free",
                Weight        = 0.49,
                YearOfIssue   = new DateTime(2005, 03, 24, 00, 00, 00),
                PhotoURL      = "StephenKing-The-Green-Mile.jpg",
                SoldItems     = 4
            },
                new Book
            {
                Id           = 5,
                Title        = "Insomnia",
                AuthorID     = 2,
                AuthorName   = "Stephen King",
                BookType     = "Paperback",
                CategoryID   = 9,
                CategoryName = "Horror",
                Copies       = 200,
                Country      = "USA",
                Description  = "Old Ralph Roberts hasn't been sleeping well lately. Every night he wakes just a little bit earlier, and pretty soon, he thinks, " +
                               "he won't get any sleep at all. It wouldn't be so bad, except for the strange hallucinations he's been having. " +
                               "Or, at least, he hopes they are hallucinations--because here in Derry, one never can tell. Part of the \"Books That Take You Anywhere You Want To Go\" " +
                               "Summer Reading Promotion.",
                Dimensions    = "4.21 x 6.93 x 1.51 inches",
                Genre         = "Horror",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 663,
                Price         = 12.98,
                PublisherID   = 5,
                PublisherName = "HarperCollins",
                Shipping      = "Free",
                Weight        = 0.70,
                YearOfIssue   = new DateTime(1995, 09, 01, 00, 00, 00),
                PhotoURL      = "StephenKing_Insomnia.jpg",
                SoldItems     = 5
            },
                new Book
            {
                Id            = 6,
                Title         = "The Shining",
                AuthorID      = 2,
                AuthorName    = "Stephen King",
                BookType      = "Paperback",
                CategoryID    = 7,
                CategoryName  = "Thrillers",
                Copies        = 40,
                Country       = "USA",
                Description   = "Evil forces try to destroy a boy with psychic powers.",
                Dimensions    = "6.44 x 9.42 x 1.46 inches",
                Genre         = "Thriller",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 450,
                Price         = 33.48,
                PublisherID   = 5,
                PublisherName = "HarperCollins",
                Shipping      = "Free",
                Weight        = 1.68,
                YearOfIssue   = new DateTime(1990, 06, 01, 00, 00, 00),
                PhotoURL      = "StephenKing_The-Shining.jpg",
                SoldItems     = 6
            },
                new Book
            {
                Id           = 7,
                Title        = "Desperation",
                AuthorID     = 2,
                AuthorName   = "Stephen King",
                BookType     = "Paperback",
                CategoryID   = 9,
                CategoryName = "Horror",
                Copies       = 230,
                Country      = "USA",
                Description  = "Now repackaged with stunning new cover art, this #1 bestseller is a chilling story set in a lonely Nevada town " +
                               "where the evil embedded in the landscape is awesome--but so are the forces summoned to combat it. Reissue",
                Dimensions    = "4.22 x 6.86 x 1.52 inches",
                Genre         = "Horror",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 547,
                Price         = 22.98,
                PublisherID   = 10,
                PublisherName = "Pearson Education",
                Shipping      = "Free",
                Weight        = 0.49,
                YearOfIssue   = new DateTime(2003, 04, 01, 00, 00, 00),
                PhotoURL      = "StephenKing_Desperation.jpg",
                SoldItems     = 7
            },
                new Book
            {
                Id           = 8,
                Title        = "Othello",
                AuthorID     = 3,
                AuthorName   = "William Shakespeare",
                BookType     = "Paperback",
                CategoryID   = 5,
                CategoryName = "Drama",
                Copies       = 65,
                Country      = "UK",
                Description  = "Shakespeare's tragedy about Othello the Moor is presented in this freshly edited text with full explanatory notes, " +
                               "scene-by-scene plot summaries, an Introduction to reading Shakespeare's language, and much more. Reissue.",
                Dimensions    = "4.10 x 6.70 x 1.00 inches",
                Genre         = "Drama",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 368,
                Price         = 5.98,
                PublisherID   = 7,
                PublisherName = "Simon & Schuster",
                Shipping      = "Free",
                Weight        = 0.40,
                YearOfIssue   = new DateTime(2003, 12, 23, 00, 00, 00),
                PhotoURL      = "WilliamShakespeare_Othello.jpg",
                SoldItems     = 18
            },
                new Book
            {
                Id            = 9,
                Title         = "Harry Potter and the Philosopher's Stone",
                AuthorID      = 4,
                AuthorName    = "J. K. Rowling",
                BookType      = "Paperback",
                CategoryID    = 1,
                CategoryName  = "Fiction",
                Copies        = 131,
                Country       = "UK",
                Description   = "The one that started the biggest publishing phenomenon of our time",
                Dimensions    = "4.45 x 7.01 x 0.87 inches",
                Genre         = "Fiction",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 336,
                Price         = 9.98,
                PublisherID   = 1,
                PublisherName = "William Morrow Paperbacks",
                Shipping      = "Free",
                Weight        = 0.35,
                YearOfIssue   = new DateTime(2004, 07, 10, 00, 00, 00),
                PhotoURL      = "Harry-Potter-and-the-Philosopher-s-Stone-Rowling-J-K.jpg",
                SoldItems     = 17
            },
                new Book
            {
                Id           = 10,
                Title        = "The Alchemist",
                AuthorID     = 6,
                AuthorName   = "Paulo Coelho",
                BookType     = "Paperback",
                CategoryID   = 1,
                CategoryName = "Fiction",
                Copies       = 222,
                Country      = "UK",
                Description  = "This international bestseller about the shepherd boy Santiago who learns how to live " +
                               "his dreams includes an inspiring afterword by the author.",
                Dimensions    = "5.36 x 8.02 x 0.56 inches",
                Genre         = "Fiction",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 197,
                Price         = 6.98,
                PublisherID   = 1,
                PublisherName = "William Morrow Paperbacks",
                Shipping      = "Free",
                Weight        = 0.49,
                YearOfIssue   = new DateTime(2006, 04, 25, 00, 00, 00),
                PhotoURL      = "PauloCoelho_The-Alchemist.jpg",
                SoldItems     = 16
            },
                new Book
            {
                Id           = 11,
                Title        = "Eleven Minutes",
                AuthorID     = 6,
                AuthorName   = "Paulo Coelho",
                BookType     = "Paperback",
                CategoryID   = 1,
                CategoryName = "Fiction",
                Copies       = 34,
                Country      = "USA",
                Description  = "This gripping and daring novel by the author of the bestselling \"The Alchemist\" sensitively " +
                               "explores the sacred nature of sex and love. \"Sensual. . . for-adults - only fairytale.\"--\"Washington Post.\"",
                Dimensions    = "5.32 x 8.04 x 0.77 inches",
                Genre         = "Fiction",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 320,
                Price         = 12.48,
                PublisherID   = 5,
                PublisherName = "HarperCollins",
                Shipping      = "Free",
                Weight        = 0.52,
                YearOfIssue   = new DateTime(2005, 03, 29, 00, 00, 00),
                PhotoURL      = "PauloCoelho_Eleven-Minutes.jpg",
                SoldItems     = 8
            },
                new Book
            {
                Id           = 12,
                Title        = "Best Kept Secret (The Clifton Chronicles)",
                AuthorID     = 7,
                AuthorName   = "Jeffrey Archer",
                BookType     = "Paperback",
                CategoryID   = 1,
                CategoryName = "Fiction",
                Copies       = 87,
                Country      = "USA",
                Description  = "Jeffrey Archer's mesmerizing saga of the Clifton and Barrington families continues... " +
                               "1945, London. The vote in the House of Lords as to who should inherit the Barrington family fortune has " +
                               "ended in a tie. The Lord Chancellor's deciding vote will cast a long shadow on the lives of Harry Clifton " +
                               "and Giles Barrington. Harry returns to America to promote his latest novel, while his beloved Emma goes in " +
                               "search of the little girl who was found abandoned in her father's office on the night he was killed. " +
                               "When the general election is called, Giles Barrington has to defend his seat in the House of Commons and " +
                               "is horrified to discover who the Conservatives select to stand against him. But it is Sebastian Clifton, " +
                               "Harry and Emma's son, who ultimately influences his uncle's fate. In 1957, Sebastian wins a scholarship to " +
                               "Cambridge, and a new generation of the Clifton family marches onto the page. But after Sebastian is expelled " +
                               "from school, he unwittingly becomes caught up in an international art fraud involving a Rodin statue that is " +
                               "worth far more than the sum it raises at auction. Does he become a millionaire? Does he go to Cambridge? " +
                               "Is his life in danger?",
                Dimensions    = "4.32 x 6.04 x 0.57 inches",
                Genre         = "Fiction",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 423,
                Price         = 14.48,
                PublisherID   = 4,
                PublisherName = "Hachette Livre",
                Shipping      = "Free",
                Weight        = 0.57,
                YearOfIssue   = new DateTime(2014, 02, 18, 00, 00, 00),
                PhotoURL      = "ArcherJeffrey-Best-Kept-Secret.jpg",
                SoldItems     = 9
            },
                new Book
            {
                Id           = 13,
                Title        = "Casino Royale",
                AuthorID     = 8,
                AuthorName   = "Ian Fleming",
                BookType     = "Paperback",
                CategoryID   = 2,
                CategoryName = "Action",
                Copies       = 122,
                Country      = "UK",
                Description  = "In the novel that introduced James Bond to the world, Ian Fleming's agent 007 is dispatched to " +
                               "a French casino in Royale-les-Eaux. His mission? Bankrupt a ruthless Russian agent who's been on a bad luck streak " +
                               "at the baccarat table. One of SMERSH's most deadly operatives, the man known only as ?Le Chiffre, ? has been a prime " +
                               "target of the British Secret Service for years. If Bond can wipe out his bankroll, Le Chiffre will likely be ?retired? " +
                               "by his paymasters in Moscow. But what if the cards won't cooperate? After a brutal night at the gaming tables, " +
                               "Bond soon finds himself dodging would-be assassins, fighting off brutal torturers, and going all-in to save the life " +
                               "of his beautiful female counterpart, Vesper Lynd. Taut, tense, and effortlessly stylish, Ian Fleming's inaugural " +
                               "James Bond adventure has all the hallmarks that made the series a touchstone for a generation of readers.",
                Dimensions    = "4.32 x 6.04 x 0.57 inches",
                Genre         = "Action",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 486,
                Price         = 13.48,
                PublisherID   = 3,
                PublisherName = "Penguin Random House",
                Shipping      = "Free",
                Weight        = 0.30,
                YearOfIssue   = new DateTime(2012, 10, 16, 00, 00, 00),
                PhotoURL      = "IanFlemming_Casino_Royale.jpg",
                SoldItems     = 15
            },
                new Book
            {
                Id           = 14,
                Title        = "From Russia with Love",
                AuthorID     = 8,
                AuthorName   = "Ian Fleming",
                BookType     = "Paperback",
                CategoryID   = 2,
                CategoryName = "Action",
                Copies       = 10,
                Country      = "UK",
                Description  = "The lethal SMERSH organization in Russia has targeted Agent 007 for elimination. " +
                               "But when James Bond allows himself to be lured to Istanbul and walks willingly into a trap, " +
                               "a game of cross and double-cross ensues, with Bond as both the stakes and the prize.",
                Dimensions    = "5.12 x 7.72 x 0.53 inches",
                Genre         = "Action",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 272,
                Price         = 6.48,
                PublisherID   = 3,
                PublisherName = "Penguin Random House",
                Shipping      = "Free",
                Weight        = 0.42,
                YearOfIssue   = new DateTime(2002, 12, 31, 00, 00, 00),
                PhotoURL      = "IanFleming_From-Russia-with-Love.jpg",
                SoldItems     = 14
            },
                new Book
            {
                Id            = 15,
                Title         = "Every Breath",
                AuthorID      = 9,
                AuthorName    = "Nicholas Sparks",
                BookType      = "Paperback",
                CategoryID    = 1,
                CategoryName  = "Fiction",
                Copies        = 37,
                Country       = "UK",
                Description   = "No description is available.",
                Dimensions    = "4.10 x 6.70 x 1.00 inches",
                Genre         = "Romance",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 463,
                Price         = 8.98,
                PublisherID   = 4,
                PublisherName = "Hachette Livre",
                Shipping      = "Free",
                Weight        = 0.50,
                YearOfIssue   = new DateTime(2010, 03, 01, 00, 00, 00),
                PhotoURL      = "NicolasSparks_Every13Breath.jpg",
                SoldItems     = 13
            },
                new Book
            {
                Id           = 16,
                Title        = "The Last Song",
                AuthorID     = 9,
                AuthorName   = "Nicholas Sparks",
                BookType     = "Paperback",
                CategoryID   = 1,
                CategoryName = "Fiction",
                Copies       = 44,
                Country      = "UK",
                Description  = "#1 bestselling author Nicholas Sparks's new novel is at once a compelling family drama and a heartrending " +
                               "tale of young love.Seventeen year old Veronica \"Ronnie\" Miller's life was turned upside-down when her parents divorced " +
                               "and her father moved from New York City to Wilmington, North Carolina. Three years later, she remains angry and alientated " +
                               "from her parents, especially her father...until her mother decides it would be in everyone's best interest if she spent " +
                               "the summer in Wilmington with him. Ronnie's father, a former concert pianist and teacher, is living a quiet life in the " +
                               "beach town, immersed in creating a work of art that will become the centerpiece of a local church.The tale that unfolds is " +
                               "an unforgettable story of love on many levels--first love, love between parents and children -- that demonstrates, " +
                               "as only a Nicholas Sparks novel can, the many ways that love can break our hearts...and heal them.",
                Dimensions    = "4.10 x 6.70 x 1.00 inches",
                Genre         = "Romance",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 463,
                Price         = 8.98,
                PublisherID   = 4,
                PublisherName = "Hachette Livre",
                Shipping      = "Free",
                Weight        = 0.50,
                YearOfIssue   = new DateTime(2010, 03, 01, 00, 00, 00),
                PhotoURL      = "NicolasSparks_The-Last-Song.jpg",
                SoldItems     = 10
            },
                new Book
            {
                Id           = 17,
                Title        = "The Da Vinci Code",
                AuthorID     = 10,
                AuthorName   = "Dan Brown",
                BookType     = "Paperback",
                CategoryID   = 7,
                CategoryName = "Thrillers",
                Copies       = 111,
                Country      = "USA",
                Description  = "PREMIUM MASS MARKET EDITION #1 Worldwide Bestseller" +
                               "--More Than 80 Million Copies Sold As millions of readers around the globe have already discovered, " +
                               "The Da Vinci Code is a reading experience unlike any other.Simultaneously lightning - paced, intelligent," +
                               "and intricately layered with remarkable research and detail, Dan Brown's novel is a thrilling masterpiece" +
                               "--from its opening pages to its stunning conclusion.",
                Dimensions    = "4.28 x 7.54 x 1.33 inches",
                Genre         = "Thriller",
                Edition       = 2,
                Language      = "English",
                NumberOfPages = 608,
                Price         = 12.98,
                PublisherID   = 6,
                PublisherName = "Macmillan Publishers",
                Shipping      = "Free",
                Weight        = 0.49,
                YearOfIssue   = new DateTime(2009, 03, 31, 00, 00, 00),
                PhotoURL      = "Dan-Brown_The-Da-Vinci-Code.jpg",
                SoldItems     = 12
            },
                new Book
            {
                Id           = 18,
                Title        = "Inferno",
                AuthorID     = 10,
                AuthorName   = "Dan Brown",
                BookType     = "Paperback",
                CategoryID   = 7,
                CategoryName = "Thrillers",
                Copies       = 100,
                Country      = "USA",
                Description  = "#1 WORLDWIDE BESTSELLER Harvard professor of symbology Robert Langdon awakens in an Italian hospital, " +
                               "disoriented and with no recollection of the past thirty-six hours, including the origin of the macabre object hidden " +
                               "in his belongings. With a relentless female assassin trailing them through Florence, he and his resourceful doctor, " +
                               "Sienna Brooks, are forced to flee. Embarking on a harrowing journey, they must unravel a series of codes, which are " +
                               "the work of a brilliant scientist whose obsession with the end of the world is matched only by his passion for one of the " +
                               "most influential masterpieces ever written, Dante Alighieri's \"The Inferno.\" Dan Brown has raised the bar yet again, " +
                               "combining classical Italian art, history, and literature with cutting-edge science in this sumptuously entertaining thriller.",
                Dimensions    = "4.28 x 7.54 x 1.33 inches",
                Genre         = "Thriller",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 648,
                Price         = 5.98,
                PublisherID   = 6,
                PublisherName = "Macmillan Publishers",
                Shipping      = "Free",
                Weight        = 0.50,
                YearOfIssue   = new DateTime(2014, 06, 06, 00, 00, 00),
                PhotoURL      = "Dan-Brown_Inferno.jpg",
                SoldItems     = 11
            },
                new Book
            {
                Id            = 19,
                Title         = "The Thirteen Problems",
                AuthorID      = 1,
                AuthorName    = "Agatha Christie",
                BookType      = "Paperback",
                CategoryID    = 7,
                CategoryName  = "Thrillers",
                Copies        = 300,
                Country       = "UK",
                Description   = "No description is available.",
                Dimensions    = "5.82 x 8.52 x 0.94 inches",
                Genre         = "Thriller",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 256,
                Price         = 17.48,
                PublisherID   = 7,
                PublisherName = "Simon & Schuster",
                Shipping      = "Free",
                Weight        = 0.35,
                YearOfIssue   = new DateTime(2016, 01, 01, 00, 00, 00),
                PhotoURL      = "AgathaCristie_13_Problems.jpg",
                SoldItems     = 11
            },
                new Book
            {
                Id           = 20,
                Title        = "The A.B.C. Murders",
                AuthorID     = 1,
                AuthorName   = "Agatha Christie",
                BookType     = "Paperback",
                CategoryID   = 7,
                CategoryName = "Thrillers",
                Copies       = 70,
                Country      = "UK",
                Description  = "When Alice Ascher is murdered in Andover, Hercule Poirot is already onto the clues. " +
                               "Alphabetically speaking, it's one down, 25 to go. This classic mystery is now repackaged in a digest-sized " +
                               "edition for young adults. Reissue.",
                Dimensions    = "5.82 x 8.52 x 0.94 inches",
                Genre         = "Thriller",
                Edition       = 1,
                Language      = "English",
                NumberOfPages = 256,
                Price         = 8.48,
                PublisherID   = 7,
                PublisherName = "Simon & Schuster",
                Shipping      = "Free",
                Weight        = 0.99,
                YearOfIssue   = new DateTime(2006, 09, 30, 00, 00, 00),
                PhotoURL      = "AgathaCristie_TheABCMurders.jpg",
                SoldItems     = 11
            }
                );

            base.OnModelCreating(modelBuilder);
        }
        public MainWindowVM(StatusBlinker statusBlinker, InMatchTrackerStateVM inMatchState, ConfigModel config, DraftingVM draftingVM,
                            IMapper mapper,
                            ProcessMonitor processMonitor,
                            ServerApiCaller api,
                            StartupShortcutManager startupManager,
                            MtgaResourcesLocator resourcesLocator,
                            FileMonitor fileMonitor,
                            DraftCardsPicker draftHelper,
                            ReaderMtgaOutputLog readerMtgaOutputLog,
                            InGameTracker2 inMatchTracker,
                            ExternalProviderTokenManager tokenManager,
                            PasswordHasher passwordHasher,
                            CacheSingleton <Dictionary <string, DraftRatings> > draftRatings,
                            DraftHelperRunner draftHelperRunner,
                            //IEmailProvider emailProvider,
                            ICollection <Card> allCards)
        {
            // Set the status blinker reference
            StatusBlinker = statusBlinker;
            // Set the network status emission handler
            StatusBlinker.EmitStatus += status => { NetworkStatus = status; };

            InMatchState        = inMatchState;
            Config              = config;
            DraftingVM          = draftingVM;
            Mapper              = mapper;
            ProcessMonitor      = processMonitor;
            Api                 = api;
            StartupManager      = startupManager;
            ResourcesLocator    = resourcesLocator;
            FileMonitor         = fileMonitor;
            DraftHelper         = draftHelper;
            ReaderMtgaOutputLog = readerMtgaOutputLog;
            InMatchTracker      = inMatchTracker;
            TokenManager        = tokenManager;
            PasswordHasher      = passwordHasher;
            DraftRatings        = draftRatings;
            DraftHelperRunner   = draftHelperRunner;
            //this.emailProvider = emailProvider;
            AllCards = allCards;

            // Set the initial state of the compression
            SetCompressedCardList(Config.CardListCollapsed);

            // Set the library order from the config
            OrderLibraryCardsBy = config.OrderLibraryCardsBy == "Converted Mana Cost"
                ? CardsListOrder.ManaCost
                : CardsListOrder.DrawChance;

            // Create the opponent window view model
            OpponentWindowVM = new OpponentWindowVM("Opponent Cards", this);

            // Subscribe to property changes
            PropertyChanged += OnPropertyChanged;

            // Set the animated icon state
            AnimatedIcon = Config?.AnimatedIcon ?? false;

            // Set the initial window settings
            PositionTop   = WindowSettings?.Position.Y ?? 0;
            PositionLeft  = WindowSettings?.Position.X ?? 0;
            WindowOpacity = WindowSettings?.Opacity ?? 0.9;
            WindowTopmost = WindowSettings?.Topmost ?? true;

            // Set the initial window size
            WindowWidth = WindowSettings != null && WindowSettings.Size.X > double.Epsilon
                ? WindowSettings.Size.X
                : 340;
            WindowHeight = WindowSettings != null && WindowSettings.Size.Y > double.Epsilon
                ? WindowSettings.Size.Y
                : 500;
        }
Example #16
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //Product

            #region Products

            // modelBuilder.Entity<Product>()
            //     .HasData(
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         },
            //         new Product
            //         {
            //             Id = 1, Name = "Хлопковая футболка", Slug = "Хлопковая футболка",
            //             ShortDescription =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Description =
            //                 "Футболка универсального серого оттенка — классическая вещь в повседневном гардеробе. Для создания модели использовали мягкое хлопковое джерси. Материал слегка тянется и комфортно облегает тело. Единственный декор — миниатюрная знаковая вышивка в виде игрока в поло. Ральф Лорен включил изделие в классическую коллекцию.",
            //             Specification = null,
            //             SpecialPriceStart = null,
            //             SpecialPriceEnd = null,
            //             Price = 3825,
            //             OldPrice = 4290,
            //             IsFeatured = true,
            //             IsAllowToOrder = true,
            //             Brand = new Brand {Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now},
            //             TaxClass = new TaxClass {Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now},
            //             UnitType = UnitType.Thing,
            //             GenderType = GenderType.Female,
            //             CreationDate = DateTime.Now
            //         }
            //     );

            #endregion

            //Brand
            modelBuilder.Entity <Brand>()
            .HasData(
                new Brand {
                Id = 1, Name = "Nike", Description = "Nike", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 2, Name = "Adidas", Description = "Adidas", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 3, Name = "Polo", Description = "Polo", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 4, Name = "Balmain", Description = "Balmain", CreationDate = DateTime.Now
            },
                new Brand
            {
                Id = 5, Name = "Bottega Veneta", Description = "Bottega Veneta", CreationDate = DateTime.Now
            },
                new Brand
            {
                Id           = 6, Name = "Brunello Cucinelli", Description = "Brunello Cucinelli",
                CreationDate = DateTime.Now
            },
                new Brand {
                Id = 7, Name = "Jil Sander", Description = "Jil Sander", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 8, Name = "Gucci", Description = "Gucci", CreationDate = DateTime.Now
            },
                new Brand
            {
                Id = 9, Name = "Ralph Lauren", Description = "Ralph Lauren", CreationDate = DateTime.Now
            },
                new Brand
            {
                Id           = 10, Name = "Alexander McQueen", Description = "Alexander McQueen",
                CreationDate = DateTime.Now
            },
                new Brand {
                Id = 11, Name = "Prada", Description = "Prada", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 12, Name = "Off-White", Description = "Off-White", CreationDate = DateTime.Now
            },
                new Brand {
                Id = 13, Name = "Versace", Description = "Versace", CreationDate = DateTime.Now
            }
                );

            //Category
            modelBuilder.Entity <Category>()
            .HasData(
                new Category {
                Id = 1, Name = "Блуза", Slug = "Блуза", CreationDate = DateTime.Now
            },
                new Category {
                Id = 2, Name = "Рубашка", Slug = "Рубашка", CreationDate = DateTime.Now
            },
                new Category {
                Id = 3, Name = "Брюки", Slug = "Брюки", CreationDate = DateTime.Now
            },
                new Category {
                Id = 4, Name = "Бриджи", Slug = "Бриджи", CreationDate = DateTime.Now
            },
                new Category {
                Id = 5, Name = "Лосины", Slug = "Лосины", CreationDate = DateTime.Now
            },
                new Category {
                Id = 6, Name = "Джинсы", Slug = "Джинсы", CreationDate = DateTime.Now
            },
                new Category {
                Id = 7, Name = "Шорты", Slug = "Шорты", CreationDate = DateTime.Now
            },
                new Category {
                Id = 8, Name = "Юбка", Slug = "Юбка", CreationDate = DateTime.Now
            },
                new Category {
                Id = 9, Name = "Комбинезон", Slug = "Комбинезон", CreationDate = DateTime.Now
            },
                new Category {
                Id = 10, Name = "Джемпер", Slug = "Джемпер", CreationDate = DateTime.Now
            },
                new Category {
                Id = 11, Name = "Свитер", Slug = "Свитер", CreationDate = DateTime.Now
            },
                new Category {
                Id = 12, Name = "Гольф", Slug = "Гольф", CreationDate = DateTime.Now
            },
                new Category {
                Id = 13, Name = "Пуловер", Slug = "Пуловер", CreationDate = DateTime.Now
            },
                new Category {
                Id = 14, Name = "Кофта", Slug = "Кофта", CreationDate = DateTime.Now
            },
                new Category {
                Id = 15, Name = "Кардиган", Slug = "Кардиган", CreationDate = DateTime.Now
            },
                new Category {
                Id = 16, Name = "Жакет", Slug = "Жакет", CreationDate = DateTime.Now
            },
                new Category {
                Id = 17, Name = "Пиджак", Slug = "Пиджак", CreationDate = DateTime.Now
            },
                new Category {
                Id = 18, Name = "Футболка", Slug = "Футболка", CreationDate = DateTime.Now
            },
                new Category {
                Id = 19, Name = "Майка", Slug = "Майка", CreationDate = DateTime.Now
            },
                new Category {
                Id = 20, Name = "Поло", Slug = "Поло", CreationDate = DateTime.Now
            },
                new Category
            {
                Id           = 21, Name = "Футболка с длинным рукавом", Slug = "Футболка с длинным рукавом",
                CreationDate = DateTime.Now
            },
                new Category {
                Id = 22, Name = "Тенниска", Slug = "Тенниска", CreationDate = DateTime.Now
            },
                new Category {
                Id = 23, Name = "Реглан", Slug = "Реглан", CreationDate = DateTime.Now
            },
                new Category {
                Id = 24, Name = "Платье", Slug = "Платье", CreationDate = DateTime.Now
            },
                new Category {
                Id = 25, Name = "Ветровка", Slug = "Ветровка", CreationDate = DateTime.Now
            }
                );

            //TaxClass
            modelBuilder.Entity <TaxClass>()
            .HasData(
                new TaxClass {
                Id = 1, Name = "0%", Interest = 0, CreationDate = DateTime.Now
            },
                new TaxClass {
                Id = 2, Name = "10%", Interest = 10, CreationDate = DateTime.Now
            },
                new TaxClass {
                Id = 3, Name = "18%", Interest = 18, CreationDate = DateTime.Now
            }
                );

            //Warehouse
            modelBuilder.Entity <Warehouse>()
            .HasData(
                new Warehouse
            {
                Id           = 1, Name = "Основной", Vendor = "452000", Address = "г. Белебей, ул. Красноармейская 125",
                CreationDate = DateTime.Now
            },
                new Warehouse
            {
                Id           = 2, Name = "Основной (запасной)", Vendor = "450000", Address = "г. Уфа, ул. Советская 25",
                CreationDate = DateTime.Now
            }
                );

            //ApplicationUser
            ApplicationUser user = new ApplicationUser()
            {
                Id             = "b74ddd14-6340-4840-95c2-db12554843e5",
                UserName       = "******",
                Email          = "*****@*****.**",
                LockoutEnabled = false,
                PhoneNumber    = "1234567890"
            };

            var passwordHasher = new PasswordHasher <ApplicationUser>();

            modelBuilder.Entity <ApplicationUser>().HasData(
                new ApplicationUser
            {
                Id                 = "b74ddd14-6340-4840-95c2-db12554843e5",
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                EmailConfirmed     = true,
                PasswordHash       = passwordHasher.HashPassword(null, "Admin1234"),
                SecurityStamp      = string.Empty
            }
                );

            //IdentityRole
            modelBuilder.Entity <IdentityRole>().HasData(
                new IdentityRole()
            {
                Id             = "fab4fac1-c546-41de-aebc-a14da6895711", Name = "Admin", ConcurrencyStamp = "1",
                NormalizedName = "Admin"
            },
                new IdentityRole()
            {
                Id             = "c7b013f0-5201-4317-abd8-c211f91b7330", Name = "User", ConcurrencyStamp = "2",
                NormalizedName = "User"
            }
                );

            //RoleUser
            modelBuilder.Entity <IdentityUserRole <string> >().HasData(
                new IdentityUserRole <string>()
            {
                RoleId = "fab4fac1-c546-41de-aebc-a14da6895711", UserId = "b74ddd14-6340-4840-95c2-db12554843e5"
            }
                );
        }
Example #17
0
        private static UserInfo GetUser(string userName, string password, string provider, string accessToken, out bool viaEmail)
        {
            viaEmail = true;
            var      action = MessageAction.LoginFailViaApi;
            UserInfo user   = null;

            try
            {
                if (string.IsNullOrEmpty(provider) || provider == "email")
                {
                    userName.ThrowIfNull(new ArgumentException(@"userName empty", "userName"));
                    password.ThrowIfNull(new ArgumentException(@"password empty", "password"));

                    int counter;
                    int.TryParse(Cache.Get <String>("loginsec/" + userName), out counter);
                    if (++counter > SetupInfo.LoginThreshold && !SetupInfo.IsSecretEmail(userName))
                    {
                        throw new Authorize.BruteForceCredentialException();
                    }
                    Cache.Insert("loginsec/" + userName, counter.ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));

                    if (EnableLdap)
                    {
                        var localization    = new LdapLocalization(Resource.ResourceManager);
                        var ldapUserManager = new LdapUserManager(localization);

                        ldapUserManager.TryGetAndSyncLdapUserInfo(userName, password, out user);
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        var passwordHash = PasswordHasher.GetClientPassword(password);
                        user = CoreContext.UserManager.GetUsersByPasswordHash(
                            CoreContext.TenantManager.GetCurrentTenant().TenantId,
                            userName,
                            passwordHash);
                    }

                    if (user == null || !CoreContext.UserManager.UserExists(user.ID))
                    {
                        throw new Exception("user not found");
                    }

                    Cache.Insert("loginsec/" + userName, (--counter).ToString(CultureInfo.InvariantCulture), DateTime.UtcNow.Add(TimeSpan.FromMinutes(1)));
                }
                else
                {
                    viaEmail = false;

                    action = MessageAction.LoginFailViaApiSocialAccount;
                    var thirdPartyProfile = ProviderManager.GetLoginProfile(provider, accessToken);
                    userName = thirdPartyProfile.EMail;

                    user = LoginWithThirdParty.GetUserByThirdParty(thirdPartyProfile);
                }
            }
            catch (Authorize.BruteForceCredentialException)
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, MessageAction.LoginFailBruteForce);
                throw new AuthenticationException("Login Fail. Too many attempts");
            }
            catch
            {
                MessageService.Send(Request, !string.IsNullOrEmpty(userName) ? userName : AuditResource.EmailNotSpecified, action);
                throw new AuthenticationException("User authentication failed");
            }

            var tenant   = CoreContext.TenantManager.GetCurrentTenant();
            var settings = IPRestrictionsSettings.Load();

            if (settings.Enable && user.ID != tenant.OwnerId && !IPSecurity.IPSecurity.Verify(tenant))
            {
                throw new IPSecurityException();
            }

            return(user);
        }
        // seed data:
        //USER
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //delete behaviors: Restrict, Cascade, SetNutll
            //delete behavior for <Genre>()
            modelBuilder.Entity <Genre>()
            .HasMany(g => g.Samples)
            .WithOne(s => s.Genre)
            .HasForeignKey(s => s.GenreId)
            .OnDelete(DeleteBehavior.Restrict);

            //delete behavior for <Sample>()
            modelBuilder.Entity <Sample>()
            .HasOne(s => s.Genre)
            .WithMany(g => g.Samples)
            .HasForeignKey(s => s.GenreId)
            .OnDelete(DeleteBehavior.Restrict);

            base.OnModelCreating(modelBuilder);
            ApplicationUser user = new ApplicationUser
            {
                ScreenName         = "Joey",
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = "7f434309-a4d9-48e9-9ebb-8803db794577",
                Id = "00000000-ffff-ffff-ffff-ffffffffffff"
            };

            var passwordHash = new PasswordHasher <ApplicationUser>();

            user.PasswordHash = passwordHash.HashPassword(user, "Password");
            modelBuilder.Entity <ApplicationUser>().HasData(user);

            //GENRE
            modelBuilder.Entity <Genre>().HasData(
                // Live Sound
                new Genre()
            {
                Id   = 1,
                Name = "Rock"
            },
                new Genre()
            {
                Id   = 2,
                Name = "Jazz"
            },
                new Genre()
            {
                Id   = 3,
                Name = "Blues"
            },
                new Genre()
            {
                Id   = 4,
                Name = "Funk"
            },
                new Genre()
            {
                Id   = 5,
                Name = "Dub"
            },
                new Genre()
            {
                Id   = 6,
                Name = "Reggae"
            },
                new Genre()
            {
                Id   = 7,
                Name = "Folk"
            },
                new Genre()
            {
                Id   = 8,
                Name = "Heavy Metal"
            },

                // Hip Hop / R&B
                new Genre()
            {
                Id   = 9,
                Name = "Hip Hop"
            },
                new Genre()
            {
                Id   = 10,
                Name = "Trap"
            },
                new Genre()
            {
                Id   = 11,
                Name = "R&B"
            },
                new Genre()
            {
                Id   = 12,
                Name = "Soul"
            },
                new Genre()
            {
                Id   = 13,
                Name = "Future Bass"
            },
                new Genre()
            {
                Id   = 14,
                Name = "Glitch Hop"
            },

                // EDM / Pop
                new Genre()
            {
                Id   = 15,
                Name = "Pop"
            }, new Genre()
            {
                Id   = 16,
                Name = "EDM"
            },
                new Genre()
            {
                Id   = 17,
                Name = "Trance"
            },
                new Genre()
            {
                Id   = 18,
                Name = "Psytrance"
            }, new Genre()
            {
                Id   = 19,
                Name = "Future House"
            },
                new Genre()
            {
                Id   = 20,
                Name = "Tropical House"
            },

                // House/Techno
                new Genre()
            {
                Id   = 21,
                Name = "Techno"
            },
                new Genre()
            {
                Id   = 22,
                Name = "House"
            },
                new Genre()
            {
                Id   = 23,
                Name = "Tech House"
            },
                new Genre()
            {
                Id   = 24,
                Name = "Deep House"
            },
                new Genre()
            {
                Id   = 25,
                Name = "Disco"
            },
                new Genre()
            {
                Id   = 26,
                Name = "Electro"
            },
                new Genre()
            {
                Id   = 27,
                Name = "UK Garage"
            },

                // Electronic
                new Genre()
            {
                Id   = 28,
                Name = "Downtempo"
            },
                new Genre()
            {
                Id   = 29,
                Name = "Ambient"
            },
                new Genre()
            {
                Id   = 30,
                Name = "IDM"
            },
                new Genre()
            {
                Id   = 31,
                Name = "Experimental"
            },
                new Genre()
            {
                Id   = 32,
                Name = "Trip Hop"
            },

                // Bass
                new Genre()
            {
                Id   = 33,
                Name = "Drum & Bass"
            },
                new Genre()
            {
                Id   = 34,
                Name = "Breakbeat"
            },
                new Genre()
            {
                Id   = 35,
                Name = "Jungle"
            },
                new Genre()
            {
                Id   = 36,
                Name = "Dubstep"
            });

            modelBuilder.Entity <Sample>().HasData(
                new Sample()
            {
                SampleName        = "Test Sample",
                SamplePath        = "/AudioFiles",
                ApplicationUserId = user.Id,
                Id           = 1,
                SampleTypeId = 1,
                MusicKeyId   = 1,
                GenreId      = 1,
                BPM          = 100
            });
            //TYPE
            modelBuilder.Entity <SampleType>().HasData(
                new SampleType()
            {
                Id   = 1,
                Name = "Drums"
            },
                new SampleType()
            {
                Id   = 2,
                Name = "Bass"
            },
                new SampleType()
            {
                Id   = 3,
                Name = "Synth"
            },
                new SampleType()
            {
                Id   = 4,
                Name = "Percussion"
            },
                new SampleType()
            {
                Id   = 5,
                Name = "Vocals"
            },
                new SampleType()
            {
                Id   = 6,
                Name = "Guitar"
            },
                new SampleType()
            {
                Id   = 7,
                Name = "Leads"
            },
                new SampleType()
            {
                Id   = 8,
                Name = "Melody"
            },
                new SampleType()
            {
                Id   = 9,
                Name = "Ryhthm"
            },
                new SampleType()
            {
                Id   = 10,
                Name = "MusicKeys"
            },
                new SampleType()
            {
                Id   = 11,
                Name = "Risers"
            },
                new SampleType()
            {
                Id   = 12,
                Name = "Downers"
            },
                new SampleType()
            {
                Id   = 13,
                Name = "Transitions"
            },
                new SampleType()
            {
                Id   = 14,
                Name = "808"
            },
                new SampleType()
            {
                Id   = 15,
                Name = "Piano"
            },
                new SampleType()
            {
                Id   = 16,
                Name = "Arp"
            },
                new SampleType()
            {
                Id   = 17,
                Name = "Brass & Woodwinds"
            },
                new SampleType()
            {
                Id   = 18,
                Name = "FX"
            },
                new SampleType()
            {
                Id   = 19,
                Name = "Pads"
            },
                new SampleType()
            {
                Id   = 20,
                Name = "Stabs"
            },
                new SampleType()
            {
                Id   = 21,
                Name = "Bells"
            },
                new SampleType()
            {
                Id   = 22,
                Name = "Textures"
            },
                new SampleType()
            {
                Id   = 23,
                Name = "Impacts"
            },
                new SampleType()
            {
                Id   = 24,
                Name = "Grooves"
            },
                new SampleType()
            {
                Id   = 25,
                Name = "Strings"
            },
                new SampleType()
            {
                Id   = 26,
                Name = "Sub"
            },
                new SampleType()
            {
                Id   = 27,
                Name = "Kicks"
            },
                new SampleType()
            {
                Id   = 28,
                Name = "Snares"
            },
                new SampleType()
            {
                Id   = 29,
                Name = "Hats"
            },
                new SampleType()
            {
                Id   = 30,
                Name = "Toms"
            },
                new SampleType()
            {
                Id   = 31,
                Name = "Claps"
            },
                new SampleType()
            {
                Id   = 32,
                Name = "Shakers"
            },
                new SampleType()
            {
                Id   = 33,
                Name = "Crashes"
            },
                new SampleType()
            {
                Id   = 34,
                Name = "Cymbals"
            },
                new SampleType()
            {
                Id   = 35,
                Name = "Fills"
            });

            //KEY
            modelBuilder.Entity <MusicKey>().HasData(
                new MusicKey()
                // Root MusicKeys
            {
                Id   = 1,
                Name = "C"
            },
                new MusicKey()
            {
                Id   = 2,
                Name = "D"
            },
                new MusicKey()
            {
                Id   = 3,
                Name = "E"
            },
                new MusicKey()
            {
                Id   = 4,
                Name = "F"
            },
                new MusicKey()
            {
                Id   = 5,
                Name = "G"
            },
                new MusicKey()
            {
                Id   = 6,
                Name = "A"
            },
                new MusicKey()
            {
                Id   = 7,
                Name = "B"
            },
                // Minor Keys
                new MusicKey()
            {
                Id   = 8,
                Name = "Cm"
            },
                new MusicKey()
            {
                Id   = 9,
                Name = "Dm"
            },
                new MusicKey()
            {
                Id   = 10,
                Name = "Em"
            },
                new MusicKey()
            {
                Id   = 11,
                Name = "Fm"
            },
                new MusicKey()
            {
                Id   = 12,
                Name = "Gm"
            },
                new MusicKey()
            {
                Id   = 13,
                Name = "Am"
            },
                new MusicKey()
            {
                Id   = 14,
                Name = "Bm"
            },
                // Flats
                new MusicKey()
            {
                Id   = 15,
                Name = "Db"
            },
                new MusicKey()
            {
                Id   = 16,
                Name = "Eb"
            },
                new MusicKey()
            {
                Id   = 17,
                Name = "Gb"
            },
                new MusicKey()
            {
                Id   = 18,
                Name = "Ab"
            },
                new MusicKey()
            {
                Id   = 19,
                Name = "Bb"
            },
                // Sharps
                new MusicKey()
            {
                Id   = 20,
                Name = "C#"
            },
                new MusicKey()
            {
                Id   = 21,
                Name = "D#"
            },
                new MusicKey()
            {
                Id   = 22,
                Name = "F#"
            }, new MusicKey()
            {
                Id   = 23,
                Name = "G#"
            }, new MusicKey()
            {
                Id   = 24,
                Name = "A#"
            });
        }
Example #19
0
        public static async void Seed(IServiceProvider serviceProvider)
        {
            using var scope         = serviceProvider.CreateScope();
            await using var context = scope.ServiceProvider.GetService <ApplicationDbContext>();

            // It should be uncomment when using UseSqlServer() settings or any other providers.
            // This is should not be used when UseInMemoryDatabase()
            // await context!.Database.MigrateAsync();

            var roles = AppData.Roles.ToArray();

            foreach (var role in roles)
            {
                var roleManager = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >();
                if (!context !.Roles.Any(r => r.Name == role))
                {
                    await roleManager.CreateAsync(new ApplicationRole { Name = role, NormalizedName = role.ToUpper() });
                }
            }

            #region developer

            var developer1 = new ApplicationUser
            {
                Email                  = "*****@*****.**",
                NormalizedEmail        = "*****@*****.**",
                UserName               = "******",
                FirstName              = "Microservice",
                LastName               = "Administrator",
                NormalizedUserName     = "******",
                PhoneNumber            = "+79000000000",
                EmailConfirmed         = true,
                PhoneNumberConfirmed   = true,
                SecurityStamp          = Guid.NewGuid().ToString("D"),
                ApplicationUserProfile = new ApplicationUserProfile
                {
                    CreatedAt   = DateTime.Now,
                    CreatedBy   = "SEED",
                    Permissions = new List <MicroservicePermission>
                    {
                        new()
                        {
                            CreatedAt   = DateTime.Now,
                            CreatedBy   = "SEED",
                            PolicyName  = "Logs:UserRoles:View",
                            Description = "Access policy for Logs controller user view"
                        }
                    }
                }
            };

            if (!context !.Users.Any(u => u.UserName == developer1.UserName))
            {
                var password = new PasswordHasher <ApplicationUser>();
                var hashed   = password.HashPassword(developer1, "123qwe!@#");
                developer1.PasswordHash = hashed;
                var userStore = scope.ServiceProvider.GetService <ApplicationUserStore>();
                var result    = await userStore !.CreateAsync(developer1);
                if (!result.Succeeded)
                {
                    throw new InvalidOperationException("Cannot create account");
                }

                var userManager = scope.ServiceProvider.GetService <UserManager <ApplicationUser> >();
                foreach (var role in roles)
                {
                    var roleAdded = await userManager !.AddToRoleAsync(developer1, role);
                    if (roleAdded.Succeeded)
                    {
                        await context.SaveChangesAsync();
                    }
                }
            }
            #endregion

            await context.SaveChangesAsync();
        }
Example #20
0
 private void CriptografyPassword(string password)
 {
     Password = PasswordHasher.Hash(password);
 }
Example #21
0
        public void InitWithNoAdlerMod()
        {
            var actual = PasswordHasher.GetHash("password", someSalt);

            Assert.NotNull(actual);
        }
Example #22
0
        public void InitialiseTestDataObjects()
        {
            var hasher = new PasswordHasher <User>();

            _yin = new User
            {
                UserName           = "******",
                FirstName          = "Yin",
                LastName           = "Wang",
                DateOfBirth        = new DateTime(1994, 12, 23),
                PhoneNumber        = "0279284492",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "00-0000-0000000-000",
                ResetToken         = "",
                CanReset           = false
            };
            _yin.HashedPassword = hasher.HashPassword(_yin, "password");

            _teresa = new User
            {
                UserName           = "******",
                FirstName          = "Teresa",
                LastName           = "Green",
                DateOfBirth        = new DateTime(1996, 02, 12),
                PhoneNumber        = "0228937228",
                Email              = "*****@*****.**",
                MedicalInformation = "Vegan, Gluten-Free, Lactose Intolerant",
                BankAccount        = "12-3456-1234567-123",
                ResetToken         = "",
                CanReset           = false
            };
            _teresa.HashedPassword = hasher.HashPassword(_teresa, "password");

            _bryan = new User
            {
                UserName           = "******",
                FirstName          = "Bryan",
                LastName           = "Ang",
                DateOfBirth        = new DateTime(1984, 02, 09),
                PhoneNumber        = "02243926392",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "98-7654-3211234-210",
                ResetToken         = "",
                CanReset           = false
            };
            _bryan.HashedPassword = hasher.HashPassword(_bryan, "password");

            _clay = new User
            {
                Id                 = 4,
                UserName           = "******",
                FirstName          = "Clay",
                LastName           = "Ton",
                DateOfBirth        = new DateTime(1985, 06, 16),
                PhoneNumber        = "02106849475",
                Email              = "*****@*****.**",
                MedicalInformation = "N/A",
                BankAccount        = "11-5723-2835024-110"
            };
            _clay.HashedPassword = hasher.HashPassword(_clay, "password");

            _payment1 = new Payment
            {
                Id          = 1,
                PaymentType = PaymentType.Electricity,
                Amount      = 175,
                Fixed       = false,
                Frequency   = Frequency.Monthly,
                StartDate   = new DateTime(2020, 03, 07),
                EndDate     = new DateTime(2020, 06, 07),
                Description = "electricity"
            };

            _payment2 = new Payment
            {
                Id          = 2,
                PaymentType = PaymentType.Rent,
                Amount      = 1000,
                Fixed       = true,
                Frequency   = Frequency.Monthly,
                StartDate   = new DateTime(2020, 03, 01),
                EndDate     = new DateTime(2020, 10, 01),
                Description = "rent"
            };

            _userPaymentBryan1 = new UserPayment
            {
                Payment   = _payment1,
                User      = _bryan,
                UserId    = _bryan.Id,
                PaymentId = _payment1.Id
            };

            _userPaymentBryan2 = new UserPayment
            {
                Payment   = _payment2,
                User      = _bryan,
                UserId    = _bryan.Id,
                PaymentId = _payment2.Id
            };

            _userPaymentYin1 = new UserPayment
            {
                Payment   = _payment1,
                User      = _yin,
                UserId    = _yin.Id,
                PaymentId = _payment1.Id
            };

            _userPaymentYin2 = new UserPayment
            {
                Payment   = _payment2,
                User      = _yin,
                UserId    = _yin.Id,
                PaymentId = _payment2.Id
            };

            _userPaymentTeresa1 = new UserPayment
            {
                Payment   = _payment1,
                User      = _teresa,
                UserId    = _teresa.Id,
                PaymentId = _payment1.Id
            };

            _userPaymentTeresa2 = new UserPayment
            {
                Payment   = _payment2,
                User      = _teresa,
                UserId    = _teresa.Id,
                PaymentId = _payment2.Id
            };

            _payment1.UserPayments = new List <UserPayment> {
                _userPaymentBryan1, _userPaymentTeresa1, _userPaymentYin1
            };
            _payment2.UserPayments = new List <UserPayment> {
                _userPaymentBryan2, _userPaymentTeresa2, _userPaymentYin2
            };

            _yin.UserPayments = new List <UserPayment> {
                _userPaymentYin1, _userPaymentYin2
            };
            _bryan.UserPayments = new List <UserPayment> {
                _userPaymentBryan1, _userPaymentBryan2
            };
            _teresa.UserPayments = new List <UserPayment> {
                _userPaymentTeresa1, _userPaymentTeresa2
            };

            _schedule1 = new Schedule
            {
                UserName     = "******",
                ScheduleType = ScheduleType.Away,
                StartDate    = new DateTime(2020, 04, 01),
                EndDate      = new DateTime(2020, 05, 01)
            };

            _flat1 = new Flat
            {
                Id      = 1,
                Address = "50 Symonds Street",
                Users   = new List <User> {
                    _yin, _teresa, _bryan, _clay
                },
                Schedules = new List <Schedule> {
                    _schedule1
                },
                Payments = new List <Payment> {
                    _payment1, _payment2
                }
            };
        }
Example #23
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseDeveloperExceptionPage();

            app.UseStaticFiles();
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                LoginPath             = new PathString("/signin")
            });

            app.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            {
                // Note: these settings must match the application details
                // inserted in the database at the server level.
                ClientId              = "myClient",
                ClientSecret          = "secret_secret_secret",
                PostLogoutRedirectUri = "/about",

                RequireHttpsMetadata          = false,
                GetClaimsFromUserInfoEndpoint = true,
                SaveTokens = true,

                // Use the authorization code flow.
                ResponseType = OpenIdConnectResponseTypes.Code,

                // Note: setting the Authority allows the OIDC client middleware to automatically
                // retrieve the identity provider's configuration and spare you from setting
                // the different endpoints URIs or the token validation parameters explicitly.
                Authority = "http://localhost:54540/",

                Scope = { "email", "roles" }
            });

            // Add a middleware used to validate access
            // tokens and protect the API endpoints.
            app.UseOAuthValidation();

            // Alternatively, you can also use the introspection middleware.
            // Using it is recommended if your resource server is in a
            // different application/separated from the authorization server.
            //
            // app.UseOAuthIntrospection(options => {
            //     options.AutomaticAuthenticate = true;
            //     options.AutomaticChallenge = true;
            //     options.Authority = "http://localhost:54540/";
            //     options.Audience = "resource_server";
            //     options.ClientId = "resource_server";
            //     options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
            // });

            app.UseIdentity();

            app.UseGoogleAuthentication(new GoogleOptions {
                ClientId     = "560027070069-37ldt4kfuohhu3m495hk2j4pjp92d382.apps.googleusercontent.com",
                ClientSecret = "n2Q-GEw9RQjzcRbU3qhfTj8f"
            });

            app.UseTwitterAuthentication(new TwitterOptions {
                ConsumerKey    = "6XaCTaLbMqfj6ww3zvZ5g",
                ConsumerSecret = "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI"
            });

            app.UseGitHubAuthentication(new GitHubAuthenticationOptions {
                ClientId     = "49e302895d8b09ea5656",
                ClientSecret = "98f1bf028608901e9df91d64ee61536fe562064b",
                Scope        = { "user:email" }
            });

            // Note: OpenIddict must be added after
            // ASP.NET Identity and the external providers.
            app.UseOpenIddict(builder => {
                builder.Options.AllowInsecureHttp = true;

                // Note: if you don't explicitly register a signing key, one is automatically generated and
                // persisted on the disk. If the key cannot be persisted, an in-memory key is used instead:
                // when the application shuts down, the key is definitely lost and the access/identity tokens
                // will be considered as invalid by client applications/resource servers when validating them.
                //
                // On production, using a X.509 certificate stored in the machine store is recommended.
                // You can generate a self-signed certificate using Pluralsight's self-cert utility:
                // https://s3.amazonaws.com/pluralsight-free/keith-brown/samples/SelfCert.zip
                //
                // builder.UseSigningCertificate("7D2A741FE34CC2C7369237A5F2078988E17A6A75");
                //
                // Alternatively, you can also store the certificate as an embedded .pfx resource
                // directly in this assembly or in a file published alongside this project:
                //
                // builder.UseSigningCertificate(
                //     assembly: typeof(Startup).GetTypeInfo().Assembly,
                //     resource: "Nancy.Server.Certificate.pfx",
                //     password: "******");

                // You can customize the default Content Security Policy (CSP) by calling UseNWebsec explicitly.
                // This can be useful to allow your HTML views to reference remote scripts/images/styles.
                builder.UseNWebsec(directives => {
                    directives.DefaultSources(directive => directive.Self())
                    .ImageSources(directive => directive.Self().CustomSources("*"))
                    .ScriptSources(directive => directive
                                   .Self()
                                   .UnsafeInline()
                                   .CustomSources("https://my.custom.url"))
                    .StyleSources(directive => directive.Self().UnsafeInline());
                });
            });

            app.UseMvcWithDefaultRoute();

            using (var context = app.ApplicationServices.GetRequiredService <ApplicationDbContext>()) {
                context.Database.EnsureCreated();

                // Add Mvc.Client to the known applications.
                if (!context.Applications.Any())
                {
                    // Note: when using the introspection middleware, your resource server
                    // MUST be registered as an OAuth2 client and have valid credentials.
                    //
                    // context.Applications.Add(new Application {
                    //     Id = "resource_server",
                    //     DisplayName = "Main resource server",
                    //     Secret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd"
                    // });

                    var hasher = new PasswordHasher <Application>();

                    context.Applications.Add(new Application {
                        Id                = "myClient",
                        DisplayName       = "My client application",
                        RedirectUri       = "http://localhost:54540/signin-oidc",
                        LogoutRedirectUri = "http://localhost:54540/",
                        Secret            = Crypto.HashPassword("secret_secret_secret"),
                        Type              = OpenIddictConstants.ApplicationTypes.Confidential
                    });

                    // To test this sample with Postman, use the following settings:
                    //
                    // * Authorization URL: http://localhost:54540/connect/authorize
                    // * Access token URL: http://localhost:54540/connect/token
                    // * Client ID: postman
                    // * Client secret: [blank] (not used with public clients)
                    // * Scope: openid email profile roles
                    // * Grant type: authorization code
                    // * Request access token locally: yes
                    context.Applications.Add(new Application {
                        Id          = "postman",
                        DisplayName = "Postman",
                        RedirectUri = "https://www.getpostman.com/oauth2/callback",
                        Type        = OpenIddictConstants.ApplicationTypes.Public
                    });

                    context.SaveChanges();
                }
            }
        }
        // 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())
            {
            }
        }
Example #25
0
        protected override void Seed(BlogContext context)
        {
            //creates lior, noa and guy as admins
            ApplicationDbContext context2 = new ApplicationDbContext();
            IdentityRole         role1    = new IdentityRole {
                Name = "Admin"
            };

            context2.Roles.Add(role1);
            context2.SaveChanges();


            var             passwordHash = new PasswordHasher();
            string          password     = passwordHash.HashPassword("Lr1234!");
            ApplicationUser admin        = new ApplicationUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = password, SecurityStamp = Guid.NewGuid().ToString(), LockoutEnabled = true
            };

            context2.Users.Add(admin);
            string          password2 = passwordHash.HashPassword("Go1234!");
            ApplicationUser admin2    = new ApplicationUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = password2, SecurityStamp = Guid.NewGuid().ToString(), LockoutEnabled = true
            };

            context2.Users.Add(admin2);
            string          password3 = passwordHash.HashPassword("Nf1234!");
            ApplicationUser admin3    = new ApplicationUser {
                UserName = "******", Email = "*****@*****.**", PasswordHash = password3, SecurityStamp = Guid.NewGuid().ToString(), LockoutEnabled = true
            };

            context2.Users.Add(admin3);
            context2.SaveChanges();

            IdentityUserRole adminRole = new IdentityUserRole()
            {
                RoleId = role1.Id,
                UserId = admin.Id
            };

            admin.Roles.Add(adminRole);
            context2.SaveChanges();

            IdentityUserRole adminRole2 = new IdentityUserRole()
            {
                RoleId = role1.Id,
                UserId = admin2.Id
            };

            admin2.Roles.Add(adminRole2);
            context2.SaveChanges();

            IdentityUserRole adminRole3 = new IdentityUserRole()
            {
                RoleId = role1.Id,
                UserId = admin3.Id
            };

            admin3.Roles.Add(adminRole3);
            context2.SaveChanges();



            Post p1 = new Post {
                Title = "BATTOCCHIO JOINS MACCABI TEL AVIV", WriterName = "Maccabi-tlv", Date = DateTime.Now, Content = "Cristian Battocchio joined Maccabi Tel Aviv as the 25-year-old Argentine born midfielder successfully underwent a medical and signed a two-year-deal with an option for a further season. The diminutive midfielder who made 20 appearances for Italy’s U-20 and U-21’s, joins Maccabi on a free transfer after spending the last two seasons in France playing for Stade Brest. Maccabi’s coach Jordi Cruyff told the club’s  official website: “Cristian is the kind of player we feel can give us a different dimension and upgrade our game”. Cristian told the club: “I am happy to be here and sign for Maccabi.It is a new experience for me to sign for such a big club which will always fight for all the titles and competing in Europe is another challenge I am looking forward to”. The Rosario born midfielder who began his playing career at the Youth Academy of Newll’s Old Boys, joined Italian club Udinese in 2009 at the age of 16.In 2012 Battocchio joined Watford on loan and after impressing the Hornets boss Gianfranco Zola made the move to Vicarage Road permanent in 2013. The arrival of former Maccabi coach Slavisa Jokanovic at Watford in 2014 saw Battocchio return to Italy and join Virtus Entella on loan before switching to Brest for which he scored 8 goals in 35 appearances last season.", TrendPicture = "https://static.maccabi-tlv.co.il/wp-content/uploads/2017/07/MTA_201707100140390e068bdf68e24ba392bd8a978139faab.jpg", TrendVideoURL = null, URL = "http://www.one.co.il"
            };

            context.Posts.Add(p1);
            Post p2 = new Post {
                Title = "'Seinfeld': things you didn't know", WriterName = "lior", Date = DateTime.Now, Content = "One of the most popular TV shows of all time is celebrating its 28th birthday. 'Seinfeld' took a while to find its feet after premiering in 1989, but by the mid-'90s the show was a hit. It ended in 1997 after nine glorious seasons with more than 75 million Americans tuning in to watch the finale. FAVORITE TV REUNIONS To celebrate the show’s birthday, news.com.au assembled some of the most interesting facts about the “show about nothing. JERRY SEINFELD’S FAVOURITE EPISODE There were 180 episodes in total, but Jerry Seinfeld has two favorites in particular. “One was the 'The Rye,' because we got to shoot that at Paramount Studios in LA which was the first time that we thought, ‘wow this is almost like a real TV show’,” Seinfeld said during a Reddit AMA. “We hadn’t felt like a real TV show, the early years of the TV show were not successful...We felt like we were a weird little orphan show.So that was a big deal for us.” And the comedian’s other favorite episode is 'The Pothole.' “Newman drives his mail truck over a sewing machine and his mail truck burst into flames,” Seinfeld recalled. “It was really fun to shoot, and it was fun to set Newman on fire.And he screamed, ‘oh the humanity’ like from the Hindenberg disaster.", TrendPicture = "http://www.sonypictures.com/tv/seinfeld/assets/images/onesheet.jpg", TrendVideoURL = "https://www.youtube.com/embed/9RK99NAJyeg", URL = "http://www.sonypictures.com/tv/seinfeld/"
            };

            context.Posts.Add(p2);
            context.SaveChanges();


            Comment c1 = new Comment {
                CommentID = 1050, CommentTitle = "Great Player", Content = "One of the best players that they could sign", URL = "http://www.walla.co.il", WriterName = "Lior"
            };

            context.Comments.Add(c1);
            Comment c2 = new Comment {
                CommentID = 3000, CommentTitle = "Hahaha", Content = "Thats great. Nice video", URL = "http://www.seinfeld.com", WriterName = "Guy"
            };

            context.Comments.Add(c2);
            Comment c3 = new Comment {
                CommentID = 3001, CommentTitle = "I love them", Content = "I love this show!!", URL = "http://www.seinfeld.com", WriterName = "Noa"
            };

            context.Comments.Add(c3);
            context.SaveChanges();

            var enrollments = new List <Enrollment>
            {
                new Enrollment {
                    PostID = p1.ID, CommentID = c1.CommentID
                },
                new Enrollment {
                    PostID = p2.ID, CommentID = c2.CommentID
                },
                new Enrollment {
                    PostID = p2.ID, CommentID = c3.CommentID
                },
            };

            enrollments.ForEach(s => context.Enrollments.Add(s));
            context.SaveChanges();
        }
Example #26
0
        public static string HashPassword(User user, string password)
        {
            var passwordHasher = new PasswordHasher <User>();

            return(passwordHasher.HashPassword(user, password));
        }
Example #27
0
 public bool IsEqualPassword(string password)
 {
     return(PasswordHasher.Verify(password, Password));
 }
        protected override void OnModelCreating(ModelBuilder builder)
        {
            string AdminId   = "3183cc93-3310-488b-98fe-b19ebe2681aa";
            string ComunId   = "9bcec916-31d6-4548-9c2d-a7dc747f5148";
            string ClienteId = "b2000f92-ea6e-4524-a5fc-618e63869c31";

            string AdminRoleId   = "3183cc03-331q-488b-98fw-b19ebe2681ae";
            string ComunRoleId   = "9bcec911-31dr-454t-9c2y-a7dc747f514u";
            string ClienteRoleId = "b2000f9h-ea6i-452o-a5fp-618e63869c3z";

            //seed admin role
            builder.Entity <IdentityRole>().HasData(new IdentityRole
            {
                Name             = "administrador",
                NormalizedName   = "administrador",
                Id               = AdminRoleId,
                ConcurrencyStamp = AdminRoleId
            },
                                                    new IdentityRole
            {
                Name             = "comun",
                NormalizedName   = "comun",
                Id               = ComunRoleId,
                ConcurrencyStamp = ComunRoleId
            },
                                                    new IdentityRole
            {
                Name             = "cliente",
                NormalizedName   = "cliente",
                Id               = ClienteRoleId,
                ConcurrencyStamp = ClienteRoleId
            });

            //create user
            var admin = new Usuario
            {
                Id              = AdminId,
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                NormalizedEmail = "*****@*****.**",
                Nombre          = "Frank",
                Apellido        = "Ofoedu",
                UserName        = "******"
            };

            var comun = new Usuario
            {
                Id              = ComunId,
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                NormalizedEmail = "*****@*****.**",
                Nombre          = "Jhon",
                Apellido        = "Whick",
                UserName        = "******"
            };
            var cliente = new Usuario
            {
                Id              = ClienteId,
                Email           = "*****@*****.**",
                EmailConfirmed  = true,
                NormalizedEmail = "*****@*****.**",
                Nombre          = "Shaw",
                Apellido        = "Owen",
                UserName        = "******"
            };
            //set user admin password
            PasswordHasher <Usuario> phAdmin = new PasswordHasher <Usuario>();

            admin.PasswordHash = phAdmin.HashPassword(admin, "Admin123!");

            //set user comun password
            PasswordHasher <Usuario> phComun = new PasswordHasher <Usuario>();

            comun.PasswordHash = phComun.HashPassword(comun, "Comun123!");

            //set user cliente password
            PasswordHasher <Usuario> phCliente = new PasswordHasher <Usuario>();

            cliente.PasswordHash = phCliente.HashPassword(cliente, "Clente123!");


            //seed user
            builder.Entity <Usuario>().HasData(admin, comun, cliente);

            //set user role to admin
            builder.Entity <IdentityUserRole <string> >().HasData(new IdentityUserRole <string>
            {
                RoleId = AdminRoleId,
                UserId = AdminId
            },
                                                                  new IdentityUserRole <string>
            {
                RoleId = ComunRoleId,
                UserId = ComunId
            },
                                                                  new IdentityUserRole <string>
            {
                RoleId = ClienteRoleId,
                UserId = ClienteId
            });

            base.OnModelCreating(builder);
        }
Example #29
0
 public AccountService(AuthDbContext context)
 {
     _context   = context;
     _pwdHasher = new PasswordHasher <Account>();
 }
Example #30
0
        protected override void Seed(EwiPracaDbContext context)
        {
            var rolesArray = new[] { RolesNames.Administrator, RolesNames.User, RolesNames.Viewer };

            var administrators = new List <string>
            {
                EncryptionService.EncryptEmail("*****@*****.**"),
                EncryptionService.EncryptEmail("*****@*****.**")
            };

            const string defaultPassword = "******";

            var passwordHash = new PasswordHasher();
            var password     = passwordHash.HashPassword(defaultPassword);

            var roles = rolesArray.Select(role => new IdentityRole(role)).ToList();

            foreach (IdentityRole role in roles)
            {
                if (context.Roles.FirstOrDefault(x => x.Name == role.Name) == null)
                {
                    context.Roles.AddOrUpdate(role);
                }
            }

            context.SaveChanges();

            foreach (var user in administrators.Select(admin => new ApplicationUser
            {
                FirstName = EncryptionService.Encrypt("Default name"),
                Surname = EncryptionService.Encrypt("Default surname"),
                UserName = admin,
                Email = admin,
                PasswordHash = password,
                LockoutEnabled = true,
                LastLoginDate = DateTime.Now,
                SecurityStamp = Guid.NewGuid().ToString(),
                IsActive = true
            }))
            {
                if (context.Users.FirstOrDefault(u => u.UserName == user.UserName) == null)
                {
                    context.Users.Add(user);
                }
            }

            context.SaveChanges();

            var adminRoleId = context.Roles.FirstOrDefault(x => x.Name == RolesNames.Administrator).Id;

            foreach (var admin in administrators)
            {
                var userAdmin = context.Users.FirstOrDefault(x => x.Email == admin);

                var userRole = new IdentityUserRole
                {
                    RoleId = adminRoleId,
                    UserId = userAdmin.Id
                };

                if (userAdmin.Roles.FirstOrDefault(x => x.RoleId == userRole.RoleId) == null)
                {
                    userAdmin.Roles.Add(userRole);
                }
            }

            context.SaveChanges();
        }
Example #31
0
        public static bool PasswordVerified(User user, string password)
        {
            var passwordHasher = new PasswordHasher <User>();

            return(Microsoft.AspNetCore.Identity.PasswordVerificationResult.Success == passwordHasher.VerifyHashedPassword(user, user.Password, password));
        }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            // Customize the ASP.NET Identity model and override the defaults if needed.
            // For example, you can rename the ASP.NET Identity table names and more.
            // Add your customizations after calling base.OnModelCreating(builder);



            // Restrict deletion of related order when OrderProducts entry is removed

            // Restrict deletion of related order when AppointmentSymptom entry is removed
            modelBuilder.Entity <Appointment>()
            .HasMany(o => o.appointmentSymptoms)
            .WithOne(l => l.appointment)
            .OnDelete(DeleteBehavior.Restrict);



            // Restrict deletion of related product when AppointmentSymptom entry is removed
            modelBuilder.Entity <Symptom>()
            .HasMany(o => o.appointmentSymptoms)
            .WithOne(l => l.symptom)
            .OnDelete(DeleteBehavior.Restrict);


            modelBuilder.Entity <Symptom>()
            .Property(b => b.DateCreated)
            .HasDefaultValueSql("GETDATE()");

            ApplicationUser user = new ApplicationUser
            {
                FirstName          = "admin",
                LastName           = "admin",
                UserName           = "******",
                NormalizedUserName = "******",
                Email           = "*****@*****.**",
                NormalizedEmail = "*****@*****.**",
                EmailConfirmed  = true,
                LockoutEnabled  = false,
                SecurityStamp   = "2b43d80c-25d9-4820-a424-b53a44531427"
            };
            var passwordHash = new PasswordHasher <ApplicationUser>();

            user.PasswordHash = passwordHash.HashPassword(user, "Admin8*");
            modelBuilder.Entity <ApplicationUser>().HasData(user);
////////////////////////////   AppointmentDB ///////////////////////////////////////////////
///
            modelBuilder.Entity <Appointment>().HasData(
                new Appointment()
            {
                AppointmentID       = 1,
                UserId              = user.Id,
                DoctorName          = "Dr Dodge",
                Address             = "123 street Franklin TN",
                Phone               = "111-337-222",
                AppointmentDate     = DateTime.Parse("2019-09-01"),
                DoctorsInstructions = "Take Medicine",
                Visited             = false
            },
                new Appointment()
            {
                AppointmentID       = 2,
                UserId              = user.Id,
                DoctorName          = "Dr Felch",
                Address             = "abc street Franklin TN",
                Phone               = "111-222-222",
                AppointmentDate     = DateTime.Parse("2019-05-20"),
                DoctorsInstructions = "Put refresh tears eye drops in every hour",
                Visited             = false
            },
                new Appointment()
            {
                AppointmentID       = 3,
                UserId              = user.Id,
                DoctorName          = "Dr Diana",
                Address             = "xyz street Nahville TN",
                Phone               = "222-337-222",
                AppointmentDate     = DateTime.Parse("2019-08-01"),
                DoctorsInstructions = "Advice excersise and walk for 30 min 5 times a week",
                Visited             = false
            }
                );



/////////////////////////////  Symptomdb  ///////////////////////////////////////////


            modelBuilder.Entity <Symptom>().HasData(
                new Symptom()
            {
                SymptomID          = 1,
                UserId             = user.Id,
                SymptomDescription = "Feeling Fatique and dizzy",
                Detail             = "In the morning when i woke up was feeling very low in energy and had an head ache",
                Severity           = 6,
            },
                new Symptom()
            {
                SymptomID          = 2,
                UserId             = user.Id,
                SymptomDescription = "Head ache",
                Detail             = "Having a head ache which goes mild to medium during day time",
                Severity           = 5,
            },
                new Symptom()
            {
                SymptomID          = 3,
                UserId             = user.Id,
                SymptomDescription = "Black lines infront of eyes",
                Detail             = "having black in lines infront of my vision all day since few months",
                Severity           = 8,
            });



            ////////////////////////////////  AppointmentSymptom ////////////////////////////////
            modelBuilder.Entity <AppointmentSymptom>().HasData(
                new AppointmentSymptom()
            {
                AppointmentSymptomID = 1,

                SymptomID     = 2,
                AppointmentID = 2,
                UserId        = user.Id
            },
                new AppointmentSymptom()
            {
                AppointmentSymptomID = 2,

                SymptomID     = 3,
                AppointmentID = 3,
                UserId        = user.Id
            },
                new AppointmentSymptom()
            {
                AppointmentSymptomID = 3,

                SymptomID     = 1,
                AppointmentID = 1,
                UserId        = user.Id
            });
        }
Example #33
0
        public async Task Get_Correct_Number_Of_Likes()
        {
            var options = Utils.GetOptions(nameof(Get_Correct_Number_Of_Likes));

            var cocktail = new Cocktail()
            {
                Id          = Guid.Parse("8a15e590-0b66-4fae-abfa-d75812b76da6"),
                Name        = "White Russian",
                Description = "The White Russian is decadent and sophisticated."
            };

            var  hasher = new PasswordHasher <User>();
            User user1  = new User
            {
                Id                 = Guid.Parse("a137730d-bb81-4611-8fb8-bb777aae86ac"),
                UserName           = "******",
                NormalizedUserName = "******",
                FirstName          = "Boyan",
                LastName           = "Vuchev",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                LockoutEnabled     = true,
                SecurityStamp      = "DC6E275DD1E24957A7781D42BB68293B",
            };

            user1.PasswordHash = hasher.HashPassword(user1, "123456");

            User user2 = new User
            {
                Id                 = Guid.Parse("ad513447-0536-432b-a848-ea96ade0040d"),
                UserName           = "******",
                NormalizedUserName = "******",
                FirstName          = "Radoslav",
                LastName           = "Simeonov",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                LockoutEnabled     = true,
                SecurityStamp      = "HNWQ7GQFUMWKGOAWSJNC5XV2VFYQRWHC",
            };

            user2.PasswordHash = hasher.HashPassword(user2, "123456");

            var cReview = new CocktailReview()
            {
                Id         = Guid.Parse("d7047a3a-7b5e-4eb5-8ed2-c846b7a4d5ce"),
                CocktailId = cocktail.Id,
                UserId     = user1.Id,
                Rating     = 1,
                Comment    = "Too sour",
                ReviewedOn = DateTime.UtcNow
            };

            var cReview2 = new CocktailReview()
            {
                Id         = Guid.Parse("11c58b41-f0db-480d-bbe5-115bc027f868"),
                CocktailId = cocktail.Id,
                UserId     = user2.Id,
                Rating     = 5,
                Comment    = "Great",
                ReviewedOn = DateTime.UtcNow
            };

            var cReviewLike2 = new CocktailReviewLike()
            {
                CocktailReviewId = cReview2.Id,
                UserId           = user2.Id,
                IsLiked          = true
            };

            var cReviewLike3 = new CocktailReviewLike()
            {
                CocktailReviewId = cReview2.Id,
                UserId           = user1.Id,
                IsLiked          = true
            };

            using (var arrangeContext = new CMContext(options))
            {
                arrangeContext.Cocktails.Add(cocktail);
                arrangeContext.Users.Add(user1);
                arrangeContext.Users.Add(user2);
                arrangeContext.CocktailReviews.Add(cReview);
                arrangeContext.CocktailReviews.Add(cReview2);
                arrangeContext.CocktailReviewLikes.Add(cReviewLike2);
                arrangeContext.CocktailReviewLikes.Add(cReviewLike3);
                await arrangeContext.SaveChangesAsync();
            }

            using (var assertContext = new CMContext(options))
            {
                var sut    = new CocktailReviewLikeService(assertContext);
                var result = await sut.GetCocktailReviewNumberOfLikes(cReview2.Id);

                Assert.AreEqual(2, result);
            }
        }
        /// <exception cref="ArgumentException">Thrown when parameter password is null or empty</exception>
        internal static DomainUserAccount[] Build(string password)
        {
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentException($"Parameter {nameof(password)} cannot be null or empty. It is needed to setup the user accounts");
            }

            string passwordHash = new PasswordHasher <DomainUserAccount>().HashPassword(new DomainUserAccount(), password);

            return(new DomainUserAccount[]
            {
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "Maurice",
                    LastName = "Slegtenhorst",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "0645377536"
                },
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "Maurice",
                    LastName = "Slegtenhorst",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "0645377536"
                },
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "Hanneke",
                    LastName = "Slegtenhorst",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "06" + new Random().Next(0, 999999).ToString("D10")
                },
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "PrivilegedEmployee_01",
                    LastName = "None",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "06" + new Random().Next(0, 999999).ToString("D10")
                },
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "Employee_01",
                    LastName = "None",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "06" + new Random().Next(0, 999999).ToString("D10")
                },
                new DomainUserAccount
                {
                    Id = Guid.NewGuid().ToString(),
                    IsAdmitted = true,
                    EmailConfirmed = true,
                    LockoutEnabled = true,
                    PhoneNumberConfirmed = true,
                    SecurityStamp = Guid.NewGuid().ToString("D"),
                    FirstName = "StandardUser_01",
                    LastName = "None",
                    Email = "*****@*****.**",
                    NormalizedEmail = "*****@*****.**".ToUpper(),
                    UserName = "******",
                    PasswordHash = passwordHash,
                    NormalizedUserName = "******".ToUpper(),
                    PhoneNumber = "06" + new Random().Next(0, 999999).ToString("D10")
                }
            });
        }
Example #35
0
        protected override void OnModelCreating(ModelBuilder builder)
        {
            base.OnModelCreating(builder);

            builder.Entity <ApplicationUserRole>(userRole =>
            {
                userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

                userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

                userRole.HasOne(ur => ur.User)
                .WithMany(r => r.ApplicationUserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
            });

            //Seed Data
            var superAdminRole = new ApplicationRole()
            {
                Id             = 1,
                Name           = Core.CommonStaticFunctions.Role_SuperAdmin,
                NormalizedName = Core.CommonStaticFunctions.Role_SuperAdmin,
                CreatedBy      = 0,
                CreationDate   = DateTime.Now
            };

            builder.Entity <ApplicationRole>().HasData(superAdminRole);

            builder.Entity <ApplicationRole>().HasData(new ApplicationRole()
            {
                Id             = 2,
                Name           = Core.CommonStaticFunctions.Role_Admin,
                NormalizedName = Core.CommonStaticFunctions.Role_Admin,
                CreatedBy      = 0,
                CreationDate   = DateTime.Now
            });

            builder.Entity <ApplicationRole>().HasData(new ApplicationRole()
            {
                Id             = 3,
                Name           = Core.CommonStaticFunctions.Role_Employee,
                NormalizedName = Core.CommonStaticFunctions.Role_Employee,
                CreatedBy      = 0,
                CreationDate   = DateTime.Now
            });

            builder.Entity <ApplicationRole>().HasData(new ApplicationRole()
            {
                Id             = 4,
                Name           = Core.CommonStaticFunctions.Role_Customer,
                NormalizedName = Core.CommonStaticFunctions.Role_Customer,
                CreatedBy      = 0,
                CreationDate   = DateTime.Now
            });

            //SuperAdmin User
            var superAdminUser = new ApplicationUser
            {
                Id                 = 1,
                FullName           = "Super Admin User",
                UserName           = "******",
                NormalizedUserName = "******",
                Email              = "*****@*****.**",
                NormalizedEmail    = "*****@*****.**",
                SecurityStamp      = Guid.NewGuid().ToString("D")
            };

            var password = new PasswordHasher <ApplicationUser>();
            var hashed   = password.HashPassword(superAdminUser, "Admin1");

            superAdminUser.PasswordHash = hashed;

            builder.Entity <ApplicationUser>().HasData(superAdminUser);

            builder.Entity <ApplicationUserRole>().HasData(new ApplicationUserRole()
            {
                RoleId = superAdminRole.Id,
                UserId = superAdminUser.Id
            });
        }
Example #36
0
        private string CreatePasswordHash(User user, string password)
        {
            var passwordHasher = new PasswordHasher <User>();

            return(passwordHasher.HashPassword(user, password));
        }
 public CustomDataServiceWrapper(IInfusionSoftConfiguration configuration, IMethodListenerProvider listenerProvider) :
     base(configuration, listenerProvider)
 {
     _hasher = new PasswordHasher();
 }
Example #38
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, ILoggerFactory factory) {
            factory.AddConsole();
            factory.AddDebug();

            app.UseIISPlatformHandler();

            app.UseForwardedHeaders(new ForwardedHeadersOptions
            {
                ForwardedHeaders = ForwardedHeaders.All
            });

            app.UseDeveloperExceptionPage();

            app.UseStaticFiles();

            // Add a middleware used to validate access
            // tokens and protect the API endpoints.
            app.UseOAuthValidation();
            // Alternatively, you can also use the introspection middleware.
            // Using it is recommended if your resource server is in a
            // different application/separated from the authorization server.
            //
            // app.UseOAuthIntrospection(options => {
            //     options.AutomaticAuthenticate = true;
            //     options.AutomaticChallenge = true;
            //     options.Authority = "http://localhost:54540/";
            //     options.Audience = "resource_server";
            //     options.ClientId = "resource_server";
            //     options.ClientSecret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd";
            // });

            app.UseIdentity();

            // Note: OpenIddict must be added after
            // ASP.NET Identity and the external providers.
            app.UseOpenIddict(options =>
            {
                // You can customize the default Content Security Policy (CSP) by calling UseNWebsec explicitly.
                // This can be useful to allow your HTML views to reference remote scripts/images/styles.
                options.UseNWebsec(directives =>
                {
                    directives.ChildSources(directive => directive.Self())
                        .DefaultSources(directive => directive.Self())
                        .ImageSources(directive => directive.Self().CustomSources("*"))
                        .FontSources(directive => directive.Self().CustomSources("data:"))
                        .ScriptSources(directive => directive
                            .Self()
                            .UnsafeEval()
                            .UnsafeInline()
                            .CustomSources("https://my.custom.url"))
                        .StyleSources(directive => directive.Self().UnsafeInline().CustomSources("data:"));
                });
            });

            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715

            app.UseMvcWithDefaultRoute();

            //app.UseSwaggerGen();
            //app.UseSwaggerUi();

            using (var context = app.ApplicationServices.GetRequiredService<ApplicationDbContext>())
            {
                context.Database.EnsureCreated();

                // Add Mvc.Client to the known applications.
                if (!context.Applications.Any())
                {
                    // Note: when using the introspection middleware, your resource server
                    // MUST be registered as an OAuth2 client and have valid credentials.
                    //
                    // context.Applications.Add(new Application {
                    //     Id = "resource_server",
                    //     DisplayName = "Main resource server",
                    //     Secret = "875sqd4s5d748z78z7ds1ff8zz8814ff88ed8ea4z4zzd"
                    // });

                    var hasher = new PasswordHasher<Application>();
                    context.Applications.Add(new Application
                    {
                        Id = "myClient",
                        DisplayName = "My client application",
                        RedirectUri = "http://localhost:53507/signin-oidc",
                        LogoutRedirectUri = "http://localhost:53507/",
                        Secret = Crypto.HashPassword("secret_secret_secret"),
                        Type = OpenIddictConstants.ApplicationTypes.Confidential
                    });

                    // To test this sample with Postman, use the following settings:
                    //
                    // * Authorization URL: http://localhost:54540/connect/authorize
                    // * Access token URL: http://localhost:54540/connect/token
                    // * Client ID: postman
                    // * Client secret: [blank] (not used with public clients)
                    // * Scope: openid email profile roles
                    // * Grant type: authorization code
                    // * Request access token locally: yes
                    context.Applications.Add(new Application
                    {
                        Id = "postman",
                        DisplayName = "Postman",
                        RedirectUri = "https://www.getpostman.com/oauth2/callback",
                        Type = OpenIddictConstants.ApplicationTypes.Public
                    });

                    context.SaveChanges();
                }
            }
        }