/// <summary> /// 保存配置实例。 /// </summary> /// <param name="site">当前配置实例。</param> /// <returns>返回数据结果。</returns> public virtual DataResult Save(SiteBase site) { var adapter = site.ToStore(); if (adapter.SiteId > 0) { return(DataResult.FromResult(_sdb.Update(adapter), DataAction.Updated)); } if (IsDuplicated(site)) { return(DataResult.FromResult(_sdb.Update(x => x.SiteKey == adapter.SiteKey, new { adapter.SiteName, adapter.UpdatedDate, adapter.SettingValue }), DataAction.Updated)); } return(DataResult.FromResult(_sdb.BeginTransaction(db => { if (!db.Create(adapter)) { return false; } site.SiteId = adapter.SiteId; foreach (var handler in _handlers) { if (!handler.OnCreate(db, site)) { return false; } } return true; }), DataAction.Created)); }
public async Task TransactionTest() { var user = new User { Name = "Sergey_Transaction" }; using (var trans = _db.BeginTransaction()) { await _db.Users.InsertAsync(user, trans); trans.Rollback(); } var userFromDb = await _db.Users.FindAsync(x => x.Name == "Sergey_Transaction"); Assert.Null(userFromDb); using (var trans = _db.BeginTransaction()) { await _db.Users.InsertAsync(user, trans); trans.Commit(); } userFromDb = await _db.Users.FindAsync(x => x.Name == "Sergey_Transaction"); Assert.NotNull(userFromDb); }
public dynamic DeleteAggregate() { int id = this.Request.Form["id"]; _dbContext.BeginTransaction(); _deleteProjectRequestAggregateCommand.Execute(id); _dbContext.Commit(); return(HttpStatusCode.OK); }
public long Add(TEntity obj) { using (var trans = _uow.BeginTransaction()) { _uow.GetEntity <TEntity>().Add(obj); trans.Commit(); _uow.Commit(); return(obj.Id); } }
/// <summary> /// 设置默认。 /// </summary> /// <param name="siteId">网站Id。</param> /// <param name="domain">域名。</param> /// <returns>返回设置结果。</returns> public virtual bool SetDefault(int siteId, string domain) { if (_sddb.BeginTransaction(db => { db.Update(x => x.SiteId == siteId, new { IsDefault = false }); db.Update(x => x.SiteId == siteId && x.Domain == domain, new { IsDefault = true }); return(true); })) { _cache.Remove(_cacheKey); return(true); } return(false); }
/// <summary> /// 更新管理员权限配置。 /// </summary> /// <returns>返回更新结果。</returns> public bool RefreshOwners() { var roleId = GetOwnerId(); if (roleId == 0) { return(false); } var permissions = EnsuredProviderPermissions(); if (_prdb.BeginTransaction(db => { foreach (var permission in permissions) { if (db.Any(x => x.PermissionId == permission.Id && x.RoleId == roleId)) { continue; } db.Create(new PermissionInRole { PermissionId = permission.Id, RoleId = roleId, Value = PermissionValue.Allow }); } return(true); })) { RemoveCache(); return(true); } return(false); }
private void InterceptAsync(IInvocation invocation, TransactionalAttribute attribute) { _logger.LogInformation($"BeginTransaction with IsolationLevel: {attribute.IsolationLevel}"); _dbContext.BeginTransaction(attribute.IsolationLevel); try { invocation.Proceed(); } catch (Exception) { _dbContext.RollbackTransaction(); throw; } if (invocation.Method.ReturnType == typeof(Task)) { invocation.ReturnValue = InterceptAsync((Task)invocation.ReturnValue, _dbContext); } else //Task<TResult> { invocation.ReturnValue = typeof(TransactionInterceptor) .GetMethod(nameof(InterceptWithResultAsync), BindingFlags.NonPublic | BindingFlags.Static) ?.MakeGenericMethod(invocation.Method.ReturnType.GenericTypeArguments[0]) .Invoke(null, new[] { invocation.ReturnValue, _dbContext }); } }
public dynamic Save() { SaveLogFileViewModel model = this.Bind <SaveLogFileViewModel>(); // make sure the processing directory exists _dirWrap.CreateDirectory(_appSettings.LogFileProcessingDirectory); foreach (HttpFile f in Request.Files) { // save the file to disk string filePath = Path.Combine(_appSettings.LogFileProcessingDirectory, f.Name); using (var fileStream = File.Create(filePath)) { f.Value.Seek(0, SeekOrigin.Begin); f.Value.CopyTo(fileStream); } // create the log file record - this will kick off the job to actually process the file try { _dbContext.BeginTransaction(); _createLogFileCommand.Execute(model.ProjectId, filePath); _dbContext.Commit(); } catch (Exception ex) { _dbContext.Rollback(); return(this.Response.AsJson <string>(ex.Message, HttpStatusCode.BadRequest)); } } return(HttpStatusCode.OK); }
public virtual Task <bool> AddAsync(List <TEntity> list, IDbTransaction transaction = null) { if (list == null || !list.Any()) { return(Task.FromResult(false)); } if (transaction == null) { transaction = DbContext.BeginTransaction(); } try { foreach (var enitty in list) { AddAsync(enitty, transaction); } transaction.Commit(); return(Task.FromResult(true)); } catch { transaction.Rollback(); transaction.Connection.Close(); throw; } }
/// <summary> /// 添加对象对比实例。 /// </summary> /// <param name="differ">对象对比实例。</param> /// <returns>返回添加结果。</returns> public virtual bool Create(IObjectDiffer differ) { return(_db.BeginTransaction(db => { foreach (var item in differ) { db.Create(item); } return true; }, 300)); }
public async Task DeleteAllAsync(DeleteAllDto dto) { using (var transaction = _dbContext.BeginTransaction()) { var tasks = dto.Ids.Select(x => DeleteEntityAsync(x)); await Task.WhenAll(tasks); await transaction.CommitAsync(); } }
public async Task HandleAsync(DeleteAllProductsCommand request) { using (var transaction = _dbContext.BeginTransaction()) { foreach (var id in request.Dto.Ids) { await _commandDispatcher.SendAsync(new DeleteProductCommand { Id = id }); } await transaction.CommitAsync(); } }
protected override void PreProceed(IInvocation invocation) { stopwatch.Restart(); var method = invocation.MethodInvocationTarget; if (method?.GetCustomAttribute <TransactionalAttribute>() != null) { //_logger.LogInformation($"{invocation.Method.Name}事务拦截前"); _dbContext.BeginTransaction(); } }
public void ExecuteResetProcessedLogFileJob(int logFileId) { using (IDbContext dbContext = _dbContextFactory.GetDbContext()) { ISetLogFileUnprocessedCommand cmd = new SetLogFileUnprocessedCommand(dbContext , new JobRegistrationService() ); dbContext.BeginTransaction(); cmd.Execute(logFileId); dbContext.Commit(); } }
public void Delete() { _dbContext.BeginTransaction(); long id = _dbContext.Insert <Employee>(new Employee { EmpName = "test" }); _dbContext.Delete <Employee>(id); _dbContext.Commit(); var employee = _dbContext.QueryWhere <Employee>($"Id={id}"); Assert.NotNull(employee); Assert.Equal(0, employee?.Count()); }
public void DbTransaction(Action <IDbContext> action) { try { _dbContext.BeginTransaction(); action?.Invoke(_dbContext); _dbContext.Commit(); } catch (Exception ex) { _dbContext.Rollback(); _logger.LogError(ex.Message); } }
protected override async Task HandleAsync(DeleteAllProductsCommand request) { using (var transaction = _dbContext.BeginTransaction()) { foreach (var id in request.Dto.Ids) { var command = new DeleteProductCommand { Id = id }; await _handlerDispatcher.SendAsync(command); } await transaction.CommitAsync(); } }
/// <summary> /// Registers a background job that runs through all the requests for a specific log file, and recalculates the aggregates /// for those requests using the project aggregates set by the user. /// </summary> /// <param name="logFileId"></param> public void ExecuteAggregateRequestJob(int logFileId) { using (IDbContext dbContext = _dbContextFactory.GetDbContext()) { IResetRequestAggregatesCommand cmd = new ResetRequestAggregatesCommand(dbContext , new LogFileRepository(dbContext) , new RequestRepository(dbContext) , new ProjectRequestAggregateRepository(dbContext) , new RequestAggregationService() ); dbContext.BeginTransaction(); cmd.Execute(logFileId); dbContext.Commit(); } }
/// <summary> /// Job registered once a file has been uploaded, to process the contents of the log file. /// </summary> /// <param name="logFileId"></param> /// <param name="filePath"></param> public void ExecuteProcessLogFileJob(int logFileId, string filePath) { using (IDbContext dbContext = _dbContextFactory.GetDbContext()) { IProcessLogFileCommand cmd = new ProcessLogFileCommand(dbContext , new LogFileRepository(dbContext) , new CreateRequestBatchCommand(dbContext, new RequestValidator()) , new JobRegistrationService() , new FileWrap() ); dbContext.BeginTransaction(); cmd.Execute(logFileId, filePath); dbContext.Commit(); } }
/// <summary> /// Use/Override the render function so that rendering takes place at the right time /// </summary> /// <param name="output"></param> protected override void Render(System.Web.UI.HtmlTextWriter output) { DataPersister persister = new DataPersister(); IDbContext dbcontext = persister.getDBContext(); dbcontext.BeginTransaction(); try { output.Write(ParentControl.RenderToString(ControlDefnToRender, LangToRenderFor)); dbcontext.CommitTransaction(); } catch { dbcontext.RollbackTransaction(); throw; } }
protected override async Task HandleAsync(DeleteAllProductsCommand request) { using (var transaction = _context.BeginTransaction()) { var tasks = request.Dto.Ids.Select(x => { var command = new DeleteProductCommand { Id = x }; return(_handlerDispatcher.SendAsync <DeleteProductCommand, Task>(command)); } ); await Task.WhenAll(tasks); await transaction.CommitAsync(); } }
public dynamic ProjectSave() { ProjectFormViewModel model = this.Bind <ProjectFormViewModel>(); ProjectModel project = Mapper.Map <ProjectFormViewModel, ProjectModel>(model); ValidationResult validationResult = _projectValidator.Validate(project); if (validationResult.Success) { _dbContext.BeginTransaction(); project = _createProjectCommand.Execute(project); _dbContext.Commit(); } SaveResultModel result = new SaveResultModel(project.Id.ToString(), validationResult.Success, validationResult.Messages.ToArray()); return(this.Response.AsJson(result)); }
/// <summary> /// 将API设置到应用中。 /// </summary> /// <param name="appid">应用程序Id。</param> /// <param name="apis">API的Id列表。</param> /// <returns>返回保存结果。</returns> public virtual DataResult AddApis(int appid, int[] apis) { return(Result(_context.BeginTransaction(db => { var asdb = db.As <ApplicationService>(); asdb.Delete(x => x.AppicationId == appid); if (apis?.Length > 0) { foreach (var api in apis) { asdb.Create(new ApplicationService { AppicationId = appid, ServiceId = api }); } } return true; }), DataAction.Updated)); }
// not-atomic example public bool RecordUserActivity(UserModel user, IEnumerable <UserActivity> activities) { try { _dbContext.BeginTransaction(); // messy example _dbContext.UserLogins .Add(activities.Where(x => x.ActivityType == ActivityTypes.Logins)); _dbContext.UserEdits .Add(activities.Where(x => x.ActivityType == ActivityTypes.Edits)); // _dbContext.CommitTransaction(); return(true); } catch (Exception ex) { // log your exceptions! _dbContext.RollbackTransaction(); } return(false); }
public void SetUp() { mocks = new MockRepository(); gameService = mocks.DynamicMock <IGameService>(); repository = mocks.DynamicMock <IRepository <Game> >(); dbContext = mocks.DynamicMock <IDbContext>(); service = new RecalcGameStateService(1, repository, gameService); game = new Game { GameState = GameStates.Started, GameDate = new DateTime(2010, 1, 1, 21, 0, 0), TotalTime = 540, TimePerTask = 90, TimePerTip = 30 }; task1 = new Task(); task1Tip0 = new Tip { SuspendTime = 0, Task = task1 }; task1Tip1 = new Tip { SuspendTime = 30, Task = task1 }; task1Tip2 = new Tip { SuspendTime = 60, Task = task1 }; task1.Tips.Add(task1Tip0); task1.Tips.Add(task1Tip1); task1.Tips.Add(task1Tip2); task1.Codes.Add(new Code { Name = "1", Task = task1 }); game.Tasks.Add(task1); Expect.Call(repository.DbContext).Return(dbContext).Repeat.Any(); Expect.Call(dbContext.BeginTransaction()).Repeat.Any(); Expect.Call(() => dbContext.CommitTransaction()).Repeat.Any(); }
/// <summary> /// 事务 /// </summary> /// <param name="sample">The sample.</param> /// <param name="sample2">The sample2.</param> /// <returns></returns> public bool CreateWithTransaction(EFSample sample, EFSample sample2) { bool result = true; using (IDbContext dbcontext = _contextFactory.Create()) { try { dbcontext.BeginTransaction();//开启事务 dbcontext.Create(sample); dbcontext.Create(sample2); dbcontext.Commit(); } catch (Exception) { dbcontext.Rollback(); result = false; } } return(result); }
public async Task test() { Agent entity2 = new Agent(); entity2.Id = entity2.CreateId(); entity2.Name = "111"; entity2.ContactNumber = "111"; entity2.Key = "111"; entity2.Secret = "111"; entity2.Remarks = "111"; await _agentRep.InsertAsync(entity2); context.BeginTransaction(); Agent entity = new Agent(); entity.Id = entity.CreateId(); entity.Name = "111"; entity.ContactNumber = "111"; entity.Key = "111"; entity.Secret = "111"; entity.Remarks = "111"; int r = await _agentRep.InsertAsync(entity); context.Commit(); Agent entity3 = new Agent(); entity3.Id = entity3.CreateId(); entity3.Name = "111"; entity3.ContactNumber = "111"; entity3.Key = "111"; entity3.Secret = "111"; entity3.Remarks = "111"; await _agentRep.InsertAsync(entity3); }
private void EnsureApiServices(IApiDescriptionGroupCollectionProvider provider) { var services = provider.ApiDescriptionGroups.Items .SelectMany(x => x.Items) .ToList(); _apis.BeginTransaction(db => { db.Update(new { Disabled = true }); foreach (var service in services) { var name = service.RelativePath.ToLower(); var description = service.GetDescription(); var descriptor = db.Find(x => x.Name == name); if (descriptor == null) { descriptor = new ApiDescriptor { Name = name, Description = description }; db.Create(descriptor); } else { descriptor.Disabled = false; if (description != null) { descriptor.Description = description; } db.Update(descriptor); } } return(true); }); }
/// <summary> /// 从数据库中加载调度任务 /// </summary> /// <returns></returns> public List <JobInfo> LoadJobFromDB() { List <JobInfo> jobInfos = new List <JobInfo>(); DynamicParameters parameters = new DynamicParameters(); parameters.Add("JobState", JobState.Enabled); IEnumerable <FapJob> jobList = _dbContext.Query <FapJob>($"select * from FapJob where JobState=@JobState", parameters); if (jobList != null && jobList.Any()) { foreach (var job in jobList) { JobInfo jobInfo = null; //更新执行状态 job.ExecState = ExecuteStatus.Execing; jobInfo = this.GetJobInfo(job); if (jobInfo != null) { jobInfos.Add(jobInfo); } } try { _dbContext.BeginTransaction(); _dbContext.Execute($"update FapJob set ExecState='{ExecuteStatus.Execing}' where Id in({string.Join(',', jobList.Select(j => j.Id))})"); _dbContext.Execute($"update FapJob set ExecState='{ExecuteStatus.NoExec}' where Id not in({string.Join(',', jobList.Select(j => j.Id))})"); _dbContext.Commit(); } catch (Exception) { _dbContext.Rollback(); } } return(jobInfos); }
public TransactionScope() { _dbContext = SmartServiceLocator<IDbContext>.GetService(); _dbContext.BeginTransaction(); }
public void BeginTransaction() { _context.BeginTransaction(); }
public void SetUp() { mocks = new MockRepository(); gameService = mocks.DynamicMock<IGameService>(); repository = mocks.DynamicMock<IRepository<Game>>(); dbContext = mocks.DynamicMock<IDbContext>(); service = new RecalcGameStateService(1, repository, gameService); game = new Game { GameState = GameStates.Started, GameDate = new DateTime(2010, 1, 1, 21, 0, 0), TotalTime = 540, TimePerTask = 90, TimePerTip = 30 }; task1 = new Task(); task1Tip0 = new Tip { SuspendTime = 0, Task = task1 }; task1Tip1 = new Tip { SuspendTime = 30, Task = task1 }; task1Tip2 = new Tip { SuspendTime = 60, Task = task1 }; task1.Tips.Add(task1Tip0); task1.Tips.Add(task1Tip1); task1.Tips.Add(task1Tip2); task1.Codes.Add(new Code { Name = "1", Task = task1 }); game.Tasks.Add(task1); Expect.Call(repository.DbContext).Return(dbContext).Repeat.Any(); Expect.Call(dbContext.BeginTransaction()).Repeat.Any(); Expect.Call(() => dbContext.CommitTransaction()).Repeat.Any(); }