Ejemplo n.º 1
0
        public async void Insert_ValidateOk()
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();

                await repo.InsertAsync(entity);

                await context.SaveChangesAsync();

                Assert.Equal(1, context.Set <TEntity>().Count());
                _baseRepository.AssertAllProperties(entity, context.Set <TEntity>().First());
            }
        }
Ejemplo n.º 2
0
        public async void SelectById_ObtainOne()
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();
                await context.Set <TEntity>().AddAsync(entity);

                await context.SaveChangesAsync();

                var entityById = await repo.SelectByIdAsync(entity.GetIds);

                Assert.NotNull(entityById);
                _baseRepository.AssertAllProperties(entity, context.Set <TEntity>().First());
            }
        }
Ejemplo n.º 3
0
        /// <summary>
        /// initializing Acl tables, remove after using
        /// for using in Hillavas.BaseProject_MaterialPro.Data.Migrations.Configuration.cs
        /// just add "AclSeed.Init(context);" to seed method
        /// </summary>
        /// <param name="db">project context</param>
        public bool Init()
        {
            using (var bt = _db.Database.BeginTransaction())
            {
                var rep = AddAdminUserAndRole();
                if (!rep.Success)
                {
                    return(false);
                }

                #region UserInRole
                var userInRole = new UserInRole()
                {
                    UserId = rep.UserId,
                    RoleId = rep.RoleId
                };
                _db.Set <UserInRole>().Add(userInRole);

                if (_db.SaveChanges() == 0)
                {
                    bt.Rollback();
                    return(false);
                }
                #endregion

                var actionsRep = AddActions();
                if (!actionsRep.Success)
                {
                    bt.Rollback();
                    return(false);
                }
                _db.Set <ActionInRole>().AddRange(actionsRep.actions.Select(x => new ActionInRole
                {
                    RoleId    = rep.RoleId,
                    ActionId  = x.ActionId,
                    IsDefault = x.ActionName == "ProfileInfo" ? true : false
                }));
                if (_db.SaveChanges() == 0)
                {
                    bt.Rollback();
                    return(false);
                }
                bt.Commit();
                return(true);
            }
        }
Ejemplo n.º 4
0
        public async void Update_ValidateOk()
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();
                await context.Set <TEntity>().AddAsync(entity);

                await context.SaveChangesAsync();

                _baseRepository.ChangeNotIdProperties(ref entity);

                repo.Update(entity);
                await context.SaveChangesAsync();

                _baseRepository.AssertAllProperties(entity, context.Set <TEntity>().First());
            }
        }
Ejemplo n.º 5
0
        public IActionResult RemoveSong()
        {
            try
            {
                var playlistId = Int32.Parse(Request.Form["playlistId"]);
                var songId     = Int32.Parse(Request.Form["songId"]);
                var song       = _context.Set <SongPlaylist>().Where(x => x.PlaylistId == playlistId && x.SongId == songId).FirstOrDefault();

                if (song != null)
                {
                    _context.Set <SongPlaylist>().Remove(song);
                    _context.SaveChanges();
                }
                return(RedirectToAction("Edit", new { id = playlistId }));
            }
            catch
            {
                Index();
                return(View("Index"));
            }
        }
Ejemplo n.º 6
0
        public async void Delete_ValidateOk()
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();
                await context.Set <TEntity>().AddAsync(entity);

                await context.SaveChangesAsync();

                repo.Delete(entity);
                await context.SaveChangesAsync();

                Assert.Empty(context.Systems);
            }
        }
Ejemplo n.º 7
0
        public async void SelectByFilter_ValidateBasicPredicates(bool expressionFilterResult, int expectedCant)
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();
                await context.Set <TEntity>().AddAsync(entity);

                await context.SaveChangesAsync();

                Expression <Func <TEntity, bool> > expressionFunctionFilter = (s) => expressionFilterResult;

                var entities = repo.SelectByFilter(expressionFunctionFilter);

                Assert.NotNull(entities);
                Assert.Equal(expectedCant, entities.Count());
            }
        }
