public void Add_ValidEntity_EntityAddedToDbContext() { FakeSet<User> setStub = new FakeSet<User>(); Mock<DbContext> contextStub = new Mock<DbContext>(); contextStub.Setup(c => c.Set<User>()).Returns(setStub); IInterceptorsResolver interceptorsResolver = new Mock<IInterceptorsResolver>().Object; UnitOfWork uof = new UnitOfWork(contextStub.BuildFactoryStub(), interceptorsResolver); User u = new User(); uof.Add(u); Assert.IsTrue(setStub.Values.Contains(u)); }
public JsonResult AddMainType(string dbName, string ParentId, string FullId) { MF_MainType mainType = new MF_MainType(); mainType.Id = GuidHelper.CreateTimeOrderID(); //非顶部节点 if (ParentId != dbName) { mainType.ParentId = ParentId; } mainType.FullId = FullId + "." + mainType.Id; mainType.DBName = dbName; mainType.Text = "新增节点"; UnitOfWork.Add(mainType); UnitOfWork.Commit(); return(Json(mainType)); }
public void Handle(AddWaiterCommand command) { if (UnitOfWork.AnyActual <Waiter>(x => x.User.Login == command.Login)) { throw new InvalidOperationException("Waiter with the same login exists."); } var secondHash = _passwordManager.CreateSecondHash(command.Login, command.Password); var addedUser = UnitOfWork.Add(new User() { SecondHash = secondHash, Login = command.Login }); UnitOfWork.Add(new Waiter() { FirstName = command.FirstName, LastName = command.LastName, User = addedUser }); }
public void Handle(CreateOrderCommand command) { Order item = null; OnCreateOrder(command, ref item); if (item == null) { item = new Order(DependencyResolver, Logger, command.Rsn == Guid.Empty ? Guid.NewGuid() : command.Rsn); UnitOfWork.Add(item); } item.CreateOrder(command.OrderId, command.CustomerId, command.EmployeeId, command.OrderDate, command.RequiredDate, command.ShippedDate, command.ShipViaId, command.Freight, command.ShipName, command.ShipAddress, command.ShipCity, command.ShipRegion, command.ShipPostalCode, command.ShipCountry); OnCreatedOrder(command, item); OnAddToUnitOfWork(command, item); UnitOfWork.Add(item); OnAddedToUnitOfWork(command, item); OnCommit(command, item); UnitOfWork.Commit(); OnCommited(command, item); }
public void Handle(AddWebClientCommand command) { if (UnitOfWork.AnyActual <WebClient>(x => x.User.Login == command.Login)) { throw new InvalidOperationException("Table with the same name exists."); } var login = command.Login; var secondHash = _passwordManager.CreateSecondHashFromFirst(command.FirstHash); var addedUser = UnitOfWork.Add(new User() { SecondHash = secondHash, Login = login }); UnitOfWork.Add(new WebClient { FirstName = command.FirstHash, LastName = command.LastName, Phone = command.Phone, Mail = command.Mail, User = addedUser }); }
public Guid CreateOtherEventSummary(Guid agencyId, string number, OtherEventSummaryDetails details) { EnsureNonExistingIdentifier <OtherEventSummary>(details.Id); // Verify that a summary doesn't already exist. var parentCase = UnitOfWork.GetEntityQuery <Domain.Summaries.Case.Case>().FirstOrDefault(x => x.Number == number && x.AgencyId == agencyId); if (parentCase == null) { parentCase = new Domain.Summaries.Case.Case(IdentityId, agencyId, number); UnitOfWork.Add(parentCase); } var otherEventSummary = new OtherEventSummary(IdentityId, agencyId, details.Id, number, parentCase); UnitOfWork.Add(otherEventSummary); UnitOfWork.Commit(); return(otherEventSummary.Id); }
public void Handle(CreateUserCommand command) { User item = null; OnCreateUser(command, ref item); if (item == null) { item = new User(DependencyResolver, Logger, command.Rsn == Guid.Empty ? Guid.NewGuid() : command.Rsn); UnitOfWork.Add(item); } item.CreateUser(); OnCreatedUser(command, item); OnAddToUnitOfWork(command, item); UnitOfWork.Add(item); OnAddedToUnitOfWork(command, item); OnCommit(command, item); UnitOfWork.Commit(); OnCommited(command, item); }
public int CreateUser(UserModel user) { var userEntity = new UserDbRepoModel(); using (_unitOfWork.Add <UserDbRepoModel>()) { userEntity = _mapper.Map <UserDbRepoModel>(user); _unitOfWork.GetRepository <UserDbRepoModel>().AddItem(userEntity); _unitOfWork.Save(); } return(userEntity.Id); }
public JsonResult Publish() { string bPublish = QueryString("bPublish"); bPublish.CheckBoolType("bPublish"); string id = QueryString("id"); id.CheckNotNullOrEmpty("id"); WFDef wfDef = UnitOfWork.GetByKey <WFDef>(id); wfDef.CheckNotNull("WFDef"); wfDef.IsPublish = bPublish; if (wfDef.IsPublish == "true") { var defInst = wfDef.CreateInst(); UnitOfWork.Add <WFDefInst>(defInst); } return(Json(UnitOfWork.Commit())); }
protected virtual void Execute <TParameters>(Action <TParameters> action, TParameters parameters) { UnitOfWork.Add(this); try { action(parameters); UnitOfWork.Commit(); Sender.Tell(true, Self); } catch (Exception exception) { Logger.LogError("Executing an Akka.net request failed.", exception: exception, metaData: new Dictionary <string, object> { { "Type", GetType() }, { "Parameters", parameters } }); Sender.Tell(false, Self); throw; } }
public void Setup() { var eventStore = new TestInMemoryEventStore(); var eventPublisher = new TestEventPublisher(); _snapshotStore = new TestSnapshotStore(); var snapshotStrategy = new DefaultSnapshotStrategy <ISingleSignOnToken>(); var dependencyResolver = new TestDependencyResolver(null); var aggregateFactory = new AggregateFactory(dependencyResolver, dependencyResolver.Resolve <ILogger>()); var repository = new SnapshotRepository <ISingleSignOnToken>(_snapshotStore, snapshotStrategy, new AggregateRepository <ISingleSignOnToken>(aggregateFactory, eventStore, eventPublisher, new NullCorrelationIdHelper(), new ConfigurationManager()), eventStore, aggregateFactory); var session = new UnitOfWork <ISingleSignOnToken>(repository); var aggregate = new TestSnapshotAggregate(); for (int i = 0; i < 30; i++) { aggregate.DoSomething(); } session.Add(aggregate); session.Commit(); }
public void Handle(WithdrawFundsFromAccountCommand command) { ICommandValidator <Cqrs.Authentication.ISingleSignOnToken, WithdrawFundsFromAccountCommand> commandValidator = null; try { commandValidator = DependencyResolver.Resolve <ICommandValidator <Cqrs.Authentication.ISingleSignOnToken, WithdrawFundsFromAccountCommand> >(); } catch (Exception exception) { Logger.LogDebug("Locating an ICommandValidator failed.", "WithdrawFundsFromAccountCommandHandler\\Handle(WithdrawFundsFromAccountCommand)", exception); } if (commandValidator != null && !commandValidator.IsCommandValid(command)) { Logger.LogInfo("The provided command is not valid.", "WithdrawFundsFromAccountCommandHandler\\Handle(WithdrawFundsFromAccountCommand)"); return; } bool continueExecution = true; OnHandle(command, ref continueExecution); if (continueExecution) { Account item = null; OnWithdrawFunds(command, ref item); if (item == null) { item = new Account(DependencyResolver, Logger, command.Rsn); UnitOfWork.Add(item); } item.WithdrawFunds(command.Amount); OnWithdrawFundsHandled(command, item); OnAddToUnitOfWork(command, item); UnitOfWork.Add(item); OnAddedToUnitOfWork(command, item); OnCommit(command, item); UnitOfWork.Commit(); OnCommited(command, item); } }
public JsonResult AddWorkFlow() { var dataStr = QueryString("data"); WFDef wfd = dataStr.JsonToObject <WFDef>(); wfd.Id = GuidHelper.CreateTimeOrderID(); wfd.IsPublish = "false"; wfd.Code = wfd.EntityFullName.Replace(".", "_");//xx_xxx_xx UnitOfWork.Add(wfd); WFDefInst defInst = new WFDefInst(); ConvertHelper.UpdateEntity(defInst, dataStr.JsonToDictionary()); defInst.Id = GuidHelper.CreateTimeOrderID(); defInst.WFDefId = wfd.Id; UnitOfWork.Add(defInst); bool b = UnitOfWork.Commit(); return(Json(b)); }
public JsonResult SaveRole() { string roleType = QueryString("RoleType"); roleType.CheckNotNullOrEmpty("角色枚举类型不能为空"); var dic = Request.Form["formData"].JsonToObject <Dictionary <string, object> >(); MF_Role role = ConvertHelper.ConvertToObj <MF_Role>(dic); role.EnumRoleType = roleType; if (string.IsNullOrEmpty(role.Id)) { role.Id = GuidHelper.CreateTimeOrderID(); UnitOfWork.Add(role); } else { UnitOfWork.UpdateEntity(role); } return(Json(UnitOfWork.Commit())); }
public void Handle(MoreItemsCommand command) { var order = UnitOfWork.Get <Order>(command.OrderId); var menuItemsIds = command.MenuItemsQuantities.Select(x => x.MenuItemId).ToArray(); var menuItems = UnitOfWork.GetWhere <MenuItem>(x => menuItemsIds.Contains(x.Id)).ToArray(); foreach (var menuItemsQuantityModel in command.MenuItemsQuantities) { var menuItemsQuantities = new MenuItemsQuantity() { Order = order, Quantity = menuItemsQuantityModel.Quantities, Item = menuItems.First(x => x.Id == menuItemsQuantityModel.MenuItemId) }; UnitOfWork.Add(menuItemsQuantities); } EventBus.PublishEvent(new AddedMoreItems() { OrderId = command.OrderId }); }
public void GoToNextStep(string nextRoutingDefInstId, WFStep currentStep, Dictionary <string, object> entityDic) { var nextRoutingDefInst = UnitOfWork.GetByKey <WFRoutingDefInst>(nextRoutingDefInstId); nextRoutingDefInst.CheckNotNull("id为{0}的WFRoutingDefInst不存在".ReplaceArg(nextRoutingDefInstId)); WFStep step = new WFStep(); step.Id = GuidHelper.CreateTimeOrderID(); step.PreStepId = currentStep.Id; step.WFNodeDefInstId = nextRoutingDefInst.ENodeDefInstId; step.WFInstId = currentStep.WFInstId; //如果下一节点不是结束节点,必须给执行人 var nextNodeDefInst = UnitOfWork.GetByKey <WFNodeDefInst>(nextRoutingDefInst.ENodeDefInstId); nextNodeDefInst.CheckNotNull("id为{0}的WFNodeDefInst不存在".ReplaceArg(nextRoutingDefInst.ENodeDefInstId)); if (nextNodeDefInst.WFNodeType != WFNodeType.End.ToString()) { string nextUserId = QueryString("nextUserId"); nextUserId.CheckNotNullOrEmpty("nextUserId"); string nextUserName = QueryString("nextUserName"); nextUserName.CheckNotNullOrEmpty("nextUserName"); step.StepUserId = nextUserId; step.StepUserName = nextUserName; step.Name = nextNodeDefInst.Name; } //结束 else { entityDic.SetValue("FlowPhase", FlowState.End.ToString()); OnFlowEnd(entityDic); } currentStep.NextStepId = step.Id;// currentStep.OperateUserId = GetCurrentUserID(); currentStep.OperateUserName = GetCurrentUserName(); currentStep.OperateTime = DateTime.Now; UnitOfWork.Add <WFStep>(step); }
public Guid CreateFieldInterviewSummary(Guid agencyId, string caseNumber, string reportNumber, FieldInterviewSummaryDetails details) { // Verify that a summary doesn't already exist. // TODO: This throws an Exception if the ID already exists in the data store. Evaluate this usage. EnsureNonExistingIdentifier <FieldInterviewSummary>(details.Id); // Associate the summary with its parent Case. var parentCase = UnitOfWork.GetEntityQuery <Domain.Summaries.Case.Case>().FirstOrDefault(x => x.Number == caseNumber && x.AgencyId == agencyId); if (parentCase == null) { parentCase = new Domain.Summaries.Case.Case(IdentityId, agencyId, caseNumber); UnitOfWork.Add(parentCase); } var fiSummary = new FieldInterviewSummary(IdentityId, agencyId, details.Id, reportNumber, parentCase); UnitOfWork.Add(fiSummary); UnitOfWork.Commit(); return(fiSummary.Id); }
public JsonResult SaveForm() { var dic = Request.Form["formData"].JsonToObject <Dictionary <string, object> >(); if (string.IsNullOrEmpty(dic.GetValue("Id"))) { FormConfig cForm = ConvertHelper.ConvertToObj <FormConfig>(dic); cForm.Id = GuidHelper.CreateTimeOrderID(); cForm.ReCreateCtrl(); UnitOfWork.Add(cForm); } else { FormConfig cForm = UnitOfWork.GetByKey <FormConfig>(dic.GetValue("Id")); ConvertHelper.UpdateEntity(cForm, dic, true, "CtrlSetting", "LayOutSetting"); UnitOfWork.UpdateEntity(cForm); } bool b = UnitOfWork.Commit(); return(Json(b)); }
public JsonResult Save() { var dic = Request.Form["formData"].JsonToObject <Dictionary <string, object> >(); if (string.IsNullOrEmpty(dic.GetValue("Id"))) { ListConfig cList = ConvertHelper.ConvertToObj <ListConfig>(dic); cList.Id = GuidHelper.CreateTimeOrderID(); cList.ButtonSetting = DefaultValue.GetListButtonJson(); cList.PropertySetting = DefaultValue.GetListPropertyJson(); UnitOfWork.Add(cList); } else { ListConfig cList = UnitOfWork.GetByKey <ListConfig>(dic.GetValue("Id")); ConvertHelper.UpdateEntity(cList, dic); UnitOfWork.UpdateEntity(cList); } bool b = UnitOfWork.Commit(); return(Json(b)); }
public JsonResult SaveWorkFlowDef() { var dic = Request.Form["formData"].JsonToObject <Dictionary <string, object> >(); string id = dic.GetValue("Id"); #region Def if (string.IsNullOrEmpty(id)) { WFDef flowDef = ConvertHelper.ConvertToObj <WFDef>(dic); flowDef.Id = GuidHelper.CreateTimeOrderID(); UnitOfWork.Add(flowDef); } else { WFDef flowDef = UnitOfWork.GetByKey <WFDef>(id); ConvertHelper.UpdateEntity(flowDef, dic); UnitOfWork.UpdateEntity(flowDef); } #endregion bool b = UnitOfWork.Commit(); return(Json(b)); }
/// <summary> /// Executes the provided <paramref name="action"/> passing it the provided <paramref name="event"/>, /// then calls <see cref="AggregateRepository{TAuthenticationToken}.PublishEvent"/> /// </summary> protected virtual void Execute <TEvent>(Action <TEvent> action, TEvent @event) where TEvent : IEvent <TAuthenticationToken> { UnitOfWork.Add(this); try { AuthenticationTokenHelper.SetAuthenticationToken(@event.AuthenticationToken); CorrelationIdHelper.SetCorrelationId(@event.CorrelationId); action(@event); UnitOfWork.Commit(); Sender.Tell(true, Self); } catch (Exception exception) { Logger.LogError("Executing an Akka.net request failed.", exception: exception, metaData: new Dictionary <string, object> { { "Type", GetType() }, { "Event", @event } }); Sender.Tell(false, Self); throw; } }
public void Handle(AddCategoryCommand command) { UnitOfWork.Add(new Category { Title = command.Title, Description = command.Description }); }
public TKey Execute(TEntity context) { UnitOfWork.Add(context); UnitOfWork.Commit(); return(context.Id); }
public void Append(Guid stream, int expectedVersion, params object[] events) { Append(stream, events); _unitOfWork.Add(new AssertEventStreamMaxEventId(stream, expectedVersion, _schema.Events.Table.QualifiedName)); }
public void Delete <T>(T entity) { assertNotDisposed(); var documentStorage = StorageFor <T>(); var deletion = documentStorage.DeleteForDocument(entity); _unitOfWork.Add(deletion); documentStorage.Eject(this, entity); }
public void AddAuditRecord(AuditRecordModel auditRecord) { using (var unitOfWork = new UnitOfWork(_connectionString)) { unitOfWork.Add(auditRecord.ToNewDbObject()); } }
public MappingModel AddMapping(MappingModel model) { if (model == null) throw new ArgumentNullException("model"); Mapping mapToReturn; using (var unitOfWork = new UnitOfWork(_connectionString)) { bool userAuthorised = UserAuthorizedToAccessSuite(unitOfWork, model.UserId, model.SuiteId, new[] {RoleType.Admin}); if (!userAuthorised) throw new UnauthorizedUserException( "User does not have access or sufficient privileges for this action to suite: " + model.SuiteId); if ( !unitOfWork.Context.Parameters.Any( x => x.ParameterId == model.ParameterId && x.SuiteId == model.SuiteId)) throw new InvalidOperationException( "Mismatch between parameter id and suite id. Can not add mapping!"); if (!unitOfWork.Context.Servers.Any(x => x.ServerId == model.ServerId && x.SuiteId == model.SuiteId)) throw new InvalidOperationException("Mismatch between server id and suite id. Can not add mapping!"); if (!unitOfWork.Context.Regions.Any(x => x.RegionId == model.RegionId && x.SuiteId == model.SuiteId)) throw new InvalidOperationException("Mismatch between region id and suite id. Can not add mapping!"); if ( !unitOfWork.Context.Environments.Any( x => x.EnvironmentId == model.EnvironmentId && x.SuiteId == model.SuiteId)) throw new InvalidOperationException( "Mismatch between environment id and suite id. Can not add mapping!"); if ( !unitOfWork.Context.Applications.Any( x => x.ApplicationId == model.ApplicationId && x.SuiteId == model.SuiteId)) throw new InvalidOperationException( "Mismatch between application id and suite id. Can not add mapping!"); mapToReturn = model.ToNewDbObject(); unitOfWork.Add(mapToReturn); } if (mapToReturn != null) return mapToReturn.ToModel(); return null; }
public EnvironmentModel AddEnvironment(EnvironmentModel model) { if (model == null) throw new ArgumentNullException("model"); Environment environmentToReturn = null; using (var unitOfWork = new UnitOfWork(_connectionString)) { bool userAuthorised = UserAuthorizedToAccessSuite(unitOfWork, model.UserId, model.SuiteId, new[] {RoleType.Admin}); if (!userAuthorised) throw new UnauthorizedUserException( "User does not have access or sufficient privileges for this action to suite: " + model.SuiteId); environmentToReturn = model.ToNewDbObject(); unitOfWork.Add(environmentToReturn); } return environmentToReturn.ToModel(); }
public SuiteModel AddSuite(SuiteCreateModel suiteModel) { Suite suiteReturn; using (var unitOfWork = new UnitOfWork(_connectionString)) { if (unitOfWork.Context.Suites.Any(x => x.SuiteName == suiteModel.SuiteName)) throw new InvalidOperationException("Suite already exists with name:" + suiteModel.SuiteName); var suiteDB = suiteModel.ToNewDbObject(); unitOfWork.Add(suiteDB); suiteReturn = suiteDB; //if (unitOfWork.Context.SuiteUsers.Any(x => x.UserId == suiteModel.UserId && x.SuiteId == suiteDB.SuiteId)) return; //var userMapping = new SuiteUser() //{ // SuiteId = suiteDB.SuiteId, // UserId = suiteModel.UserId //}; //unitOfWork.Add(userMapping); foreach (var environment in suiteModel.Environments) { environment.SuiteId = suiteDB.SuiteId; environment.IsActive = true; unitOfWork.Add(environment.ToNewDbObject()); } foreach (var application in suiteModel.Applications) { application.SuiteId = suiteDB.SuiteId; application.IsActive = true; unitOfWork.Add(application.ToNewDbObject()); } foreach (var region in suiteModel.Regions) { region.SuiteId = suiteDB.SuiteId; region.IsActive = true; unitOfWork.Add(region.ToNewDbObject()); } foreach (var server in suiteModel.Servers) { server.SuiteId = suiteDB.SuiteId; server.IsActive = true; unitOfWork.Add(server.ToNewDbObject()); } unitOfWork.Add(new SuiteUser { SuiteId = suiteReturn.SuiteId, UserId = (int) suiteModel.UserId, RoleId = (int) RoleType.Admin }); } return GetSuite(suiteModel.UserId, suiteReturn.SuiteId); }
public ServerModel AddServer(ServerModel model) { if (model == null) throw new ArgumentNullException("model"); Server appToReturn; using (var unitOfWork = new UnitOfWork(_connectionString)) { bool userAuthorised = UserAuthorizedToAccessSuite(unitOfWork, model.UserId, model.SuiteId, new[] {RoleType.Admin}); if (!userAuthorised) throw new UnauthorizedUserException( "User does not have access or sufficient privileges for this action to suite: " + model.SuiteId); appToReturn = model.ToNewDbObject(); unitOfWork.Add(appToReturn); } if (appToReturn != null) return appToReturn.ToModel(); return null; }
public ActionResult Add(Memo m) { switch (m.Type) { case "Памятка": if (TryValidateModel(m)) { u.Add(m); u.SaveChanges(); return(JavaScript("location.reload(true)")); } else { return(PartialView("AddMemo", m)); } case "Дело": var tmp = m as Buisness; if (TryValidateModel(tmp)) { if (u.Get <Buisness>(x => Buisness.Compare(x, tmp) == 0) == null) { u.Add(m); u.SaveChanges(); return(JavaScript("location.reload(true)")); } else { ModelState.AddModelError("intersect", "Эта запись пересекается с другой по времени!"); return(PartialView("AddBuisness", tmp)); } } else { return(PartialView("AddBuisness", tmp)); } case "Встреча": var tmp1 = m as Meeting; if (TryValidateModel(m as Meeting)) { if (u.Get <Buisness>(x => Buisness.Compare(x, tmp1) == 0) == null) { u.Add(m); u.SaveChanges(); return(JavaScript("location.reload(true)")); } else { ModelState.AddModelError("intersect", "Эта запись пересекается с другой по времени!"); return(PartialView("AddMeeting", tmp1)); } } else { return(PartialView("AddMeeting", tmp1)); } default: return(RedirectToAction("Index")); } }
public void Add(Customer customer) { _unitOfWork.Add(customer); }