public async Task <ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { // Conta dias para o limite de teste do sistema int diasParaTeste = 1; int.TryParse(WebConfigurationManager.AppSettings["diasParaTeste"].ToString(), out diasParaTeste); var limiteDeTeste = DateTime.Now.AddDays(diasParaTeste); // Cria somente usuário de teste var situacao = "T"; var empresa = new Empresa() { Id = IdentityGenerator.NewSequentialGuid(), Descricao = model.Nome }; var context = new ApplicationDbContext(); context.Empresas.Add(empresa); context.SaveChanges(); var user = new ApplicationUser { UserName = model.Email, Email = model.Email, Nome = model.Nome, Situacao = situacao, LimiteDeTeste = limiteDeTeste, IdEmpresa = empresa.Id }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent : false, rememberBrowser : false); // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=320771 // Send an email with this link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>"); return(RedirectToAction("Index", "Home")); } AddErrors(result); } // If we got this far, something failed, redisplay form return(View(model)); }
public MemberDTO Add(MemberDTO itemDto) { var model = itemDto.ToModel(); model.Id = IdentityGenerator.NewSequentialGuid(); model.Created = DateTime.UtcNow; // 数据验证 this.ValidateModel(model); _Repository.Add(model); this.OperationLog(HrMessagesResources.Add_Member, model.ToDto(), null); //commit the unit of work _Repository.UnitOfWork.Commit(); return(model.ToDto()); }
public ShipDTO Add(ShipDTO shipDTO) { var ship = shipDTO.ToModel(); ship.Id = IdentityGenerator.NewSequentialGuid(); ship.Created = DateTime.UtcNow; if (ship.Name.IsNullOrBlank()) { throw new DefinedException(CommonMessageResources.Name_Empty); } if (_Repository.Exists(ship)) { throw new DataExistsException(string.Format(BaseMessagesResources.Ship_Exists_WithValue, ship.Name)); } var ruleName = CommonMessageResources.SerialNumberRule_Ship; var snRule = SerialNumberRuleQuerier.FindBy(ruleName); if (snRule == null) { throw new DataNotFoundException(string.Format(BaseMessagesResources.SerialNumberRule_NotExists_WithValue, ruleName)); } ship.Sn = SerialNumberGenerator.GetSerialNumber(snRule.Prefix, snRule.UseDateNumber, snRule.NumberLength); _Repository.Add(ship); #region 操作日志 var shipDto = ship.ToDto(); OperateRecorder.RecordOperation(shipDto.Sn, BaseMessagesResources.Add_Ship, shipDto.GetOperationLog()); #endregion //commit the unit of work _Repository.UnitOfWork.Commit(); return(ship.ToDto()); }
public Task <Guid> CreateDailyIncome(DailyIncomeObject obj) { return(Task.Run(() => { try { if (obj.Id == Guid.Empty) { var dataObj = new MapperConfiguration(doj => { doj.CreateMap <DailyIncomeObject, DailyIncome>(); }); IMapper iMapper = dataObj.CreateMapper(); var source = new DailyIncome(); source.Id = IdentityGenerator.NewSequentialGuid(); source.AmountMade = obj.AmountMade; source.Balance = obj.Balance; source.CompulsorySavings = obj.CompulsorySavings; source.PercentageProfit = obj.PercentageProfit; source.Profit = obj.Profit; source.DaillyAllowance = obj.DaillyAllowance; source.EntryDate = obj.EntryDate; source.Expenses = obj.Expenses; dailyIncomeRepo.Add(source); dailyIncomeRepo.UnitofWork.Commit(); return source.Id; } else { throw new InvalidOperationException(); } } catch (Exception) { throw; } })); }
public async Task RemoveCollectionWithCachingAsync() { var identities = new List <Identity> { IdentityGenerator.Default, IdentityGenerator.Generate() }; await _identityRepository.AddAsync(identities, o => o.Cache().ImmediateConsistency()); Assert.Equal(2, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(0, _cache.Misses); await _identityRepository.RemoveAsync(identities, o => o.ImmediateConsistency()); Assert.Equal(0, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(0, _cache.Misses); Assert.Equal(0, await _identityRepository.CountAsync()); }
public MenuDTO Add(MenuDTO menuDTO) { var menu = menuDTO.ToModel(); menu.Id = IdentityGenerator.NewSequentialGuid(); menu.Created = DateTime.UtcNow; if (menu.Name.IsNullOrBlank()) { throw new DataExistsException(UserSystemResource.Common_Name_Empty); } if (_Repository.Exists(menu)) { throw new DataExistsException(UserSystemResource.Menu_Exists); } _Repository.Add(menu); //commit the unit of work _Repository.UnitOfWork.Commit(); return(menu.ToDto()); }
//public User SignIn(string username, string password) //{ // var user = _unitOfWork.GetRepository<User>().GetFirstOrDefault(predicate:u=>u.UserName == username || u.Mobile == username); // if (user == null) return null; // var salt = Convert.FromBase64String(user.SecurityStamp); // var pwdHash = Hash.HashPasswordWithSalt(password, salt); // return user.PasswordHash == pwdHash ? user : null; //} public int CreateUser(string userName, string email, string password, string realName, string mobile) { if (IsExistEmail(email)) { return(1); //1 邮箱已存在 } if (IsExistUserName(userName)) { return(2); //1 用户名已存在 } if (IsExistMobile(mobile)) { return(3); //1 手机号已存在 } var securityStamp = Hash.GenerateSalt(); var passwordHash = Hash.HashPasswordWithSalt(password, securityStamp); var newUser = new User() { Id = IdentityGenerator.SequentialGuid(), UserName = userName, RealName = realName, Email = email, SecurityStamp = Convert.ToBase64String(securityStamp), PasswordHash = passwordHash, CreateDate = DateTime.Now, IsActive = true, Mobile = mobile }; //_logger.LogInformation(string.Format(Logs.CreateMessage, EntityNames.User, userName)); _db.Add(newUser); _db.SaveChanges(); //_unitOfWork.GetRepository<User>().Insert(newUser); //_unitOfWork.SaveChanges(); // SetUserCookies(false, newUser); return(0); }
public RoleDTO Add(RoleDTO roleDTO) { var role = roleDTO.ToModel(); role.Id = IdentityGenerator.NewSequentialGuid(); role.Created = DateTime.UtcNow; if (role.Name.IsNullOrBlank()) { throw new DataExistsException(UserSystemResource.Common_Name_Empty); } if (_Repository.Exists(role)) { throw new DataExistsException(UserSystemResource.Role_Exists); } _Repository.Add(role); //commit the unit of work _Repository.UnitOfWork.Commit(); return(role.ToDto()); }
public async Task HandleAsync(ProductSubscribedEvent @event) { var client = await _aggregateRootRepository.Get <AggregatesModel.ClientAggregate.Client>(@event.ClientId); #region product var product = await _aggregateRootRepository.Get <AggregatesModel.ProductAggregate.Product>(@event.ProductId); product.SubscribeClient(@event.ClientId, $"{client.FirstName} {client.LastName}", client.Email); await _aggregateRootRepository.Save(product); #endregion #region account var aggregate = new Account(IdentityGenerator.NewSequentialGuid(IdentityGeneratorType.SequentialAsString), @event.Number, @event.ClientId, @event.ProductId); aggregate.Activate(); await _aggregateRootRepository.Save(aggregate); #endregion }
public void AddRole() { var sw = new Stopwatch(); TimeSpan timeCost; using (var unitOfWork = new TSoftUnitOfWork()) { sw.Start(); #region AddOrUpdate const string roleName = "超级管理员"; var role = unitOfWork.Roles.FirstOrDefault(x => x.Name.Equals(roleName)); string salt = Guid.NewGuid().ToString(); if (role == null) { role = new Role() { Id = IdentityGenerator.NewSequentialGuid(), Name = roleName, Created = DateTime.UtcNow, IsEnable = true }; unitOfWork.Roles.Add(role); } else { role.Name = "超级管理员"; role.Created = DateTime.UtcNow; } #endregion unitOfWork.DbContext.SaveChanges(); sw.Stop(); timeCost = sw.Elapsed; } Console.WriteLine("Elapsed: " + timeCost.Ticks); }
public async Task GetByIdWithCacheAsync() { var identity = await _identityRepository.AddAsync(IdentityGenerator.Default); Assert.NotNull(identity?.Id); Assert.Equal(0, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(0, _cache.Misses); Assert.Equal(identity, await _identityRepository.GetByIdAsync(identity.Id, o => o.Cache())); Assert.Equal(1, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(1, _cache.Misses); Assert.Equal(identity, await _identityRepository.GetByIdAsync(identity.Id, o => o.Cache())); Assert.Equal(1, _cache.Count); Assert.Equal(1, _cache.Hits); Assert.Equal(1, _cache.Misses); Assert.Null(await _identityRepository.GetByIdAsync("not-yet", o => o.Cache())); Assert.Equal(2, _cache.Count); Assert.Equal(1, _cache.Hits); Assert.Equal(2, _cache.Misses); Assert.Null(await _identityRepository.GetByIdAsync("not-yet", o => o.Cache())); Assert.Equal(2, _cache.Count); Assert.Equal(2, _cache.Hits); Assert.Equal(2, _cache.Misses); var newIdentity = await _identityRepository.AddAsync(IdentityGenerator.Generate("not-yet"), o => o.Cache()); Assert.NotNull(newIdentity?.Id); Assert.Equal(2, _cache.Count); Assert.Equal(2, _cache.Hits); Assert.Equal(2, _cache.Misses); Assert.Equal(newIdentity, await _identityRepository.GetByIdAsync("not-yet", o => o.Cache())); Assert.Equal(2, _cache.Count); Assert.Equal(3, _cache.Hits); Assert.Equal(2, _cache.Misses); }
public RoleDTO Add(RoleDTO roleDTO) { var role = roleDTO.ToModel(); role.Id = IdentityGenerator.NewSequentialGuid(); role.Created = DateTime.UtcNow; var group = _RoleGroupRepository.Get(roleDTO.RoleGroupId); if (group == null) { throw new DataExistsException(UserSystemMessagesResources.RoleGroup_NotExists); } role.RoleGroup = group; if (role.Name.IsNullOrBlank()) { throw new DefinedException(UserSystemMessagesResources.Name_Empty); } if (_Repository.Exists(role)) { throw new DataExistsException(string.Format(UserSystemMessagesResources.Role_Exists_WithValue, role.Name)); } _Repository.Add(role); #region 操作日志 var roleDto = role.ToDto(); OperateRecorder.RecordOperation(roleDto.Id.ToString(), UserSystemMessagesResources.Add_Role, roleDto.GetOperationLog()); #endregion //commit the unit of work _Repository.UnitOfWork.Commit(); return(role.ToDto()); }
public void CreateUser(String email, string password, string userRole) { var usermanager = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(new ApplicationDbContext())); if (usermanager.FindByName("manager") == null) { var user = new ApplicationUser(); user.Id = IdentityGenerator.NewSequentialGuid().ToString(); user.UserName = email; user.Email = email; string pass = password; var newUser = usermanager.Create(user, pass); if (newUser.Succeeded) { //var userRole = new ApplicationUser(); usermanager.AddToRole(user.Id, userRole); } } }
public void TestSavePushMessage() { BuildMessageBusiness buildBus = new BuildMessageBusiness(); PushMessageBusiness pushBus = new PushMessageBusiness(); NotifyMessage mess = new NotifyMessage() { MessageId = IdentityGenerator.New(), AppId = "11012", MessagePriority = MessagePriorityEnum.High, MessageKey = MessagePriorityEnum.High.ToString() + "_" + new Random().Next(1, 11).ToString(), MessageType = "OrderTicketOut", NotifyData = "a=1&b=2", SourceFrom = "test", ClientIP = "127.0.0.1" }; List <PushMessageModel> list = buildBus.GetType().InvokeMember("BuildMessage", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Instance, System.Type.DefaultBinder, buildBus, new object[] { mess }) as List <PushMessageModel>; pushBus.Save(list); }
public void CompareWhenLeftIsNullAndRightIsNullReturnFalseTest() { //Arrange TestEntity entityLeft = null; TestEntity entityRight = new TestEntity(); entityRight.Id = IdentityGenerator.SequentialGuid();; //Act if (!(entityLeft == (EntityBase)null))//this perform ==(left,right) { Assert.Fail(); } if (!(entityRight != (EntityBase)null))//this perform !=(left,right) { Assert.Fail(); } }
public async Task <IActionResult> CreateUserAsync([FromBody] RegisterIM model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } var result = await _context.Users.CountAsync(d => d.Email == model.Email); if (result > 0) { return(BadRequest("邮箱已存在")); } result = await _context.Users.CountAsync(d => d.Username == model.UserName); if (result > 0) { return(BadRequest("用户名已存在")); } var securityStamp = EncryptionHelper.GenerateSalt(); var passwordHash = EncryptionHelper.HashPasswordWithSalt(model.Password, securityStamp); var newUser = new User() { Id = IdentityGenerator.SequentialGuid(), Username = model.UserName, Email = model.Email, SecurityStamp = Convert.ToBase64String(securityStamp), PasswordHash = passwordHash, CreateDate = DateTime.Now, IsActive = true, }; _context.Add(newUser); await _context.SaveChangesAsync(); return(Ok("用户创建成功")); }
public void Edit_AdminInstance_CallsStoredProcedureExecutionForAdminAccountEdit() { //prepare IMembershipRepository membershipRepository = _kernel.Get <IMembershipRepository>(); var adminMock2 = _kernel.GetMock <IUserAccount>(); adminMock2.SetupProperty(x => x.ID, IdentityGenerator.NewSequentialGuid()); adminMock2.SetupProperty(x => x.AccountCreationDateTime, DateTime.Now); adminMock2.SetupProperty(x => x.AccountStatus, AccountStatusOptions.Active); adminMock2.SetupProperty(x => x.EmailAddress, "*****@*****.**"); adminMock2.SetupProperty(x => x.FirstName, "Jalal"); adminMock2.SetupProperty(x => x.LastName, "Uddin"); adminMock2.SetupProperty(x => x.LastWrongPasswordAttemptDateTime, DateTime.Now.AddDays(-2)); adminMock2.SetupProperty(x => x.MobileNumber, "8801737364773"); adminMock2.SetupProperty(x => x.EncryptedPassword, "testpass123"); adminMock2.SetupProperty(x => x.WrongPasswordAttempt, 0); _kernel.GetMock <IDbCommandFactory>().Setup(x => x.CreateParameter(It.IsAny <string>(), It.IsAny <object>())) .Returns(new SqlParameter("parameter", "parameter value")); _kernel.GetMock <IDbCommandFactory>().Setup(x => x.CreateCommand("AdminAccount_Edit", It.IsAny <object[]>())) .Returns(new SqlCommand("AdminAccount_Edit") { CommandType = System.Data.CommandType.StoredProcedure }); _kernel.GetMock <IDbCommandExecutionService>().Setup(x => x.ExecuteCommand( It.Is <DbCommand>(y => y.CommandType == System.Data.CommandType.StoredProcedure && y.CommandText == "AdminAccount_Edit"))).Verifiable(); // act membershipRepository.Edit(adminMock2.Object); // assert _kernel.GetMock <IDbCommandExecutionService>().VerifyAll(); }
public async Task RemoveCollectionWithCaching() { var identities = new List <Identity> { IdentityGenerator.Default, IdentityGenerator.Generate() }; await _identityRepository.AddAsync(identities, addToCache : true); Assert.Equal(2, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(0, _cache.Misses); await _identityRepository.RemoveAsync(identities); Assert.Equal(0, _cache.Count); Assert.Equal(0, _cache.Hits); Assert.Equal(0, _cache.Misses); await _client.RefreshAsync(); Assert.Equal(0, await _identityRepository.CountAsync()); }
public void InsertTest() { var sw = new Stopwatch(); TimeSpan timeCost; using (var unitOfWork = new RuicoUnitOfWork()) { sw.Start(); #region Add var roleGroup = new RoleGroup() { Id = IdentityGenerator.NewSequentialGuid(), Name = "角色组", Description = "remark", Created = DateTime.UtcNow }; unitOfWork.RoleGroups.Add(roleGroup); unitOfWork.Roles.Add(new Role() { Id = IdentityGenerator.NewSequentialGuid(), Name = "系统管理员", Description = "remark", RoleGroup = roleGroup, Created = DateTime.UtcNow }); #endregion unitOfWork.DbContext.SaveChanges(); sw.Stop(); timeCost = sw.Elapsed; } Console.WriteLine("Elapsed: " + timeCost.Ticks); }
private void ValidateModel(Member model) { if (model.Name.IsNullOrBlank()) { throw new DefinedException(CommonMessageResources.Name_Empty); } if (model.Userid.IsNullOrBlank()) { throw new DefinedException(HrMessagesResources.Member_UserId_Empty); } if (_Repository.Exists(model)) { throw new DataExistsException(string.Format(HrMessagesResources.Member_Exists_WithValue, string.Format("Userid:{0},WeixinId:{1},Email{2}", model.Userid, model.WeixinId, model.Email))); } if (model.Departments.Count > 0) { var departments = new List <Domain.HrModule.Entities.Department>(); foreach (var dep in model.Departments) { var existDep = _DepartmentRepository.Find(x => x.DepartmentId == dep.DepartmentId); if (existDep != null) { departments.Add(existDep); } else { dep.Id = IdentityGenerator.NewSequentialGuid(); dep.Created = DateTime.UtcNow; _DepartmentRepository.Add(dep); departments.Add(dep); } } model.Departments = departments; } }
public Task <Guid> CreateGenExpense(GenExpenseObject obj) { return(Task.Run(() => { try { if (obj.Id == Guid.Empty) { var dataObj = new MapperConfiguration(doj => { doj.CreateMap <GenExpenseObject, GenExpense>(); }); IMapper iMapper = dataObj.CreateMapper(); var source = new GenExpense(); source.Id = IdentityGenerator.NewSequentialGuid(); source.Amount = obj.Amount; source.Description = obj.Description; source.Purpose = obj.Purpose; source.ExpenseDate = obj.ExpenseDate; genExpenseRepo.Add(source); genExpenseRepo.UnitofWork.Commit(); return source.Id; } else { throw new InvalidOperationException(); } } catch (Exception) { throw; } })); }
public Task <Guid> CreateExpense(ExpenseObject obj) { return(Task.Run(() => { try { if (obj.Id == Guid.Empty) { var dataObj = new MapperConfiguration(ap => { ap.CreateMap <ExpenseObject, Expense>(); }); IMapper iMapper = dataObj.CreateMapper(); var source = new Expense(); source.Id = IdentityGenerator.NewSequentialGuid(); source.Amount = obj.Amount; source.Date = obj.Date; source.Details = obj.Details; expenseRepo.Add(source); expenseRepo.UnitofWork.Commit(); return source.Id; } else { throw new InvalidOperationException(); } } catch (Exception) { throw; } })); }
public async Task GetAllWithPaging() { var identity1 = await _identityRepository.AddAsync(IdentityGenerator.Default); Assert.NotNull(identity1?.Id); var identity2 = await _identityRepository.AddAsync(IdentityGenerator.Generate()); Assert.NotNull(identity2?.Id); await _client.RefreshAsync(); var results = await _identityRepository.GetAllAsync(paging : new PagingOptions().WithLimit(1)); Assert.NotNull(results); Assert.Equal(1, results.Documents.Count); Assert.Equal(1, results.Page); Assert.True(results.HasMore); Assert.Equal(2, results.Total); Assert.True(await results.NextPageAsync()); Assert.Equal(1, results.Documents.Count); Assert.Equal(2, results.Page); Assert.Equal(2, results.Total); Assert.False(results.HasMore); var secondDoc = results.Documents.First(); Assert.False(await results.NextPageAsync()); Assert.Equal(0, results.Documents.Count); Assert.Equal(2, results.Page); Assert.False(results.HasMore); Assert.Equal(2, results.Total); var secondPageResults = await _identityRepository.GetAllAsync(paging : new PagingOptions().WithPage(2).WithLimit(1)); Assert.Equal(secondDoc, secondPageResults.Documents.First()); //TODO Ensure we are using snapshot paging... }
public async Task RemoveAllWithDeleteByQueryAsync() { const int COUNT = 10000; Log.SetLogLevel <IdentityWithNoCachingRepository>(LogLevel.Information); await _identityRepositoryWithNoCaching.AddAsync(IdentityGenerator.GenerateIdentities(COUNT), o => o.ImmediateConsistency()); Log.SetLogLevel <IdentityWithNoCachingRepository>(LogLevel.Trace); var disposables = new List <IDisposable>(2); var countdownEvent = new AsyncCountdownEvent(1); try { disposables.Add(_identityRepositoryWithNoCaching.DocumentsRemoving.AddSyncHandler((o, args) => { countdownEvent.Signal(); })); disposables.Add(_identityRepositoryWithNoCaching.DocumentsRemoved.AddSyncHandler((o, args) => { countdownEvent.Signal(); })); var sw = Stopwatch.StartNew(); Assert.Equal(COUNT, await _identityRepositoryWithNoCaching.RemoveAllAsync(o => o.ImmediateConsistency(true))); sw.Stop(); _logger.LogInformation($"Deleted {COUNT} documents in {sw.ElapsedMilliseconds}ms"); await countdownEvent.WaitAsync(new CancellationTokenSource(TimeSpan.FromMilliseconds(250)).Token); Assert.Equal(0, countdownEvent.CurrentCount); Assert.Equal(0, await _identityRepositoryWithNoCaching.CountAsync()); } finally { foreach (var disposable in disposables) { disposable.Dispose(); } disposables.Clear(); } }
public async Task <ActionResult> Create([Bind(Include = "ChargeScheduleName,Description,EffectiveDate")] ChargeScheduleViewModel chargeScheduleModel) { chargeScheduleModel.IsActive = false; chargeScheduleModel.CreatedBy = User.Identity.Name; chargeScheduleModel.DateCreated = DateTime.Now; try { chargeScheduleModel.ChargeScheduleId = IdentityGenerator.NewSequentialGuid(); var chargeSchedule = Map <ChargeScheduleViewModel, ChargeSchedule>(chargeScheduleModel); db.ChargeSchedules.Add(chargeSchedule); await db.SaveChangesAsync(); TempData.Clear(); TempData.Add("ChargeScheduleId", chargeSchedule.ChargeScheduleId); return(RedirectToAction("Index")); } catch (Exception ex) { ModelState.AddModelError("*", ex); return(View(chargeScheduleModel)); } }
public async Task GetAllWithSnapshotPagingAsync() { var identity1 = await _identityRepository.AddAsync(IdentityGenerator.Default, o => o.ImmediateConsistency()); Assert.NotNull(identity1?.Id); var identity2 = await _identityRepository.AddAsync(IdentityGenerator.Generate(), o => o.ImmediateConsistency()); Assert.NotNull(identity2?.Id); var results = await _identityRepository.GetAllAsync(o => o.PageLimit(1).SnapshotPagingLifetime(TimeSpan.FromMinutes(1))); Assert.NotNull(results); Assert.Equal(1, results.Documents.Count); Assert.Equal(1, results.Page); Assert.True(results.HasMore); Assert.Equal(identity1.Id, results.Documents.First().Id); Assert.Equal(2, results.Total); Assert.True(await results.NextPageAsync()); Assert.Equal(1, results.Documents.Count); Assert.Equal(2, results.Page); Assert.Equal(2, results.Total); Assert.Equal(identity2.Id, results.Documents.First().Id); // TODO: Figure out why this is true when there are no more results Assert.True(results.HasMore); var secondDoc = results.Documents.First(); Assert.False(await results.NextPageAsync()); Assert.Equal(0, results.Documents.Count); Assert.Equal(2, results.Page); Assert.False(results.HasMore); Assert.Equal(2, results.Total); var secondPageResults = await _identityRepository.GetAllAsync(o => o.PageNumber(2).PageLimit(1)); Assert.Equal(secondDoc, secondPageResults.Documents.First()); }
public UserDTO Add(UserDTO userDTO) { var user = userDTO.ToModel(); user.Id = IdentityGenerator.NewSequentialGuid(); user.Created = DateTime.UtcNow; user.LastLogin = Const.SqlServerNullDateTime; user.PwdSalt = Guid.NewGuid().ToString(); if (user.Name.IsNullOrBlank()) { throw new DataExistsException(UserSystemResource.Common_Name_Empty); } if (_Repository.Exists(user)) { throw new DataExistsException(UserSystemResource.User_Exists); } user.LoginPwd = AuthService.EncryptPassword(user.LoginPwd, user.PwdSalt); _Repository.Add(user); //commit the unit of work _Repository.UnitOfWork.Commit(); return(user.ToDto()); }
public AppMenuDTO Add(AppMenuDTO itemDto) { var model = itemDto.ToModel(); model.Id = IdentityGenerator.NewSequentialGuid(); model.Created = DateTime.UtcNow; if (model.Parent != null && model.Parent.Id != Guid.Empty) { model.Parent = _Repository.Get(itemDto.Parent.Id); } // 数据验证 this.ValidateModel(model); _Repository.Add(model); this.OperationLog(WeixinMessagesResources.Add_AppMenu, model.ToDto(), null); //commit the unit of work _Repository.UnitOfWork.Commit(); return(model.ToDto()); }
public async Task AddAsync() { var identity1 = await _identityRepository.AddAsync(IdentityGenerator.Generate()); Assert.NotNull(identity1?.Id); var disposables = new List <IDisposable>(2); var countdownEvent = new AsyncCountdownEvent(2); try { var identity2 = IdentityGenerator.Default; disposables.Add(_identityRepository.DocumentsAdding.AddSyncHandler((o, args) => { Assert.Equal(identity2, args.Documents.First()); countdownEvent.Signal(); })); disposables.Add(_identityRepository.DocumentsAdded.AddSyncHandler((o, args) => { Assert.Equal(identity2, args.Documents.First()); countdownEvent.Signal(); })); var result = await _identityRepository.AddAsync(identity2); Assert.Equal(IdentityGenerator.Default.Id, result.Id); await countdownEvent.WaitAsync(new CancellationTokenSource(TimeSpan.FromMilliseconds(250)).Token); Assert.Equal(0, countdownEvent.CurrentCount); } finally { foreach (var disposable in disposables) { disposable.Dispose(); } disposables.Clear(); } }
public UserDTO Add(UserDTO userDTO) { var user = userDTO.ToModel(); user.Id = IdentityGenerator.NewSequentialGuid(); user.Created = DateTime.UtcNow; if (user.Name.IsNullOrBlank()) { throw new DataExistsException(UserSystemResource.Common_Name_Empty); } if (_Repository.Exists(user)) { throw new DataExistsException(UserSystemResource.User_Exists); } _Repository.Add(user); //commit the unit of work _Repository.UnitOfWork.Commit(); return(user.ToDto()); }