Ejemplo n.º 8
0
        public async void Insert_Existent_Id_ThrowException()
        {
            using (var context = new AuthDbContext(CreateNewContextOptions()))
            {
                TRepository repo   = _baseRepository.GetNewRepository(context);
                TEntity     entity = _baseRepository.GetNewValidEntity();
                await context.Set <TEntity>().AddAsync(entity);

                await context.SaveChangesAsync();

                _baseRepository.ChangeNotIdProperties(ref entity);

                Func <Task> insertFunction = async() =>
                {
                    await repo.InsertAsync(entity);

                    await context.SaveChangesAsync();
                };

                await Assert.ThrowsAsync <ArgumentException>(insertFunction);
            }
        }
 public InformalEducationService(IServiceProvider serviceProvider, AuthDbContext dbContext)
 {
     DbContext            = dbContext;
     this.DbSet           = dbContext.Set <InformalEducation>();
     this.IdentityService = serviceProvider.GetService <IIdentityService>();
 }
Ejemplo n.º 10
0
 public virtual async Task <IList <TEntity> > GetAllAsync()
 {
     return(await _dbContext.Set <TEntity>().AsNoTracking().ToListAsync());
 }
Ejemplo n.º 11
0
 public ValueTask <TEntity> SelectByIdAsync(params object[] keyValues)
 {
     return(Context.Set <TEntity>().FindAsync(keyValues));
 }
Ejemplo n.º 12
0
 public Repository(AuthDbContext context)
 {
     this._set     = context.Set <T>();
     this._context = context;
 }
Ejemplo n.º 13
0
 //This methos should be used to Create a new User
 public bool CreateUser(User user)
 {
     authDbContext.Set <User>().Add(user);
     authDbContext.SaveChanges();
     return(true);
 }
Ejemplo n.º 14
0
 public FamilyDataService(IServiceProvider serviceProvider, AuthDbContext dbContext)
 {
     DbContext            = dbContext;
     this.DbSet           = dbContext.Set <FamilyData>();
     this.IdentityService = serviceProvider.GetService <IIdentityService>();
 }
Ejemplo n.º 15
0
 public GenericRepository()
 {
     dbContext = new AuthDbContext();
     dbSet     = dbContext.Set <T>();
 }
 public WorkingExperienceService(IServiceProvider serviceProvider, AuthDbContext dbContext)
 {
     DbContext            = dbContext;
     this.DbSet           = dbContext.Set <WorkingExperience>();
     this.IdentityService = serviceProvider.GetService <IIdentityService>();
 }
Ejemplo n.º 17
0
        public async Task <int> UpdateAsync(int id, Account model)
        {
            var data = await ReadByIdAsync(id);

            data.Username = model.Username;
            if (!string.IsNullOrEmpty(model.Password))
            {
                data.Password = SHA1Encrypt.Hash(model.Password);
            }
            data.IsLocked                 = model.IsLocked;
            data.AccountProfile.Dob       = model.AccountProfile.Dob;
            data.AccountProfile.Email     = model.AccountProfile.Email;
            data.AccountProfile.Firstname = model.AccountProfile.Firstname;
            data.AccountProfile.Gender    = model.AccountProfile.Gender;
            data.AccountProfile.Lastname  = model.AccountProfile.Lastname;

            var updatedRoles = model.AccountRoles.Where(x => data.AccountRoles.Any(y => y.RoleId == x.RoleId));
            var addedRoles   = model.AccountRoles.Where(x => !data.AccountRoles.Any(y => y.RoleId == x.RoleId));
            var deletedRoles = data.AccountRoles.Where(x => !model.AccountRoles.Any(y => y.RoleId == x.RoleId));

            var updatedstore = model.Stores.Where(x => data.Stores.Any(y => y.Id == x.Id));
            var addedstore   = model.Stores.Where(x => !data.Stores.Any(y => y.Id == x.Id));
            var deletedstore = data.Stores.Where(x => !model.Stores.Any(y => y.Id == x.Id));

            foreach (var item in updatedRoles)
            {
                var role = data.AccountRoles.SingleOrDefault(x => x.RoleId == item.RoleId);

                EntityExtension.FlagForUpdate(role, IdentityService.Username, UserAgent);
            }

            foreach (var item in addedRoles)
            {
                item.AccountId = id;
                item.Role      = null;
                EntityExtension.FlagForCreate(item, IdentityService.Username, UserAgent);
                data.AccountRoles.Add(item);
            }

            foreach (var item in deletedRoles)
            {
                EntityExtension.FlagForDelete(item, IdentityService.Username, UserAgent, true);
            }

            foreach (var item in updatedstore)
            {
                var store = data.Stores.SingleOrDefault(x => x.Id == item.Id);
                EntityExtension.FlagForUpdate(store, IdentityService.Username, UserAgent);
            }

            foreach (var item in addedstore)
            {
                item.AccountId = id;
                item.Id        = 0;
                EntityExtension.FlagForCreate(item, IdentityService.Username, UserAgent);
                DbContext.Set <Store>().Add(item);
            }

            foreach (var item in deletedstore)
            {
                EntityExtension.FlagForDelete(item, IdentityService.Username, UserAgent, true);
            }

            EntityExtension.FlagForUpdate(data, IdentityService.Username, UserAgent);

            DbSet.Update(data);
            return(await DbContext.SaveChangesAsync());
        }
