protected virtual void CreateOrMigrate(Tenant tenant, Action <MasterDbContext> seedAction) { var args = new DbPerTenantConnectionStringResolveArgs( tenant == null ? (int?)null : (int?)tenant.Id, tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant ); args["DbContextType"] = typeof(MasterDbContext); args["DbContextConcreteType"] = typeof(MasterDbContext); var nameOrConnectionString = ConnectionStringHelper.GetConnectionString( _connectionStringResolver.GetNameOrConnectionString(args) ); using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { using (var dbContext = _dbContextResolver.Resolve <MasterDbContext>(nameOrConnectionString, null)) { dbContext.Database.Migrate(); seedAction?.Invoke(dbContext); _unitOfWorkManager.Current.SaveChanges(); uow.Complete(); } } }
public async Task <SystemToken> SystemTokenList(string TokenType) { using (var unitOfWork = _unitOfWorkManager.Begin()) { var Tokens = new TencentTokens(); var SystemTokens = _repository.GetAll().Where(a => a.IsDelete == false && a.TokenType == TokenType); var TokenInfos = await SystemTokens.ToListAsync(); var TokenInfo = TokenInfos.FirstOrDefault(); if (TokenInfo != null) { // 如果数据超时了重新获取 if (TokenInfo.EffectiveTime <= DateTime.Now.AddHours(1)) { Tokens = tencentToken.TencentAccessToken(TokenInfo).Result; TokenInfo.access_token = Tokens.access_token; TokenInfo.EffectiveLength = int.Parse(Tokens.expires_in); TokenInfo.EffectiveTime = DateTime.Now.AddSeconds(TokenInfo.EffectiveLength); TokenInfo.TokenJson = JsonHelper.ToJson(Tokens); TokenInfo.RefreshEffectiveTime = DateTime.Now; TokenInfo = await _repository.UpdateAsync(TokenInfo); } if (string.IsNullOrEmpty(TokenInfo.access_token)) { Tokens = tencentToken.TencentAccessToken(TokenInfo).Result; TokenInfo.access_token = Tokens.access_token; TokenInfo.EffectiveLength = int.Parse(Tokens.expires_in); TokenInfo.EffectiveTime = DateTime.Now.AddSeconds(TokenInfo.EffectiveLength); TokenInfo.TokenJson = JsonHelper.ToJson(Tokens); TokenInfo.RefreshEffectiveTime = DateTime.Now; TokenInfo = await _repository.UpdateAsync(TokenInfo); } // 最后验证token有效性 var WeCharIP = tencentToken.WeCharIP(TokenInfo).Result; if (WeCharIP.ip_list == null) { Tokens = tencentToken.TencentAccessToken(TokenInfo).Result; TokenInfo.access_token = Tokens.access_token; TokenInfo.EffectiveLength = int.Parse(Tokens.expires_in); TokenInfo.EffectiveTime = DateTime.Now.AddSeconds(TokenInfo.EffectiveLength); TokenInfo.TokenJson = JsonHelper.ToJson(Tokens); TokenInfo.RefreshEffectiveTime = DateTime.Now; TokenInfo = await _repository.UpdateAsync(TokenInfo); } } else { // 当没数据时先获取数据再保存 Tokens = tencentToken.TencentAccessToken(TokenInfo).Result; TokenInfo.access_token = Tokens.access_token; TokenInfo.EffectiveLength = int.Parse(Tokens.expires_in); TokenInfo.EffectiveTime = DateTime.Now.AddSeconds(TokenInfo.EffectiveLength); TokenInfo.TokenJson = JsonHelper.ToJson(Tokens); TokenInfo.RefreshEffectiveTime = DateTime.Now; TokenInfo.Id = await _repository.InsertAndGetIdAsync(TokenInfo); } unitOfWork.Complete(); return(TokenInfo); } }
public void Intercept(IInvocation invocation) { MethodInfo methodInfo = invocation.MethodInvocationTarget; if (methodInfo == null) { methodInfo = invocation.Method; } //如果标记了 [UnitOfWork] if (!UnitOfWorkHelper.IsUnitOfWorkMethod(methodInfo, out var unitOfWorkAttribute)) { using (IUnitOfWork unitOfWork = unitOfWorkManager.Begin()) { try { invocation.Proceed(); unitOfWork.Commit(); } catch { unitOfWork.Rollback(); throw; } finally { unitOfWork.Dispose(); } } } else { invocation.Proceed(); } }
protected virtual void CreateOrMigrate(AbpTenantBase tenant) { var args = new DbPerTenantConnectionStringResolveArgs( tenant == null ? (int?)null : (int?)tenant.Id, tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant ); args["DbContextType"] = typeof(TDbContext); args["DbContextConcreteType"] = typeof(TDbContext); var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(_connectionStringResolver.GetNameOrConnectionString(args)); using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress)) { using (var dbContext = _iocResolver.ResolveAsDisposable <TDbContext>(new { nameOrConnectionString = nameOrConnectionString })) { var dbInitializer = new MigrateDatabaseToLatestVersion <TDbContext, TConfiguration>( true, new TConfiguration { Tenant = tenant }); dbInitializer.InitializeDatabase(dbContext.Object); _unitOfWorkManager.Current.SaveChanges(); uow.Complete(); } } }
public async Task <HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = new CancellationToken()) { try { using (var uow = _unitOfWorkManager.Begin()) { // Switching to host is necessary for single tenant mode. using (_unitOfWorkManager.Current.SetTenantId(null)) { if (!await _dbContextProvider.GetDbContext().Database.CanConnectAsync(cancellationToken)) { return(HealthCheckResult.Unhealthy( "HinnovaDbContext could not connect to database" )); } var user = await _dbContextProvider.GetDbContext().Users.AnyAsync(cancellationToken); uow.Complete(); if (user) { return(HealthCheckResult.Healthy("HinnovaDbContext connected to database and checked whether user added")); } return(HealthCheckResult.Unhealthy("HinnovaDbContext connected to database but there is no user.")); } } } catch (Exception e) { return(HealthCheckResult.Unhealthy("HinnovaDbContext could not connect to database.", e)); } }
public void OnActionExecuting(ActionExecutingContext filterContext) { if (filterContext.IsChildAction) { return; } var methodInfo = filterContext.ActionDescriptor.GetMethodInfoOrNull(); if (methodInfo == null) { return; } var unitOfWorkAttr = UnitOfWorkAttribute.GetUnitOfWorkAttributeOrNull(methodInfo) ?? _configuration.DefaultUnitOfWorkAttribute; if (unitOfWorkAttr.IsDisabled) { return; } SetCurrentUow( filterContext.HttpContext, _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions()) ); }
public bool Exist(string connectionString) { if (connectionString.IsNullOrEmpty()) { //connectionString is null for unit tests return(true); } try { using (var uow = _unitOfWorkManager.Begin()) { // Switching to host is necessary for single tenant mode. using (_unitOfWorkManager.Current.SetTenantId(null)) { _dbContextProvider.GetDbContext().Database.OpenConnection(); uow.Complete(); } } } catch { return(false); } return(true); }
public async Task GetClaimsAsync() { using (var uow = _unitOfWorkManager.Begin()) { var role = await _identityRoleRepository.FindByNormalizedNameAsync(_lookupNormalizer.Normalize("moderator")); role.ShouldNotBeNull(); var claims = await _identityRoleStore.GetClaimsAsync(role); claims.ShouldNotBeEmpty(); claims.ShouldContain(x => x.Type == "test-claim" && x.Value == "test-value"); await uow.CompleteAsync(); } }
//[Fact] public async Task ShouldRollbackTransactionOnFailure() { const string exceptionMessage = "This is a test exception!"; var blogName = Guid.NewGuid().ToString("N"); try { using (uowManager.Begin()) { await blogRepository.InsertAsync( new Blog(blogName, $"http://{blogName}.com/") ); throw new Exception(exceptionMessage); } } catch (Exception ex) when(ex.Message == exceptionMessage) { } await UsingDbContextAsync(async context => { var blog = await context.Blogs.FirstOrDefaultAsync(b => b.Name == blogName); blog.ShouldNotBeNull(); }); }
public async Task Role_Update_Event_Test() { var role = await RoleRepository .FindByNormalizedNameAsync(LookupNormalizer.NormalizeName("moderator")) ; var permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); permissionGrantsInRole.ShouldNotBeNull(); permissionGrantsInRole.Count.ShouldBeGreaterThan(0); var count = permissionGrantsInRole.Count; using (var uow = UowManager.Begin()) { var identityResult = await RoleManager.SetRoleNameAsync(role, "TestModerator"); identityResult.Succeeded.ShouldBeTrue(); var xx = await RoleRepository.UpdateAsync(role); await uow.CompleteAsync(); } role = await RoleRepository.GetAsync(role.Id); role.Name.ShouldBe("TestModerator"); permissionGrantsInRole = await PermissionGrantRepository.GetListAsync("R", role.Name); permissionGrantsInRole.Count.ShouldBe(count); }
public bool Exist(string connectionString) { if (connectionString.IsNullOrEmpty()) { //单元测试下连接字符串为空 return(true); } try { using (var uow = _unitOfWorkManager.Begin()) { // 在单租户模式下切换到host using (_unitOfWorkManager.Current.SetTenantId(null)) { _dbContextProvider.GetDbContext().Database.OpenConnection(); uow.Complete(); } } } catch { return(false); } return(true); }
public async Task Should_Automatically_Save_Changes_On_Uow() { int blog1Id; //Act using (var uow = _uowManager.Begin()) { var blog1 = await _blogRepository.SingleAsync(b => b.Name == "test-blog-1"); blog1Id = blog1.Id; blog1.Name = "test-blog-1-updated"; await uow.CompleteAsync(); } //Assert await UsingDbContextAsync(async context => { var blog1 = await context.Blogs.SingleAsync(b => b.Id == blog1Id); blog1.Name.ShouldBe("test-blog-1-updated"); }); }
public virtual async Task Should_Write_AuditLog_For_Entity_That_Property_Has_Audited_Attribute_And_Has_Changed_Even_Entity_Has_DisableAuditing_Attribute() { var entityId = Guid.NewGuid(); var repository = ServiceProvider.GetRequiredService <IBasicRepository <AppEntityWithDisableAuditingAndPropertyHasAudited, Guid> >(); await repository.InsertAsync(new AppEntityWithDisableAuditingAndPropertyHasAudited(entityId, "test name", "test name2", "test name3")); using (var scope = _auditingManager.BeginScope()) { using (var uow = _unitOfWorkManager.Begin()) { var entity = await repository.GetAsync(entityId); entity.Name = "new name1"; await repository.UpdateAsync(entity); await uow.CompleteAsync(); } await scope.SaveAsync(); } #pragma warning disable 4014 _auditingStore.Received().SaveAsync(Arg.Is <AuditLogInfo>(x => x.EntityChanges.Count == 1 && x.EntityChanges[0].PropertyChanges.Count == 1 && x.EntityChanges[0].PropertyChanges[0].PropertyName == nameof(AppEntityWithDisableAuditingAndPropertyHasAudited.Name))); #pragma warning restore 4014 }
public async Task Should_Rollback_Transaction_On_Failure() { const string exceptionMessage = "This is a test exception!"; string blogName = Guid.NewGuid().ToString("N"); try { using (_uowManager.Begin()) { await _blogRepository.InsertAsync( new Blog(blogName, $"http://{blogName}.com/") ); throw new Exception(exceptionMessage); } } catch (Exception ex) when(ex.Message == exceptionMessage) { } using (IUnitOfWorkCompleteHandle uow = The <IUnitOfWorkManager>().Begin()) { _blogRepository.FirstOrDefault(x => x.Name == blogName).ShouldBeNull(); uow.Complete(); } }
public void CloneAllEstimateDetails(int customerInvoiceId, int estimateId) { var estimate = _estimateRepository.Get(estimateId); if (estimate != null) { var tenantId = estimate.TenantId; var estimateDetailList = _estimateDetailRepository.GetAll() .Where(e => e.EstimateId == estimate.Id && !e.IsDeleted); if (estimateDetailList != null && estimateDetailList.Count() > 0) { foreach (var item in estimateDetailList) { CustomerInvoiceDetail customerInvoiceDetail = new CustomerInvoiceDetail() { Charge = item.Charge, CustomerInvoiceId = customerInvoiceId, Description = item.Description, Discount = item.Discount, Gross = item.Cost, Net = item.MarkUp, Quantity = item.Quantity, ItemTypeId = item.ItemTypeId, UomId = item.UomId, WorkOrderActionId = item.WorkOrderActionId, Tax = item.Tax, UnitPrice = item.UnitPrice }; if (tenantId != null) { customerInvoiceDetail.TenantId = (int?)tenantId; } using (var unitOfWork = _unitOfWorkManager.Begin()) { _customerInvoiceDetailRepository.InsertAndGetId(customerInvoiceDetail); unitOfWork.Complete(); unitOfWork.Dispose(); } } UpdateCustomerInvoicePrices(customerInvoiceId); } } }
/// <summary> /// 排课 /// </summary> /// <param name="input"></param> /// <returns></returns> public bool StudentArrangeCourse(CreateStudentCourseArrangeInput input) { Logger.Info("AddStudentCourseArrange: " + input); var arrange = input.MapTo <StudentCourseArrange>(); string studentIds = GenerateStudentIds(input); arrange.StudentId = studentIds; bool result = true; if (!string.IsNullOrEmpty(input.Id)) { result = !string.IsNullOrEmpty(_studentCourseArrangeRepository.Update(arrange).Id); } else { arrange.Id = IdentityCreator.NewGuid; arrange.ArrangeTime = DateTime.Now; arrange.CreatorUserId = AbpSession.UserId.Value; result = validDate(input); if (result) { if (input.CrossWeek != null && input.CrossWeek.Value) { StringBuilder builder = new StringBuilder(); using (var unitOfWork = _unitOfWorkManager.Begin()) //启用工作单元 { try { var lastDate = CalendarHelper.LastDayOfMonth(input.BeginTime); var crossTimes = Math.Floor(Convert.ToDecimal((lastDate.Day - input.BeginTime.Day) / 7)); for (int i = 0; i <= crossTimes; i++) { var newArrange = input.MapTo <StudentCourseArrange>(); newArrange.Id = IdentityCreator.NewGuid; newArrange.ArrangeTime = DateTime.Now; newArrange.CreatorUserId = AbpSession.UserId.Value; newArrange.StudentId = studentIds; newArrange.BeginTime = newArrange.BeginTime.Value.AddDays(7 * i); newArrange.EndTime = newArrange.EndTime.Value.AddDays(7 * i); _studentCourseArrangeRepository.Insert(newArrange); } unitOfWork.Complete(); //提交事务 } catch (Exception ex) { builder.AppendLine(ex.Message); } result = builder.Length == 0; } } else { result = !string.IsNullOrEmpty(_studentCourseArrangeRepository.Insert(arrange).Id); //.InsertOrUpdate(arrange); } } } return(result); }
public static void PerformSyncUow(this IUnitOfWorkManager unitOfWorkManager, Action action, UnitOfWorkOptions options = null) { using (var uow = unitOfWorkManager.Begin(options ?? DefaultUoWOptions)) { action(); uow.Complete(); } }
private async Task WithNewUowAsync(Func <Task> func) { using (var uow = _unitOfWorkManager.Begin(requiresNew: true)) { await func(); await uow.SaveChangesAsync(); } }
/// <summary> /// 驗證 PriceId /// </summary> /// <param name="priceId">price's table id</param> public bool PriceIdValidate(int priceId) { using (IUnitOfWork uow = _unitOfWorkManager.Begin()) { Prices price = uow.PricesRepository.Get(priceId); return(price != null); } }
public void Should_Set_CreatorUserId_When_DynamicInsert_Is_Enabled() { AbpSession.UserId = 1; using (var uow = _unitOfWorkManager.Begin()) { var book = _bookRepository.Get(1); book.ShouldNotBeNull(); book.Name = "Hitchhiker's Guide to the Galaxy"; _bookRepository.Update(book); uow.Complete(); } var book2 = _bookRepository.Get(1); book2.LastModifierUserId.ShouldNotBe(null); }
public override void InterceptSynchronous(IInvocation invocation) { var method = GetMethodInfo(invocation); var unitOfWorkAttr = _unitOfWorkOptions.GetUnitOfWorkAttributeOrNull(method); if (unitOfWorkAttr == null || unitOfWorkAttr.IsDisabled) { invocation.Proceed(); return; } using (var uow = _unitOfWorkManager.Begin(unitOfWorkAttr.CreateOptions())) { invocation.Proceed(); uow.Complete(); } }
public async Task <User> GetUserOrNullAsync(UserIdentifier userIdentifier) { using (_unitOfWorkManager.Begin()) { using (_unitOfWorkManager.Current.SetTenantId(userIdentifier.TenantId)) { return(await FindByIdAsync(userIdentifier.UserId)); } } }
private void PerformSyncUow(IInvocation invocation, UnitOfWorkOptions options) { using (var uow = _unitOfWorkManager.Begin(options)) { invocation.Proceed(); uow.Complete(); } }
public void Should_Trigger_Complete_On_Success() { var completed = false; var disposed = false; using (var uow = _unitOfWorkManager.Begin()) { uow.Completed += (o, e) => completed = true; uow.Disposed += (sender, args) => disposed = true; uow.Complete(); completed.ShouldBeTrue(); } disposed.ShouldBeTrue(); }
/// <summary> /// Create new record in the <see cref="NotificationMessage"/>. Is used for audit purposes and retries /// </summary> /// <param name="templateId">Id of the template</param> /// <param name="recipientId">Id of the person</param> /// <param name="fillData">fill data action (specific to the send type)</param> /// <returns></returns> protected async Task <Guid> CreateNotificationMessageAsync(Guid templateId, Guid?recipientId, Action <NotificationMessage> fillData) { var messageId = Guid.NewGuid(); using (var uow = UowManager.Begin(TransactionScopeOption.RequiresNew)) { // get template again to isolate sessions var localTemplate = await TemplateRepository.GetAsync(templateId); var localRecipient = recipientId.HasValue ? await PersonRepository.GetAsync(recipientId.Value) : null; var message = new NotificationMessage() { Id = messageId, Notification = localTemplate.Notification, Template = localTemplate, Recipient = localRecipient, Status = RefListNotificationStatus.Outgoing, TryCount = 0 }; fillData.Invoke(message); await NotificationMessageRepository.InsertAsync(message); await uow.CompleteAsync(); } return(messageId); }
public async Task <ActionResult> Create(CreateUserDto model, FormCollection collection) { if (ModelState.IsValid) { try { using (var uow = _unitOfWorkManager.Begin()) { model.IsActive = true; var userId = await _userAppService.CreateUser(model); var roles = await _roleAppService.GetRoles(new GetRolesInput()); var list = new List <UserRoleDto>(); foreach (var item in roles.Items) { var info = new UserRoleDto(); var chkName = "Role_" + item.Id; var chkVal = collection[chkName]; if (chkVal == "on") { info.RoleId = item.Id; info.UserId = userId; info.Status = true; list.Add(info); } } await _userAppService.CreateOrUpdate(list); await uow.CompleteAsync(); } var lang = string.Format(L("Created.RecordSucceed").Localize(), model.UserName); this.AddModelMessage("", lang, MessageTypes.Information); } catch (Exception ex) { this.AddModelMessage("exception", ex.Message); } } return(RedirectToAction("Index")); }
public virtual async Task HandleEventAsync(EntityCreatedEto <RefundEto> eventData) { using var uow = _unitOfWorkManager.Begin(isTransactional: true); using var changeTenant = _currentTenant.Change(eventData.Entity.TenantId); var refund = await _refundRepository.FindAsync(eventData.Entity.Id); if (refund != null) { return; } var payment = await _paymentRepository.FindAsync(eventData.Entity.PaymentId); if (payment == null) { return; } refund = _objectMapper.Map <RefundEto, Refund>(eventData.Entity); refund.SetRefundItems( _objectMapper.Map <List <RefundItemEto>, List <RefundItem> >(eventData.Entity.RefundItems)); refund.RefundItems.ForEach(item => { FillRefundItemStoreId(item); FillRefundItemOrderId(item); }); FillRefundItemOrderLines(refund); await _refundRepository.InsertAsync(refund, true); if (refund.CompletedTime.HasValue) { uow.OnCompleted(async() => await _distributedEventBus.PublishAsync(new EShopRefundCompletedEto { Refund = _objectMapper.Map <Refund, EShopRefundEto>(refund) })); } await uow.CompleteAsync(); }
protected virtual async Task SaveLogAsync(AuditLogInfo auditInfo) { using (var uow = _unitOfWorkManager.Begin(true)) { await _auditLogRepository.InsertAsync(new AuditLog(_guidGenerator, auditInfo)).ConfigureAwait(false); await uow.SaveChangesAsync().ConfigureAwait(false); } }
public void Should_Get_SoftDeleted_Entities_If_Filter_Is_Disabled() { using (_unitOfWorkManager.Begin()) using (_unitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete)) { var books = _booksRepository.GetAllList(); books.Any(x => x.IsDeleted).ShouldBe(true); } }
/// <summary> /// /// </summary> /// <param name="httpContext"></param> /// <returns></returns> public async Task Invoke(HttpContext httpContext) { using (var uow = _unitOfWorkManager.Begin()) { await _next(httpContext); await uow.CompleteAsync(httpContext.RequestAborted); } }