internal static string PrintSummary(this EntityChangeSet changeSet) { var sb = new System.Text.StringBuilder(); PrintSummary(changeSet, sb); return(sb.ToString()); }
public void EntityMotionTest() { int numEntities = 100; var ctx = new SimulationContext(true); EntityPool pool = new EntityPool(EntityPoolTests.CreateEntities(ctx.LocalSpace, numEntities, i => new RandomMotion()), ctx); InconsistencyCoverage ic = InconsistencyCoverage.NewCommon(); for (int i = 0; i < 100; i++) { var old = pool.ToArray(); EntityChangeSet set = new EntityChangeSet(); ctx.SetGeneration(i); var errors = pool.TestEvolve(set, InconsistencyCoverage.NewCommon(), i, TimeSpan.FromSeconds(1)); Assert.IsNull(errors, errors != null ? errors[0].ToString() : ""); Assert.AreEqual(numEntities, set.FindNamedSet("motions").Size); foreach (var e in old) { var m = set.FindMotionOf(e.ID.Guid); Assert.IsNotNull(m); Assert.AreNotEqual(m.TargetLocation, m.Origin.Position, i.ToString()); Assert.IsTrue(Simulation.FullSimulationSpace.Contains(m.TargetLocation)); Assert.IsTrue(Simulation.MySpace.Contains(m.TargetLocation)); } Assert.AreEqual(0, set.Execute(pool, ic, ctx)); Assert.AreEqual(numEntities, pool.Count); Entity e1; foreach (var e in old) { Assert.IsTrue(pool.Find(e.ID.Guid, out e1)); Assert.AreNotEqual(e.ID.Position, e1.ID.Position); } } }
protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { Assert.AreEqual(0, changeSet.AddedEntities.Count, "Change set should not contained added entities."); Assert.IsFalse(changeSet.IsEmpty, "Change set should not be empty."); Assert.AreEqual(1, changeSet.ModifiedEntities.Count, "Change set should contain a single modified entity."); Assert.AreEqual(0, changeSet.RemovedEntities.Count, "Change set should not contained removed entities."); ChangeSetEntry[] submitOperations = changeSet.GetChangeSetEntries().ToArray(); Assert.AreEqual(1, submitOperations.Length, "A single submit operation is expected."); MockUser userToSubmit = (MockUser)submitOperations[0].Entity; MockUser userToReturn = new MockUser() { Name = userToSubmit.Name, Type = UserType.Saved }; List <ChangeSetEntry> submitOperationsToReturn = new List <ChangeSetEntry>(); submitOperationsToReturn.Add(new ChangeSetEntry(userToReturn, submitOperations[0].Id, submitOperations[0].Operation)); this.Result = new AdcSubmitAsyncResult(changeSet, submitOperationsToReturn, userToReturn, callback, userState); return(this.Result); }
partial void ArtikellisteCollection_Validate(ScreenValidationResultsBuilder results) { if (this.DataWorkspace.ApplicationData.Details.HasChanges) { EntityChangeSet changeSet = this.DataWorkspace.ApplicationData.Details.GetChanges(); foreach (Rechnungen entity in changeSet.AddedEntities.OfType <Rechnungen>()) { if (entity.ArtikellisteCollection.Count() == 0) { //entity.Details.DiscardChanges(); //results.AddScreenResult("Eine Bestellung muß mindestens eine Position beinhalten.", ValidationSeverity.Warning); //results.AddPropertyError("Eine Bestellung muß mindestens eine Position beinhalten.");//, entity.Details.Properties.ArtikellisteCollection); } } foreach (Rechnungen entity in changeSet.ModifiedEntities.OfType <Rechnungen>()) { if (entity.ArtikellisteCollection.Count() == 0) { entity.Details.DiscardChanges(); results.AddScreenResult("Eine Bestellung muß mindestens eine Position beinhalten.", ValidationSeverity.Error); //results.AddPropertyError("<Fehlermeldung>"); } } } }
internal void SetChangeSet(EntityChangeSet changeSet) { foreach (var recorderContext in _recorderContexts) { recorderContext.SetChangeSet(changeSet); } }
public virtual async Task SaveAsync(EntityChangeSet changeSet) { try { var obj = changeSet; if (obj != null) { var entityChanges = obj.EntityChanges; obj.EntityChanges = null; var csId = await _changeSetRepository.InsertAndGetIdAsync(obj); entityChanges.ForEach(async x => { var propChanges = x.PropertyChanges; x.PropertyChanges = null; x.EntityChangeSetId = csId; var cId = await _changesRepository.InsertAndGetIdAsync(x); propChanges.ForEach(async p => { p.EntityChangeId = cId; var pId = await _propChangesRepository.InsertAndGetIdAsync(p); }); }); } } catch (Exception e) { Logger.Error(e.Message, e); } }
protected override sealed IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { FakeAsyncResult asyncResult = null; try { IEnumerable <ChangeSetEntry> operationResults = this.Submit(changeSet); asyncResult = new FakeAsyncResult { Callback = callback, AsyncState = userState, ChangeSet = changeSet, OperationResults = operationResults }; } catch (Exception error) { asyncResult = new FakeAsyncResult { Callback = callback, AsyncState = userState, Error = error }; } this.syncContext.Post( o => { ((FakeAsyncResult)o).Complete(); }, asyncResult); return(asyncResult); }
public virtual void Save(EntityChangeSet changeSet) { try { var obj = changeSet; if (obj == null) { return; } var entityChanges = obj.EntityChanges; obj.EntityChanges = null; var csId = _changeSetRepository.InsertAndGetId(obj); entityChanges.ForEach(x => { var propChanges = x.PropertyChanges; x.PropertyChanges = null; x.EntityChangeSetId = csId; if (string.IsNullOrEmpty(x.EntityId)) { // update id for inserted entity x.EntityId = x.EntityEntry.GetType().GetProperty(nameof(IEntity.Id))?.GetValue(x.EntityEntry)?.ToString(); } var cId = _changesRepository.InsertAndGetId(x); propChanges.ForEach(p => { p.EntityChangeId = cId; var pId = _propChangesRepository.InsertAndGetId(p); }); }); } catch (Exception e) { Logger.Error(e.Message, e); } }
public void SimpleEntityFaultTest() { var ctx = new SimulationContext(true); EntityPool pool = new EntityPool(EntityPoolTests.CreateEntities(ctx.LocalSpace, 100, new RandomLogic(new Type[] { typeof(ConsistentLogic), typeof(FaultLogic) }).Instantiate), ctx); InconsistencyCoverage ic = InconsistencyCoverage.NewCommon(); int any = -1; for (int i = 0; i < 8; i++) { EntityChangeSet set = new EntityChangeSet(); ctx.SetGeneration(i); var errors = pool.TestEvolve(set, ic, i, TimeSpan.FromSeconds(1)); if (errors != null) { Assert.IsTrue(ic.OneCount > 0); if (any == -1) { any = i; } } ic = ic.Grow(true); Assert.IsTrue(ic.Size == InconsistencyCoverage.CommonResolution); } if (any == 0) { Assert.AreEqual(ic.OneCount, ic.Size.Product); } }
public virtual void Save(EntityChangeSet changeSet) { try { if (!IsEntityHistoryEnabled) { return; } //UpdateChangeSet(context, changeSet); if (changeSet.EntityChanges.Count == 0) { return; } StaticContext.IocManager.Resolve <NHibernateEntityHistoryStore>()?.Save(changeSet); //StaticContext.IocManager.Resolve<IEntityHistoryStore>()?.Save(changeSet); var historyEventRepository = StaticContext.IocManager.Resolve <IRepository <EntityHistoryEvent, Guid> >(); EntityHistoryEvents.ForEach(e => historyEventRepository.Insert(e)); } catch (Exception e) { Logger.Error(e.Message, e); } }
public void SaveCommandExecute_ShouldCallSubmitChanges() { //Arrange bool submitExecuted = false; bool loadExecuted = false; var mockDomainClient = new Mock <FakeDomainClient>(); ReportWizardContext context = new ReportWizardContext(mockDomainClient.Object); mockDomainClient.Setup(dc => dc.Query(It.Is <EntityQuery>(query => query.EntityType == typeof(DataItem)))) .Callback(() => loadExecuted = true) // used to verify it was called .Returns(() => new Entity[] // a data item { new DataItem { Name = "ProgrammeBalance", Caption = "Programme Balance", Description = "The current programme balance", LocationOnSystem = "The location on the system" } }.AsQueryable()); EntityChangeSet resultSet = context.EntityContainer.GetChanges(); //resultSet.GetChangeSetEntries mockDomainClient.Setup(dc => dc.Submit(It.Is <EntityChangeSet>(ecs => ecs.ModifiedEntities.Count == 1))) //mockDomainClient.Setup(dc => dc.Submit(It.Is<EntityChangeSet>(ecs => ecs.AddedEntities.Count == 0))) .Callback(() => submitExecuted = true) .Returns(() => new List <ChangeSetEntry>()); //.Returns(resultSet.GetChangeSetEntries()); //Act EditDataItemViewModel viewModel = new EditDataItemViewModel(It.IsAny <Guid>(), context); EnqueueConditional(() => //Wait until the load has finished context.IsLoading == false); EnqueueCallback(() => //Amend the description of the data item and submit the changes to the database { context.DataItems.FirstOrDefault(x => x.Name == "ProgrammeBalance").Description = "Amended Description"; viewModel.SaveCommand.Execute(null); }); EnqueueConditional(() => //Wait until the submit has finished context.IsSubmitting == false); //Assert EnqueueCallback(() => //test that the method was executed { Assert.IsTrue(submitExecuted, "The submit was not called"); //Test if the method was executed //mockDomainClient.Verify(dc => dc.Submit(It.Is<EntityChangeSet>(ecs => ecs.ModifiedEntities.Count == 1))); }); EnqueueTestComplete(); }
/// <summary> /// Builds the list of submit operations from the current <see cref="EntityChangeSet"/>. /// </summary> /// <param name="changeSet">The <see cref="EntityChangeSet"/> to process.</param> /// <returns>The list of <see cref="ChangeSetEntry"/> for the specified <see cref="EntityChangeSet"/>.</returns> private static List<ChangeSetEntry> BuildOperations(EntityChangeSet changeSet) { List<ChangeSetEntry> operations = new List<ChangeSetEntry>(); int clientID = 0; EntityOperationType operationType = EntityOperationType.None; foreach (Entity entity in changeSet) { switch (entity.EntityState) { case EntityState.New: operationType = EntityOperationType.Insert; break; case EntityState.Modified: operationType = EntityOperationType.Update; break; case EntityState.Deleted: operationType = EntityOperationType.Delete; break; default: continue; } // create the operation and apply any original values ChangeSetEntry changeSetEntry = new ChangeSetEntry(entity, clientID++, operationType); if (entity.OriginalValues != null) { if (entity.MetaType.ShouldRoundtripOriginal && entity.OriginalValues != null) { changeSetEntry.OriginalEntity = GetRoundtripEntity(entity); } else { // In cases where the entity is modified but we're not sending // an original we need to flag the entity as having changes. // For example, this happens in Timestamp scenarios. changeSetEntry.HasMemberChanges = true; } } // add any custom method invocations if (entity.CustomMethodInvocation != null) { if (string.IsNullOrEmpty(entity.CustomMethodInvocation.Name)) { throw new ArgumentException(Resource.DomainClient_InvocationNameCannotBeNullOrEmpty); } if (changeSetEntry.EntityActions == null) { changeSetEntry.EntityActions = new Dictionary<string, object[]>(); } changeSetEntry.EntityActions.Add(entity.CustomMethodInvocation.Name, entity.CustomMethodInvocation.Parameters.ToArray()); } operations.Add(changeSetEntry); } return operations; }
/// <summary> /// Private constructor used by all public constructors. /// </summary> /// <param name="changeSet">the changeset being submitted</param> /// <param name="message">The localized error message</param> /// <param name="innerException">Optional inner exception.</param> /// <param name="status">status of the exception</param> /// <param name="errorCode">custom error code</param> /// <param name="stackTrace">stack trace of the exception</param> private SubmitOperationException(EntityChangeSet changeSet, string message, Exception innerException, OperationErrorStatus status, int errorCode, string stackTrace) : base(message, innerException, status, errorCode, stackTrace, GetValidationResults(changeSet)) { _changeSet = changeSet; _entitiesInError = new ReadOnlyCollection<Entity>(changeSet .Where(p => p.EntityConflict != null || p.HasValidationErrors) .ToList()); }
public void InferredAdd_EntityRefs() { NorthwindEntityContainer ec = new NorthwindEntityContainer(); // add a few existing entities Order order1 = new Order { OrderID = 1 }; Order_Detail detail1 = new Order_Detail { OrderID = 2, ProductID = 1 }; ec.LoadEntities(new Entity[] { order1, detail1 }); ((IChangeTracking)ec).AcceptChanges(); Assert.IsFalse(ec.HasChanges); // build a detached graph of a new category and 2 products Category newCategory = new Category { CategoryID = 1 }; Product newProduct1 = new Product { ProductID = 3 }; Product newProduct2 = new Product { ProductID = 4 }; newCategory.Products.Add(newProduct1); newCategory.Products.Add(newProduct2); // set the the Product reference on the existing detail to // one of the new detached products - we expect the entire // graph to be infer added EntityChangeSet cs = ec.GetChanges(); Assert.IsTrue(cs.IsEmpty); detail1.Product = newProduct1; cs = ec.GetChanges(); Assert.AreEqual(3, cs.AddedEntities.Count); Assert.IsTrue(cs.AddedEntities.Contains(newProduct1)); // the entity set directly Assert.IsTrue(cs.AddedEntities.Contains(newCategory)); // inferred via Product.Category ER Assert.IsTrue(cs.AddedEntities.Contains(newProduct2)); // inferred via Category.Products EC // verify that inferred Adds can be state transitioned via subsequent // calls to Attach ec.GetEntitySet <Product>().Attach(newProduct2); newProduct2.ProductName += "x"; cs = ec.GetChanges(); Assert.AreEqual(2, cs.AddedEntities.Count); Assert.AreEqual(2, cs.ModifiedEntities.Count); Assert.IsFalse(cs.AddedEntities.Contains(newProduct2)); Assert.IsTrue(cs.ModifiedEntities.Contains(newProduct2)); }
protected override Task <SubmitCompletedResult> SubmitAsyncCore(EntityChangeSet changeSet, CancellationToken cancellationToken) { IEnumerable <ChangeSetEntry> submitOperations = changeSet.GetChangeSetEntries(); // perform mock submit operations SubmitCompletedResult submitResults = new SubmitCompletedResult(changeSet, submitOperations); return(TaskHelper.FromResult(submitResults)); }
/// <summary> /// Public constructor /// </summary> /// <param name="changeSet">The changeset being submitted</param> internal SubmittingChangesEventArgs(EntityChangeSet changeSet) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this._changeSet = changeSet; }
/// <summary> /// Initializes a new <see cref="WebDomainClientAsyncResult<TContract>"/> instance used for Submit operations. /// </summary> /// <param name="entityChangeSet">The Submit operation <see cref="EntityChangeSet"/>.</param> /// <param name="changeSetEntries">The collection of <see cref="ChangeSetEntry"/>s to submit.</param> /// <param name="callback">Optional <see cref="AsyncCallback"/> to invoke upon completion.</param> /// <param name="asyncState">Optional user state information that will be passed to the <paramref name="callback"/>.</param> /// <exception cref="ArgumentNullException">if <paramref name="domainClient"/> is null.</exception> /// <exception cref="ArgumentNullException">if <paramref name="endOperationMethod"/> is null.</exception> private WebApiDomainClientAsyncResult(WebApiDomainClient domainClient, EntityChangeSet entityChangeSet, IEnumerable<ChangeSetEntry> changeSetEntries, AsyncCallback callback, object asyncState) : base(domainClient, entityChangeSet, callback, asyncState) { // base class validates domainClient _interfaceType = domainClient.ServiceInterfaceType; _operationName = "SubmitChanges"; _changeSetEntries = changeSetEntries; }
public void TestAssociations_UpdatedReferencingNew() { NorthwindEntityContainer ec = new NorthwindEntityContainer(); Product p1 = new Product { ProductID = 1, CategoryID = 1 }; Product p2 = new Product { ProductID = 2, CategoryID = 2 }; Category c1 = new Category { CategoryID = 1 }; Category c2 = new Category { CategoryID = 2 }; ec.LoadEntities(new Entity[] { p1, p2, c1, c2 }); // take two existing parents (the FK side of the association) // access their existing children Category prevCat = p1.Category; Assert.IsNotNull(prevCat); prevCat = p2.Category; Assert.IsNotNull(prevCat); // create two new children Category newCat1 = new Category { CategoryID = 3 }; Category newCat2 = new Category { CategoryID = 4 }; // assign the two new children p1.Category = newCat1; p2.Category = newCat2; EntityChangeSet cs = ec.GetChanges(); Assert.AreEqual(2, cs.AddedEntities.Count); Assert.AreEqual(2, cs.ModifiedEntities.Count); List <ChangeSetEntry> entries = ChangeSetBuilder.Build(cs); ChangeSetEntry entry = entries.Single(p => p.Entity == p1); // the bug was that we weren't populating the association map in this // scenario since previously we required BOTH parent and child to be new. // We've relaxed that to ensure that if the child is new, the association // shows up in the map. Assert.IsNotNull(entry.Associations); int[] ids = entry.Associations["Category"]; Category referenced = (Category)entries.Single(p => p.Id == ids.Single()).Entity; Assert.AreSame(newCat1, referenced); }
/// <summary> /// Public constructor /// </summary> /// <param name="changeSet">The changeset that was submitted.</param> /// <param name="entitiesInError">The list of entities that were in error.</param> /// <param name="error"><see cref="Exception"/> for the submit operation if it failed.</param> /// <param name="canceled"><c>true</c> if the submit operation was canceled, <c>false</c> otherwise.</param> internal SubmittedChangesEventArgs(EntityChangeSet changeSet, IEnumerable <Entity> entitiesInError, Exception error, bool canceled) : base(error, canceled, null) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this.ChangeSet = changeSet; this.EntitiesInError = entitiesInError; }
/// <summary> /// Public constructor /// </summary> /// <param name="changeSet">The changeset that was submitted.</param> /// <param name="entitiesInError">The list of entities that were in error.</param> /// <param name="error"><see cref="Exception"/> for the submit operation if it failed.</param> /// <param name="canceled"><c>true</c> if the submit operation was canceled, <c>false</c> otherwise.</param> internal SubmittedChangesEventArgs(EntityChangeSet changeSet, IEnumerable<Entity> entitiesInError, Exception error, bool canceled) : base(error, canceled, null) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this.ChangeSet = changeSet; this.EntitiesInError = entitiesInError; }
/// <summary> /// Public constructor /// </summary> /// <param name="changeSet">The changeset that was submitted.</param> /// <param name="operationResults">The operation results returned from the domain service. Will be null /// if the submit failed client side validation.</param> /// <param name="error">Exception for the submit operation if it failed.</param> /// <param name="canceled">True if the submit operation was canceled, false otherwise.</param> /// <param name="userState">Optional user state.</param> public SubmittedChangesEventArgs(EntityChangeSet changeSet, IEnumerable<EntityOperation> operationResults, Exception error, bool canceled, object userState) : base(error, canceled, userState) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this._changeSet = changeSet; this._operationResults = operationResults; }
/// <summary> /// Public constructor /// </summary> /// <param name="changeSet">The changeset that was submitted.</param> /// <param name="operationResults">The operation results returned from the domain service. Will be null /// if the submit failed client side validation.</param> /// <param name="error">Exception for the submit operation if it failed.</param> /// <param name="canceled">True if the submit operation was canceled, false otherwise.</param> /// <param name="userState">Optional user state.</param> public SubmittedChangesEventArgs(EntityChangeSet changeSet, IEnumerable <EntityOperation> operationResults, Exception error, bool canceled, object userState) : base(error, canceled, userState) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this._changeSet = changeSet; this._operationResults = operationResults; }
public void StateAdvertisementTest() { var ctx = new SimulationContext(); EntityPool pool = RandomDefaultPool(100, ctx); for (int i = 0; i < 100; i++) { EntityChangeSet set = new EntityChangeSet(); ctx.SetGeneration(i); var errors = pool.TestEvolve(set, InconsistencyCoverage.NewCommon(), i, TimeSpan.FromSeconds(5)); Assert.IsNull(errors, errors != null ? errors[0].ToString() : ""); Assert.AreEqual(0, set.Execute(pool, ctx)); HashSet <Guid> env = new HashSet <Guid>(); var state = pool.ToArray(); int it = 0; foreach (var e in state) { env.Clear(); foreach (var e1 in state) { float dist = ctx.GetDistance(e.ID.Position, e1.ID.Position); if (e1.ID.Guid != e.ID.Guid && dist <= Simulation.SensorRange) { Console.WriteLine(dist + "/" + Simulation.SensorRange); env.Add(e1.ID.Guid); } } Assert.AreEqual(env.Count, e.Contacts.Length, i + "." + it + ": " + e); if (env.Count > 0) { it++; } foreach (var c in e.Contacts) { float dist = ctx.GetDistance(c.ID.Position, e.ID.Position); Assert.IsTrue(dist <= Simulation.SensorRange, dist + " <= " + Simulation.SensorRange); Assert.AreNotEqual(c.ID.Guid, e.ID.Guid); Assert.IsTrue(env.Contains(c.ID.Guid)); } var app = e.Appearances.Get <ConsistencyAppearance>(); if (i > 0) { Assert.IsNotNull(e.Appearances); Assert.IsNotNull(app); } if (app != null) { Assert.IsTrue(app.IsConsistent); } } } }
public void TestMockClientReturnsNull() { NullReturningMockDomainClient dc = new NullReturningMockDomainClient(); AsyncCallback ignored = delegate { }; InvokeArgs invokeArgs = new InvokeArgs("M", typeof(void), null, true /*hasSideEffects*/); DomainClientAsyncResult result = (DomainClientAsyncResult)dc.BeginInvoke(invokeArgs, ignored, null); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndInvoke(result.InnerAsyncResult), "asyncResult"); result = null; result = (DomainClientAsyncResult)dc.BeginQuery(new EntityQuery <Entity>(dc, "GetIgnored", null, true, false), ignored, null); }); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndQuery(result.InnerAsyncResult), "asyncResult"); List <Entity> list = new List <Entity>(); list.Add(new Product()); ReadOnlyCollection <Entity> simpleCollection = new ReadOnlyCollection <Entity>(list); ReadOnlyCollection <Entity> emptyCollection = new ReadOnlyCollection <Entity>(new List <Entity>()); EntityChangeSet emptyChangeSet = new EntityChangeSet(simpleCollection, emptyCollection, emptyCollection); result = null; result = (DomainClientAsyncResult)dc.BeginSubmit(emptyChangeSet, ignored, null); }); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndSubmit(result.InnerAsyncResult), "asyncResult"); }); EnqueueTestComplete(); }
protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { IEnumerable <ChangeSetEntry> submitOperations = changeSet.GetChangeSetEntries(); MockAsyncResult ar = new MockAsyncResult(null, userState, new object[] { changeSet, submitOperations, userState }); // perform mock submit operations callback.Invoke(ar); return(ar); }
static void FormatComponentChange(ref EntityChangeSet changeSet, PackedComponent c, System.Text.StringBuilder sb) { int ti = TypeManager.GetTypeIndexFromStableTypeHash(changeSet.TypeHashes[c.PackedTypeIndex].StableTypeHash); var typeName = TypeManager.GetTypeInfo(ti).DebugTypeName; sb.Append("\t"); sb.Append(typeName); sb.Append(" - "); // Could also print out GUID here sb.AppendLine(changeSet.Names[c.PackedEntityIndex].ToString()); }
/// <summary> /// Initializes a new <see cref="DomainClientAsyncResult"/> instance used for Submit operations. /// </summary> /// <param name="domainClient">The associated <see cref="DomainClient"/>.</param> /// <param name="entityChangeSet">The Submit operation <see cref="EntityChangeSet"/>.</param> /// <param name="callback">Optional <see cref="AsyncCallback"/> to invoke upon completion.</param> /// <param name="asyncState">Optional user state information that will be passed to the <paramref name="callback"/>.</param> /// <exception cref="ArgumentNullException">if <paramref name="domainClient"/> is null.</exception> protected DomainClientAsyncResult(DomainClient domainClient, EntityChangeSet entityChangeSet, AsyncCallback callback, object asyncState) : base(callback, asyncState) { if (domainClient == null) { throw new ArgumentNullException("domainClient"); } this._asyncOperationType = AsyncOperationType.Submit; this._domainClient = domainClient; this._entityChangeSet = entityChangeSet; }
unsafe public static void SerializeResourcePacket(EntityChangeSet entityChangeSet, ref UnsafeAppendBuffer buffer) { var changeSetBuffer = new UnsafeAppendBuffer(1024, 16, Allocator.TempJob); Serialize(entityChangeSet, &changeSetBuffer, out var globalObjectIds); buffer.Add(globalObjectIds); buffer.Add(changeSetBuffer.Ptr, changeSetBuffer.Length); changeSetBuffer.Dispose(); globalObjectIds.Dispose(); }
protected override SubmitCompletedResult EndSubmitCore(IAsyncResult asyncResult) { MockAsyncResult ar = (MockAsyncResult)asyncResult; object[] stateParts = (object[])ar.InnerState; EntityChangeSet changeSet = (EntityChangeSet)stateParts[0]; IEnumerable <ChangeSetEntry> submitOperations = (IEnumerable <ChangeSetEntry>)stateParts[1]; SubmitCompletedResult submitResults = new SubmitCompletedResult(changeSet, submitOperations); return(submitResults); }
/// <summary> /// Initializes a new instance of the <see cref="SubmitOperation"/> class. /// </summary> /// <param name="changeSet">The changeset being submitted.</param> /// <param name="completeAction">Optional action to invoke when the operation completes.</param> /// <param name="userState">Optional user state to associate with the operation.</param> /// <param name="cancelAction">Optional action to invoke when the operation is canceled. If null, cancellation will not be supported.</param> internal SubmitOperation(EntityChangeSet changeSet, Action<SubmitOperation> completeAction, object userState, Action<SubmitOperation> cancelAction) : base(userState) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } this._cancelAction = cancelAction; this._completeAction = completeAction; this._changeSet = changeSet; }
/// <summary> /// Verify successful completion of an update operation /// </summary> private void VerifySuccess(CompositionInheritanceScenarios ctxt, SubmitOperation so, IEnumerable <Entity> expectedUpdates) { // verify operation completed successfully TestHelperMethods.AssertOperationSuccess(so); // verify that all operations were executed EntityChangeSet cs = so.ChangeSet; VerifyOperationResults(cs.AddedEntities, expectedUpdates); // verify that all changes have been accepted cs = ctxt.EntityContainer.GetChanges(); Assert.IsTrue(cs.IsEmpty); }
/// <summary> /// Initializes a new instance of the SubmitCompletedResult class /// </summary> /// <param name="changeSet">The changeset that was submitted.</param> /// <param name="operationResults">The <see cref="ChangeSetEntry"/> results sent back from the /// DomainService for the submit operation.</param> public SubmitCompletedResult(EntityChangeSet changeSet, IEnumerable<ChangeSetEntry> operationResults) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } if (operationResults == null) { throw new ArgumentNullException("operationResults"); } this._changeSet = changeSet; this._operationResults =new ReadOnlyCollection<ChangeSetEntry>(operationResults.ToList()); }
/// <summary> /// Builds an operation list for the specified <see cref="EntityChangeSet"/>. /// </summary> /// <param name="changeSet">The <see cref="EntityChangeSet"/>.</param> /// <returns>The list of <see cref="ChangeSetEntry"/> for the specified <see cref="EntityChangeSet"/>.</returns> public static List<ChangeSetEntry> Build(EntityChangeSet changeSet) { CheckForInvalidUpdates(changeSet); // translate to an operation list List<ChangeSetEntry> operations = BuildOperations(changeSet); // recursively visit all composition relationships in the // changeset and add operations for unmodified children. UnmodifiedOperationAdder.Add(operations); // set the association maps for all operations in the changeset AssociationMapBuilder.Build(operations); return operations; }
public void CloneTest() { var ctx = RandomContext(); for (int i = 0; i < 100; i++) { EntityChangeSet set = RandomSet(ctx); EntityChangeSet copy = set.Clone(); Assert.AreEqual(set, copy); copy.Add(RandomInstantiation(ctx)); Assert.AreNotEqual(set, copy); } }
public virtual EntityChangeSet CreateEntityChangeSet() { if (!IsEntityHistoryEnabled) { return(null); } var changeSet = new EntityChangeSet() { Reason = EntityChangeSetReasonProvider.Reason.TruncateWithPostfix(EntityChangeSet.MaxReasonLength), // Fill "who did this change" BrowserInfo = ClientInfoProvider.BrowserInfo.TruncateWithPostfix(EntityChangeSet.MaxBrowserInfoLength), ClientIpAddress = ClientInfoProvider.ClientIpAddress.TruncateWithPostfix(EntityChangeSet.MaxClientIpAddressLength), ClientName = ClientInfoProvider.ComputerName.TruncateWithPostfix(EntityChangeSet.MaxClientNameLength), ImpersonatorTenantId = AbpSession.ImpersonatorTenantId, ImpersonatorUserId = AbpSession.ImpersonatorUserId, TenantId = AbpSession.TenantId, UserId = AbpSession.UserId }; // Add description for property change foreach (var entityHistoryEvent in EntityHistoryEvents.Where(x => !string.IsNullOrEmpty(x.PropertyName) && x.EntityChange != null && x.EventType != EntityHistoryCommonEventTypes.PROPERTY_CHANGE_AS_EVENT)) { var prop = EntityChanges .FirstOrDefault(x => x.EntityId == entityHistoryEvent.EntityChange.EntityId && x.EntityTypeFullName == entityHistoryEvent.EntityChange.EntityTypeFullName && x.PropertyChanges != null) ?.PropertyChanges.FirstOrDefault(x => x.PropertyName == entityHistoryEvent.PropertyName); if (prop != null) { entityHistoryEvent.EntityPropertyChange = prop; EntityChanges.Remove(entityHistoryEvent.EntityChange); entityHistoryEvent.EntityChange = null; } } changeSet.EntityChanges = EntityChanges; return(changeSet); }
public void ChangeSet_DontLoadUnloadedAssociations() { NorthwindEntityContainer entities = new NorthwindEntityContainer(); EntitySet <Order> orders = entities.GetEntitySet <Order>(); EntitySet <Order_Detail> details = entities.GetEntitySet <Order_Detail>(); // add a few existing entities Order order = new Order { OrderID = 1 }; Order_Detail detail = new Order_Detail { OrderID = 1, ProductID = 1 }; entities.LoadEntities(new Entity[] { order, detail }); // modify both entities order.Freight = 5; detail.Quantity = 5; IEntityRef er = detail.GetEntityRef("Order"); Assert.IsNull(er); IEntityCollection ec = order.Order_Details; Assert.IsFalse(ec.HasValues); EntityChangeSet cs = entities.GetChanges(); Assert.AreEqual(2, cs.ModifiedEntities.Count); // after computing the changeset, no association members // should have been loaded er = detail.GetEntityRef("Order"); Assert.IsNull(er); Assert.IsFalse(ec.HasValues); // after building the operation list, no association members // should have been loaded ChangeSetBuilder.Build(cs); er = detail.GetEntityRef("Order"); Assert.IsNull(er); Assert.IsFalse(ec.HasValues); }
public IntervalChangeReader(DbReaderAndChangeChecker checker) { this.checker = checker; // I like to use Do instead of just combining this all into Select to make the side effect obvious. this.Changes = Observable.Interval(TimeSpan.FromSeconds(seconds), scheduler).Do( x => { var changes = DbReaderAndChangeChecker.Refresh(this.knownXRefs); // Make changes to knownXRefs which is my state. this.knownXRefs.AddRange(changes.Added); this.knownXRefs.RemoveAll(y => changes.Removed.Any(z => z.Id == y.Id)); this.knownXRefs.RemoveAll(y => changes.Changed.Any(z => z.Id == y.Id)); this.knownXRefs.AddRange(changes.Changed); lastChangeResult = changes; }).Select(x => this.lastChangeResult); }
protected override async Task <SubmitCompletedResult> SubmitAsyncCore(EntityChangeSet changeSet, CancellationToken cancellationToken) { Assert.AreEqual(0, changeSet.AddedEntities.Count, "Change set should not contained added entities."); Assert.IsFalse(changeSet.IsEmpty, "Change set should not be empty."); Assert.AreEqual(1, changeSet.ModifiedEntities.Count, "Change set should contain a single modified entity."); Assert.AreEqual(0, changeSet.RemovedEntities.Count, "Change set should not contained removed entities."); ChangeSetEntry[] submitOperations = changeSet.GetChangeSetEntries().ToArray(); Assert.AreEqual(1, submitOperations.Length, "A single submit operation is expected."); cancellationToken.Register(() => this.CancellationRequested = true); await _callbackDelay.WaitAsync(cancellationToken); // Maybe assert expected type if (this.Error != null) { throw this.Error; } this.Submitted = true; MockUser userToSubmit = (MockUser)submitOperations[0].Entity; MockUser userToReturn = new MockUser() { Name = userToSubmit.Name, Type = UserType.Saved }; List <ChangeSetEntry> submitOperationsToReturn = new List <ChangeSetEntry>(); submitOperationsToReturn.Add(new ChangeSetEntry(userToReturn, submitOperations[0].Id, submitOperations[0].Operation)); var operation = submitOperationsToReturn.First(); operation.Entity = userToReturn; operation.ConflictMembers = this.SubmitConflictMembers; operation.ValidationErrors = this.SubmitValidationErrors; return(new SubmitCompletedResult(changeSet, submitOperationsToReturn)); }
public EntityChangeSet GetCurrentChangeSet() { // Return null if there are no entities in the change set. if (this.EntitiesForInsert.Count == 0 && this.EntitiesForUpdate.Count == 0 && this.EntitiesForDelete.Count == 0) { return(null); } EntityChangeSet changeset = new EntityChangeSet( this.EntitiesForUpdate.AsReadOnly(), this.EntitiesForInsert.AsReadOnly(), this.EntitiesForDelete.AsReadOnly() ); return(changeset); }
public ServiceSubmitChangesResult( EntityChangeSet changeSet, IEnumerable<Entity> entitiesInError, Exception error, bool cancelled, object userState) : base(error, cancelled, userState) { if (changeSet == null) { throw new ArgumentNullException("changeSet"); } if (entitiesInError == null) { throw new ArgumentNullException("entitiesInError"); } this._changeSet = changeSet; this._entitiesInError = entitiesInError; }
/// <summary> /// Verify that all update operations in the specified <see cref="EntityChangeSet"/> are permitted. /// </summary> /// <param name="changeSet">The <see cref="EntityChangeSet"/> to check.</param> internal static void CheckForInvalidUpdates(EntityChangeSet changeSet) { AssociationUpdateChecker associationChecker = new AssociationUpdateChecker(); foreach (Entity entity in changeSet) { if (entity.EntityState == EntityState.Modified) { foreach (PropertyInfo modifiedProperty in entity.ModifiedProperties) { if (modifiedProperty.GetCustomAttributes(typeof(KeyAttribute), false).Any()) { throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, Resource.Entity_KeyMembersCannotBeChanged, modifiedProperty.Name, entity.GetType().Name)); } } } // search associated entities for any invalid changes associationChecker.Visit(entity); } }
public void DomainOperationException_Ctors() { var entities = new List<Entity> {new EntityX()}; var emtpy = new ReadOnlyCollection<Entity>(entities); var changeSet = new EntityChangeSet(emtpy, emtpy, emtpy); // ctor(changeSet, message, status) var soe = new SubmitOperationException(changeSet, "message", OperationErrorStatus.Unauthorized); Assert.AreEqual(changeSet, soe.ChangeSet); Assert.AreEqual("message", soe.Message, "ctor(msg) failed"); Assert.IsNull(soe.InnerException, "InnerException s/b null"); Assert.IsNull(soe.StackTrace, "Default stack trace s/b null"); Assert.AreEqual(0, soe.ErrorCode, "Error code s/b 0"); Assert.AreEqual(OperationErrorStatus.Unauthorized, soe.Status, "ctor(msg, status) failed status"); Assert.IsFalse(soe.ValidationErrors.Any(), "default validationErrors should be empty"); // ctor(changeSet, message, innerException) var ioe = new InvalidOperationException("ioe"); soe = new SubmitOperationException(changeSet, "message", ioe); Assert.AreEqual(changeSet, soe.ChangeSet); Assert.AreEqual("message", soe.Message, "ctor(msg) failed"); Assert.AreSame(ioe, soe.InnerException, "InnerException failed"); Assert.IsNull(soe.StackTrace, "Default stack trace s/b null"); Assert.AreEqual(0, soe.ErrorCode, "Error code s/b 0"); Assert.AreEqual(OperationErrorStatus.ServerError, soe.Status, "Default status s/b ServerError"); Assert.IsFalse(soe.ValidationErrors.Any(), "default validationErrors should be empty"); // ctor(changeSet, message, doe) var doe2 = new DomainOperationException("message", OperationErrorStatus.Unauthorized, 5, "stackTrace"); soe = new SubmitOperationException(changeSet, "mm", doe2); Assert.AreEqual(changeSet, soe.ChangeSet); Assert.AreEqual("mm", soe.Message, "ctor(doe) failed message"); Assert.IsNull(soe.InnerException, "InnerException s/b null"); Assert.AreEqual("stackTrace", soe.StackTrace, "StackTrace failed"); Assert.AreEqual(5, soe.ErrorCode, "Error code failed"); Assert.AreEqual(OperationErrorStatus.Unauthorized, soe.Status, "ctor(msg, status) failed status"); Assert.IsFalse(soe.ValidationErrors.Any(), "default validationErrors should be empty"); }
/// <summary> /// Initializes a new instance of the <see cref="SubmitResult"/> class. /// </summary> /// <param name="changeSet">The changeset which was submitted.</param> public SubmitResult(EntityChangeSet changeSet) { _changeSet = changeSet; }
public void TestMockClientReturnsNull() { NullReturningMockDomainClient dc = new NullReturningMockDomainClient(); AsyncCallback ignored = delegate { }; InvokeArgs invokeArgs = new InvokeArgs("M", typeof(void), null, true /*hasSideEffects*/); DomainClientAsyncResult result = (DomainClientAsyncResult)dc.BeginInvoke(invokeArgs, ignored, null); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndInvoke(result.InnerAsyncResult), "asyncResult"); result = null; result = (DomainClientAsyncResult)dc.BeginQuery(new EntityQuery<Entity>(dc, "GetIgnored", null, true, false), ignored, null); }); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndQuery(result.InnerAsyncResult), "asyncResult"); List<Entity> list = new List<Entity>(); list.Add(new Product()); ReadOnlyCollection<Entity> simpleCollection = new ReadOnlyCollection<Entity>(list); ReadOnlyCollection<Entity> emptyCollection = new ReadOnlyCollection<Entity>(new List<Entity>()); EntityChangeSet emptyChangeSet = new EntityChangeSet(simpleCollection, emptyCollection, emptyCollection); result = null; result = (DomainClientAsyncResult)dc.BeginSubmit(emptyChangeSet, ignored, null); }); EnqueueConditional(() => result != null); EnqueueCallback(delegate { Assert.IsNull(result.InnerAsyncResult); ExceptionHelper.ExpectArgumentNullException( () => dc.EndSubmit(result.InnerAsyncResult), "asyncResult"); }); EnqueueTestComplete(); }
/// <summary> /// Create a IEnumerable which iterates the changeset and returns all validation errors /// </summary> /// <param name="changeSet">ChangeSet to read validation errors from</param> /// <returns></returns> private static IEnumerable<ValidationResult> GetValidationResults(EntityChangeSet changeSet) { return changeSet.Where(p => p.EntityConflict != null || p.HasValidationErrors) .SelectMany(p => p.ValidationErrors); }
/// <summary> /// Submits the specified <see cref="EntityChangeSet"/> to the DomainService asynchronously. /// </summary> /// <param name="changeSet">The <see cref="EntityChangeSet"/> to submit to the DomainService.</param> /// <param name="callback">The callback to invoke when the submit has been executed.</param> /// <param name="userState">Optional user state associated with this operation.</param> /// <returns>An asynchronous result that identifies this submit request.</returns> public IAsyncResult BeginSubmit(EntityChangeSet changeSet, AsyncCallback callback, object userState) { if (callback == null) { throw new ArgumentNullException("callback"); } if (changeSet == null) { throw new ArgumentNullException("changeSet"); } if (changeSet.IsEmpty) { throw new InvalidOperationException(OpenRiaServices.DomainServices.Client.Resource.DomainClient_EmptyChangeSet); } DomainClientAsyncResult domainClientResult = DomainClientAsyncResult.CreateSubmitResult(this, changeSet, callback, userState); // call the actual implementation asynchronously domainClientResult.InnerAsyncResult = this.BeginSubmitCore( changeSet, delegate(IAsyncResult result) { DomainClientAsyncResult clientResult = (DomainClientAsyncResult)result.AsyncState; clientResult.InnerAsyncResult = result; clientResult.Complete(); }, domainClientResult); return domainClientResult; }
public AdcSubmitAsyncResult(EntityChangeSet changeSet, IEnumerable<ChangeSetEntry> submitOperations, MockUser user, AsyncCallback asyncCallback, object asyncState) : base(user, asyncCallback, asyncState) { this._changeSet = changeSet; this._submitOperations = submitOperations; }
protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { return null; }
protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { IEnumerable<ChangeSetEntry> submitOperations = changeSet.GetChangeSetEntries(); MockAsyncResult ar = new MockAsyncResult(null, userState, new object[] { changeSet, submitOperations, userState }); // perform mock submit operations callback.Invoke(ar); return ar; }
/// <summary> /// Creates a new <see cref="DomainClientAsyncResult"/> used for Submit operations. /// </summary> /// <param name="domainClient">The associated <see cref="DomainClient"/>.</param> /// <param name="entityChangeSet">The Submit operation <see cref="EntityChangeSet"/>.</param> /// <param name="callback">The <see cref="AsyncCallback"/> to invoke upon completion.</param> /// <param name="asyncState">Optional user state information that will be passed to the <paramref name="callback"/>.</param> /// <returns>A <see cref="DomainClientAsyncResult"/> used for Submit operations</returns> public static DomainClientAsyncResult CreateSubmitResult(DomainClient domainClient, EntityChangeSet entityChangeSet, AsyncCallback callback, object asyncState) { return new DomainClientAsyncResult(domainClient, entityChangeSet, callback, asyncState); }
/// <summary> /// Method called by the framework to asynchronously process the specified <see cref="EntityChangeSet"/>. /// Overrides should not call the base method. /// </summary> /// <param name="changeSet">The <see cref="EntityChangeSet"/> to submit to the DomainService.</param> /// <param name="callback">The callback to invoke when the submit has been executed.</param> /// <param name="userState">Optional user state associated with this operation.</param> /// <returns>An asynchronous result that identifies this submit request.</returns> protected virtual IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { throw new NotSupportedException(); }
/// <summary> /// Constructor that accepts a localized exception message and status /// </summary> /// <param name="changeSet">the changeset being submitted</param> /// <param name="message">The localized exception message</param> /// <param name="status">The status of the exception</param> public SubmitOperationException(EntityChangeSet changeSet, string message, OperationErrorStatus status) : this(changeSet, message, /*innerException*/ null, status, /*errorCode*/ 0, /*stackTrace*/ null) { _changeSet = changeSet; }
public void DomainClient_SubmitWithNullInvocation() { TestEntityContainer container = new TestEntityContainer(); //TODO: find a better way to not hardcode the list of known types WebDomainClient<CityDomainContext.ICityDomainServiceContract> client = new WebDomainClient<CityDomainContext.ICityDomainServiceContract>(TestURIs.Cities) { EntityTypes = new Type[] { typeof(City), typeof(ChangeSetEntry), typeof(EntityOperationType) } }; List<Entity> emptyList = new List<Entity>(); List<Entity> modifiedEntities = new List<Entity>(); // invoke domain methods on a few entities container.LoadEntities(_cities); _cities[1].AssignCityZone(_assignCityZone.Parameters.First().ToString()); // submit changeset with hand-crafted entities: valid invocation and null invocation modifiedEntities.Add(_cities[0]); modifiedEntities.Add(_cities[1]); modifiedEntities.Add(_cities[2]); Assert.AreEqual(EntityState.Modified, _cities[1].EntityState); EntityChangeSet changeset = new EntityChangeSet(emptyList.AsReadOnly(), modifiedEntities.AsReadOnly(), emptyList.AsReadOnly()); SubmitCompletedResult submitResults = null; client.BeginSubmit( changeset, delegate(IAsyncResult asyncResult) { submitResults = client.EndSubmit(asyncResult); }, null ); // wait for submit to complete EnqueueConditional(() => submitResults != null); EnqueueCallback(delegate { Assert.AreEqual(1, submitResults.Results.Count()); Assert.AreEqual(1, submitResults.Results.Where(e => e.Operation == EntityOperationType.Update).Count()); // REVIEW: Do we really need the operation data back from the server? // ChangeSetEntry returned = submitResults.Results.Single(e => e.OperationName == _assignCityZone.Name); // Assert.IsNotNull(returned); // Assert.AreEqual(1, returned.OperationData.Count()); }); EnqueueTestComplete(); }
/// <summary> /// Private constructor used by all public constructors. /// </summary> /// <param name="changeSet">the changeset being submitted</param> /// <param name="message">The localized error message</param> /// <param name="innerException">Optional inner exception.</param> /// <param name="status">status of the exception</param> /// <param name="errorCode">custom error code</param> /// <param name="stackTrace">stack trace of the exception</param> private SubmitOperationException(EntityChangeSet changeSet, string message, Exception innerException, OperationErrorStatus status, int errorCode, string stackTrace) : base(message, innerException, status, errorCode, stackTrace, GetValidationResults(changeSet)) { _changeSet = changeSet; }
/// <summary> /// Method called by the framework to asynchronously process the specified <see cref="T:OpenRiaServices.DomainServices.Client.EntityChangeSet" />. /// Overrides should not call the base method. /// </summary> /// <param name="changeSet">The <see cref="T:OpenRiaServices.DomainServices.Client.EntityChangeSet" /> to submit to the DomainService.</param> /// <param name="callback">The callback to invoke when the submit has been executed.</param> /// <param name="userState">Optional user state associated with this operation.</param> /// <returns> /// An asynchronous result that identifies this submit request. /// </returns> protected override IAsyncResult BeginSubmitCore(EntityChangeSet changeSet, AsyncCallback callback, object userState) { var result = WebApiDomainClientAsyncResult.CreateSubmitResult(this, changeSet, changeSet.GetChangeSetEntries().ToList(), callback, userState); var parameters = new Dictionary<string, object>() { {"changeSet", result.ChangeSetEntries} }; return BeginWebRequest(result, hasSideEffects: true, parameters: parameters, queryOptions: null); }
public void DomainClient_SubmitWithNonexistentDomainMethod() { TestEntityContainer container = new TestEntityContainer(); WebDomainClient<CityDomainContext.ICityDomainServiceContract> client = new WebDomainClient<CityDomainContext.ICityDomainServiceContract>(TestURIs.Cities) { EntityTypes = new Type[] { typeof(City) } }; List<Entity> emptyList = new List<Entity>(); List<Entity> modifiedEntities = new List<Entity>(); // invoke domain methods on a few entities container.LoadEntities(_cities); _cities[0].CustomMethodInvocation = _reject; // submit changeset with hand-crafted entities (without calling Invoke) modifiedEntities.Add(_cities[0]); EntityChangeSet changeset = new EntityChangeSet(emptyList.AsReadOnly(), modifiedEntities.AsReadOnly(), emptyList.AsReadOnly()); SubmitCompletedResult submitResults = null; DomainOperationException expectedException = null; EnqueueCallback(delegate { client.BeginSubmit( changeset, delegate(IAsyncResult asyncResult) { try { submitResults = client.EndSubmit(asyncResult); } catch (DomainOperationException e) { expectedException = e; } }, null ); }); EnqueueConditional(() => expectedException != null); EnqueueCallback(delegate { Assert.IsNull(submitResults); Assert.AreEqual("This DomainService does not support operation 'Reject' for entity 'CityWithInfo'.", expectedException.Message); }); EnqueueTestComplete(); }
/// <summary> /// Internal "copy" constructor. /// </summary> /// <param name="changeSet">the changeset being submitted</param> /// <param name="message">The new error message to use</param> /// <param name="exception">The exception to copy</param> internal SubmitOperationException(EntityChangeSet changeSet, string message, DomainOperationException exception) : this(changeSet, message, exception.InnerException, exception.Status, exception.ErrorCode, exception.StackTrace) { _changeSet = changeSet; }
/// <summary> /// Constructor that accepts a localized exception message and status /// </summary> /// <param name="changeSet">the changeset being submitted</param> /// <param name="message">The localized exception message</param> /// <param name="innerException">inner exception.</param> public SubmitOperationException(EntityChangeSet changeSet, string message, Exception innerException) : this(changeSet, message, innerException, /*status*/ OperationErrorStatus.ServerError, /*errorCode*/ 0, /*stackTrace*/ null) { _changeSet = changeSet; }
protected override IEnumerable<ChangeSetEntry> Submit(EntityChangeSet changeSet) { return null; }