Ejemplo n.º 18
0
 public AccountService(IServiceProvider serviceProvider, AuthDbContext dbContext)
 {
     DbContext            = dbContext;
     this.DbSet           = dbContext.Set <Account>();
     this.IdentityService = serviceProvider.GetService <IIdentityService>();
 }
Ejemplo n.º 19
0
        public async Task <IActionResult> Register(RegisterViewModel model, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                var vm = await BuildRegisterViewModelAsync(model);

                return(View(vm));
            }

            var user = await _context.Set <AppUser>().FirstOrDefaultAsync(r => r.UserName == model.Username);

            if (user != null)
            {
                ModelState.AddModelError("Username", "Un utilisateur avec cette adresse email existe déjà.");
                var vm = await BuildRegisterViewModelAsync(model);

                return(View(vm));
            }

            user = new AppUser()
            {
                UserName  = model.Username,
                Email     = model.Username,
                FirstName = model.FirstName,
                LastName  = model.LastName
            };

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

            if (!result.Succeeded)
            {
                ModelState.AddModelError(string.Empty, result.Errors.ToString());
                var vm = await BuildRegisterViewModelAsync(model);

                return(View(vm));
            }

            await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Email, user.Email));

            await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.FamilyName, user.LastName));

            await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.GivenName, user.FirstName));

            await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Name, $"{user.FirstName} {user.LastName}"));

            await _userManager.AddClaimAsync(user, new Claim(JwtClaimTypes.Role, _configuration.GetValue <string>("Roles:Anonymous:value")));

            await _userManager.AddToRoleAsync(user, _configuration.GetValue <string>("Roles:AppUser:value"));

            var token = await _userManager.GenerateEmailConfirmationTokenAsync(user);

            var url = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, token = token, returnUrl = model.ReturnUrl }, Url.ActionContext.HttpContext.Request.Scheme);

            var msg = new SendEmailRequest();

            msg.Destination = new Destination
            {
                ToAddresses = new List <string> {
                    $"{user.FirstName}<{user.Email}>"
                }
            };

            msg.Source     = $"{_configuration.GetValue<string>("mailer:sender:name")}<{_configuration.GetValue<string>("mailer:sender:email")}>";
            msg.ReturnPath = _configuration.GetValue <string>("mailer:bounces");
            msg.Message    = new Message
            {
                Subject = new Content("Confirmation de votre adresse mail")
            };

            var content = await _templateEngine.CompileRenderAsync("ConfirmEmailEvent.cshtml", new { UserName = $"{user.FirstName} {user.LastName}", Url = url });

            msg.Message.Body = new Body {
                Html = new Content(content)
            };

            var response = await _mailer.SendEmailAsync(msg, cancellationToken);

            return(await Login(new LoginInputModel
            {
                Username = model.Username,
                Password = model.Password,
                ReturnUrl = model.ReturnUrl
            }, "login"));
        }