public async Task Load_Cancel_DomainClientCancel()
        {
            var mockDomainClient = new CitiesMockDomainClient();

            Cities.CityDomainContext ctx = new Cities.CityDomainContext(mockDomainClient);

            // If cancellation results in request beeing cancelled the result should be cancelled
            var tcs = new TaskCompletionSource <QueryCompletedResult>();

            mockDomainClient.QueryCompletedResult = tcs.Task;
            var loadOp = ctx.Load(ctx.GetCitiesQuery());

            loadOp.Cancel();

            Assert.IsTrue(loadOp.IsCancellationRequested);
            Assert.IsTrue(ctx.IsLoading);
            Assert.IsFalse(loadOp.IsCanceled);
            Assert.IsFalse(loadOp.IsComplete);

            tcs.TrySetCanceled(loadOp.CancellationToken);
            await loadOp;

            Assert.IsFalse(ctx.IsLoading);
            Assert.IsTrue(loadOp.IsCanceled);
            Assert.IsTrue(loadOp.IsComplete);
            Assert.IsFalse(loadOp.HasError, "Cancelled operation should not have any error");
        }
        public async Task LoadAsync_Cancel_DomainClientCompletes()
        {
            var mockDomainClient = new CitiesMockDomainClient();

            Cities.CityDomainContext ctx = new Cities.CityDomainContext(mockDomainClient);
            var city = new City()
            {
                Name = "NewCity", StateName = "NN", CountyName = "NewCounty"
            };

            // If cancellation results in request beeing cancelled the result should be cancelled
            var tcs = new TaskCompletionSource <QueryCompletedResult>();

            using var cts = new CancellationTokenSource();
            mockDomainClient.QueryCompletedResult = tcs.Task;
            var loadTask = ctx.LoadAsync(ctx.GetCitiesQuery(), cts.Token);

            cts.Cancel();
            tcs.SetResult(new QueryCompletedResult(new[] { city }, Array.Empty <Entity>(), -1, Array.Empty <ValidationResult>()));

            var result = await loadTask;

            Assert.AreEqual(1, result.Entities.Count);
            Assert.AreSame(city, result.Entities.First());
        }
        public void Load_ValidationErrors()
        {
            var mockDomainClient = new CitiesMockDomainClient();

            ValidationResult[] validationErrors = new ValidationResult[] { new ValidationResult("Foo", new string[] { "Bar" }) };
            mockDomainClient.QueryCompletedResult = Task.FromResult(new QueryCompletedResult(Enumerable.Empty <Entity>(), Enumerable.Empty <Entity>(), 0, validationErrors));
            Cities.CityDomainContext ctx = new Cities.CityDomainContext(mockDomainClient);
            string myState = "Test User State";

            LoadOperation <Cities.City> loadOperation = ctx.Load(ctx.GetCitiesQuery(), LoadBehavior.RefreshCurrent, l => l.MarkErrorAsHandled(), myState);;

            this.EnqueueCompletion(() => loadOperation);
            EnqueueCallback(delegate
            {
                Assert.AreSame(myState, loadOperation.UserState);

                CollectionAssert.AreEqual(validationErrors, (ICollection)loadOperation.ValidationErrors);

                // verify the exception properties
                var ex = loadOperation.Error as DomainOperationException;
                Assert.IsNotNull(ex, "expected exception of type DomainOperationException");
                Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
                Assert.AreEqual(string.Format(Resource.DomainContext_LoadOperationFailed_Validation, "GetCities"), ex.Message);
            });

            EnqueueTestComplete();
        }
        public async Task Load()
        {
            Cities.CityDomainContext ctx = new Cities.CityDomainContext(new CitiesMockDomainClient());
            string myState = "Test User State";

            var           query = ctx.GetCitiesQuery().Where(p => p.StateName == "WA").OrderBy(p => p.CountyName).Take(4);
            LoadOperation lo    = ctx.Load(query, TestHelperMethods.DefaultOperationAction, myState);

            await lo;

            Assert.IsNull(lo.Error);
            Assert.AreEqual(4, ctx.Cities.Count);
            Assert.IsTrue(ctx.Cities.All(p => p.StateName == "WA"));
            Assert.AreEqual(myState, lo.UserState);
        }
        public async Task LoadAsync_ValidationErrors()
        {
            var mockDomainClient = new CitiesMockDomainClient();

            ValidationResult[] validationErrors = new ValidationResult[] { new ValidationResult("Foo", new string[] { "Bar" }) };
            mockDomainClient.QueryCompletedResult = Task.FromResult(new QueryCompletedResult(Enumerable.Empty <Entity>(), Enumerable.Empty <Entity>(), 0, validationErrors));
            Cities.CityDomainContext ctx = new Cities.CityDomainContext(mockDomainClient);

            var ex = await ExceptionHelper.ExpectExceptionAsync <DomainOperationException>(
                () => ctx.LoadAsync(ctx.GetCitiesQuery()),
                string.Format(Resource.DomainContext_LoadOperationFailed_Validation, "GetCities"));

            // verify the exception properties
            Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
            CollectionAssert.AreEqual(validationErrors, (ICollection)ex.ValidationErrors);
        }
        public void CancellationSupport()
        {
            var domainClient = new CitiesMockDomainClient();

            domainClient.SetSupportsCancellation(false);
            Cities.CityDomainContext ctx = new Cities.CityDomainContext(domainClient);

            var           query = ctx.GetCitiesQuery();
            LoadOperation lo    = ctx.Load(query, false);

            Assert.IsFalse(lo.CanCancel, "Cancellation should not be supported.");
            Assert.IsFalse(ctx.DomainClient.SupportsCancellation, "Cancellation should not be supported.");

            ExceptionHelper.ExpectException <NotSupportedException>(delegate
            {
                lo.Cancel();
            }, string.Format(CultureInfo.CurrentCulture, Resources.AsyncOperation_CancelNotSupported));
        }
        public async Task LoadAsync_Cancel_DomainClientCancel()
        {
            var mockDomainClient = new CitiesMockDomainClient();

            Cities.CityDomainContext ctx = new Cities.CityDomainContext(mockDomainClient);

            // If cancellation results in request beeing cancelled the result should be cancelled
            var tcs = new TaskCompletionSource <QueryCompletedResult>();

            using var cts = new CancellationTokenSource();
            mockDomainClient.QueryCompletedResult = tcs.Task;
            var loadTask = ctx.LoadAsync(ctx.GetCitiesQuery(), cts.Token);

            Assert.IsTrue(ctx.IsLoading);
            cts.Cancel();
            tcs.TrySetCanceled(cts.Token);

            await ExceptionHelper.ExpectExceptionAsync <OperationCanceledException>(() => loadTask, allowDerivedExceptions : true);

            Assert.IsTrue(loadTask.IsCanceled);
            Assert.IsFalse(ctx.IsLoading);
        }
        public void Bug706034_AccessCachedEntityResultsInCallback()
        {
            Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);

            bool callbackCalled = false;
            Exception callbackException = null;
            Action<LoadOperation<City>> callback = (op) =>
            {
                if (op.HasError)
                {
                    op.MarkErrorAsHandled();
                }

                try
                {
                    Assert.AreEqual(11, op.AllEntities.Count());
                    Assert.AreEqual(11, op.Entities.Count());
                }
                catch (Exception e)
                {
                    callbackException = e;
                }
                finally
                {
                    callbackCalled = true;
                }
            };

            var q = cities.GetCitiesQuery();
            LoadOperation<City> lo = cities.Load(q, callback, null);

            // KEY to bug : access Entity collections to force them to cache
            IEnumerable<City> entities = lo.Entities;
            IEnumerable<Entity> allEntities = lo.AllEntities;

            EnqueueConditional(() => lo.IsComplete && callbackCalled);
            EnqueueCallback(delegate
            {
                Assert.IsNull(callbackException);
                Assert.IsNull(lo.Error);

                Assert.AreEqual(11, lo.AllEntities.Count());
                Assert.AreEqual(11, lo.Entities.Count());
            });
            EnqueueTestComplete();
        }
        public void Inherit_Run_CUD_Delete_Derived()
        {
            // Inheritance is City <-- CityWithEditHistory <-- CityWithInfo
            CityDomainContext citiesContext = new CityDomainContext(TestURIs.Cities);
            DateTime priorLastUpdated = DateTime.Now;
            LoadOperation lo = null;
            SubmitOperation so = null;
            CityWithInfo cityWithInfo = null;
            string originalName = null;
            string originalStateName = null;
            string originalCountyName = null;

            // Invoke service operation to clear out all static data
            // (we rely on static data for deleted cities so that it
            //  survives across queries)
            InvokeOperation invoke = citiesContext.ResetData(null, null);

            EnqueueConditional(delegate
            {
                return invoke.IsComplete;
            });
            EnqueueCallback(delegate
            {
                if (invoke.Error != null)
                {
                    Assert.Fail("Failed on invoke of ResetData: " + invoke.Error.Message);
                }
            });

            EnqueueCallback(delegate
            {
                // Load all cities, not just derived ones
                lo = citiesContext.Load(citiesContext.GetCitiesQuery());
            });


            // wait for Load to complete
            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(delegate
            {

                cityWithInfo = citiesContext.Cities.OfType<CityWithInfo>().FirstOrDefault();
                Assert.IsNotNull(cityWithInfo, "expected to find at least one CityWithInfo entity");
                Assert.IsFalse(cityWithInfo.EditHistory.Contains("update"), "Did not expect edit history to be set yet.");

                originalName = cityWithInfo.Name;
                originalStateName = cityWithInfo.StateName;
                originalCountyName = cityWithInfo.CountyName;

                // Delete it.  Note that the delete CUD method in the CityDomainService
                // moves the deleted city over into DeletedCities so it can still be found
                citiesContext.Cities.Remove(cityWithInfo);

                so = citiesContext.SubmitChanges();
            });
            // wait for submit to complete
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                if (so.Error != null)
                {
                    Assert.Fail("Unexpected error on submit: " + so.Error.Message);
                }

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                CityWithInfo deletedCity = citiesContext.Cities.OfType<CityWithInfo>().SingleOrDefault<CityWithInfo>
                                                (c => (c.Name == originalName &&
                                                       c.StateName == originalStateName &&
                                                       c.CountyName == originalCountyName));
                Assert.IsNull(deletedCity, "Did not expect to find deleted City after the submit");
                
                // Load the deleted cities (it was tombstoned)
                citiesContext.Cities.Clear();
                lo = citiesContext.Load(citiesContext.GetDeletedCitiesQuery());
            });

            // Wait for deleted city query to complete
            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(delegate
            {
                if (lo.Error != null)
                {
                    Assert.Fail("Unexpected error on load of deleted queries: " + lo.Error.Message);
                }

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                CityWithInfo deletedCity = citiesContext.Cities.OfType<CityWithInfo>().SingleOrDefault<CityWithInfo>
                                                (c => (c.Name == originalName &&
                                                       c.StateName == originalStateName &&
                                                       c.CountyName == originalCountyName));
                Assert.IsNotNull(deletedCity, "Expected to find deleted City in the tombstone list");
                Assert.IsTrue(deletedCity.EditHistory.Contains("delete"), "Expected edit history to show delete but it only shows: " + deletedCity.EditHistory);
            });

            EnqueueTestComplete();
        }
        public void Inherit_Run_CUD_Update_Derived()
        {
            // Inheritance is City <-- CityWithEditHistory <-- CityWithInfo
            CityDomainContext citiesContext = new CityDomainContext(TestURIs.Cities);
            DateTime priorLastUpdated = DateTime.Now;

            // Load all cities, not just derived ones
            LoadOperation lo = citiesContext.Load(citiesContext.GetCitiesQuery());
            SubmitOperation so = null;
            CityWithInfo cityWithInfo = null;
            string originalName = null;
            string originalStateName = null;
            string originalCountyName = null;

            // wait for Load to complete
            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(delegate
            {

                cityWithInfo = citiesContext.Cities.OfType<CityWithInfo>().FirstOrDefault();
                Assert.IsNotNull(cityWithInfo, "expected to find at least one CityWithInfo entity");
                Assert.IsFalse(cityWithInfo.EditHistory.Contains("update"), "Did not expect edit history to be set yet.");

                originalName = cityWithInfo.Name;
                originalStateName = cityWithInfo.StateName;
                originalCountyName = cityWithInfo.CountyName;

                cityWithInfo.Info = "inserted new info";

                so = citiesContext.SubmitChanges();
            });
            // wait for submit to complete
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                if (so.Error != null)
                {
                    Assert.Fail("Unexpected error on submit: " + so.Error.Message);
                }

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                CityWithInfo updatedCity = citiesContext.Cities.OfType<CityWithInfo>().SingleOrDefault<CityWithInfo>
                                                (c => (c.Name == originalName && 
                                                       c.StateName == originalStateName && 
                                                       c.CountyName == originalCountyName));
                Assert.IsNotNull(updatedCity, "Did not find modified City after the submit");
                Assert.IsTrue(updatedCity.EditHistory.Contains("update"), "EditHistory was" + updatedCity.EditHistory);
                Assert.AreEqual("inserted new info", updatedCity.Info, "Updated Info did not get applied");
            });

            EnqueueTestComplete();
        }
        public void DomainContext_Submit_DomainMethodAndCRUD()
        {
            List<string> propChanged_addedCity = new List<string>();
            City newCity = new City { Name = "Sammamish", CountyName = "King", StateName = "WA" };
            int refZipCode = 0;
            int refCityCount = 0;

            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);

            LoadOperation lo = citiesProvider.Load(citiesProvider.GetCitiesQuery(), false);
            SubmitOperation so = null;

            // wait for LoadCities to complete, then LoadZips
            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                refCityCount = citiesProvider.Cities.Count;
                lo = citiesProvider.Load(citiesProvider.GetZipsQuery(), false);
            });

            // wait for Load to complete, then invoke some domain methods
            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                // this test the following combinations of CRUD and Domain method in changeset:
                // - Invoke -> update
                // - Add -> invoke
                // - Remove
                // - Invoke only
                City[] cities = citiesProvider.Cities.ToArray();
                cities[0].ZoneName = "Zone44";
                cities[0].AssignCityZone("Zone1");
                cities[1].AssignCityZone("Zone2");
                citiesProvider.Cities.Add(newCity);
                newCity.AssignCityZone("Zone3");
                citiesProvider.Cities.Remove(cities[4]);
                citiesProvider.Cities.Remove(cities[5]);

                // keep a reference zip code before invoking the method: this will increment Code by offset=1 on the server
                Zip zip = citiesProvider.Zips.First();
                refZipCode = zip.Code;
                zip.ReassignZipCode(1, true);

                newCity.PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    if (e.PropertyName != "IsReadOnly" && e.PropertyName != "HasChanges"
                        && e.PropertyName != "EntityState" && e.PropertyName != "ValidationErrors")
                    {
                        propChanged_addedCity.Add(e.PropertyName);
                    }
                };

                Assert.IsTrue(newCity.CanAssignCityZoneIfAuthorized);
                Assert.IsTrue(newCity.CanAutoAssignCityZone);

                so = citiesProvider.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);

                Assert.IsFalse(newCity.CanAssignCityZoneIfAuthorized);
                Assert.IsFalse(newCity.CanAutoAssignCityZone);

                Assert.AreEqual(3, so.ChangeSet.ModifiedEntities.Count);
                Assert.AreEqual(1, so.ChangeSet.AddedEntities.Count);
                Assert.AreEqual(2, so.ChangeSet.RemovedEntities.Count);
            });
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                Assert.IsNull(so.Error, string.Format("SubmitOperation.Error should be null.\r\nMessage: {0}\r\nStack Trace:\r\n{1}", so.Error != null ? so.Error.Message : string.Empty, so.Error != null ? so.Error.StackTrace : string.Empty));
                Assert.IsTrue(newCity.CanAssignCityZoneIfAuthorized);
                Assert.IsTrue(newCity.CanAutoAssignCityZone);
                Assert.IsTrue(newCity.CanAssignCityZone);

                // verify we got property change notifications for the new city entity (guard property should be reverted once SubmitChanges is called)
                Assert.AreEqual(9, propChanged_addedCity.Count);
                Assert.AreEqual(1, propChanged_addedCity.Count(prop => prop == "ZoneName"));
                Assert.AreEqual(1, propChanged_addedCity.Count(prop => prop == "ZoneID"));
                Assert.AreEqual(1, propChanged_addedCity.Count(prop => prop == "CanAssignCityZone"));
                Assert.AreEqual(1, propChanged_addedCity.Count(prop => prop == "IsAssignCityZoneInvoked"));
                // The other custom method invocations should have changed from true -> false during submit
                // and from false -> true after submit
                Assert.AreEqual(2, propChanged_addedCity.Count(prop => prop == "CanAssignCityZoneIfAuthorized"));
                Assert.AreEqual(2, propChanged_addedCity.Count(prop => prop == "CanAutoAssignCityZone"));


                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                Assert.AreEqual(1, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Zone1" && c.CountyName == "King")).ZoneID);
                Assert.AreEqual(2, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Zone2")).ZoneID);
                Assert.AreEqual(3, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Zone3" && c.Name == newCity.Name)).ZoneID);
                Assert.IsTrue(citiesProvider.Zips.Any<Zip>(z => z.Code == refZipCode - 1));

                // verify unchanged entities
                Assert.IsFalse(citiesProvider.Cities.Any(c => (c.ZoneName == null && c.ZoneID != 0)));

                // verify that after a successful submit, DM invocations on the entities have been accepted
                Assert.IsFalse(so.ChangeSet.ModifiedEntities.Any(p => p.EntityActions.Any()));
                EntityChangeSet changeSet = citiesProvider.EntityContainer.GetChanges();
                Assert.IsTrue(changeSet.IsEmpty);
            });

            EnqueueTestComplete();
        }
        public void CustomMethodFlag_ChangeNotifications()
        {
            List<string> propChanged = new List<string>();
            CityDomainContext ctxt = new CityDomainContext(TestURIs.Cities);
            City city = null;

            LoadOperation lo = ctxt.Load(ctxt.GetCitiesQuery(), false);
            SubmitOperation so = null;

            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                city = ctxt.Cities.First();

                city.PropertyChanged += (s, e) =>
                {
                    propChanged.Add(e.PropertyName);
                };

                Assert.IsTrue(city.CanAssignCityZone);
                Assert.IsFalse(city.IsAssignCityZoneInvoked);

                city.AssignCityZone("Twilight");

                Assert.IsFalse(city.CanAssignCityZone);
                Assert.IsTrue(city.IsAssignCityZoneInvoked);

                Assert.IsTrue(propChanged.Contains("CanAssignCityZone"));
                Assert.IsTrue(propChanged.Contains("IsAssignCityZoneInvoked"));
                propChanged.Clear();

                so = ctxt.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);
            });
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                Assert.IsFalse(so.HasError);

                Assert.IsTrue(city.CanAssignCityZone);
                Assert.IsFalse(city.IsAssignCityZoneInvoked);

                Assert.IsTrue(propChanged.Contains("CanAssignCityZone"));
                Assert.IsTrue(propChanged.Contains("IsAssignCityZoneInvoked"));
            });
            EnqueueTestComplete();
        }
        public void DomainContext_Submit_CUDOperationMethodValidation()
        {
            CityDomainContext ctxt = new CityDomainContext(TestURIs.Cities);

            LoadOperation lo = ctxt.Load(ctxt.GetCitiesQuery(), false);
            SubmitOperation so = null;

            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                TestHelperMethods.AssertOperationSuccess(lo);

                // update
                City[] cities = ctxt.Cities.Where(p => p.GetType() == typeof(City)).ToArray();
                City city = cities[0];
                city.ZoneID = 693;

                // custom method
                city.AssignCityZone("Z1");

                // delete
                City deletedCity = new City() { Name = "Issaquah", CountyName = "King", StateName = "WA", ZoneID = 693 };
                ctxt.Cities.Attach(deletedCity);
                ctxt.Cities.Remove(deletedCity);

                // insert
                City newCity = new City() { Name = "Sylvannia", CountyName = "Lucas", StateName = "OH" };
                newCity.ZoneID = 693;
                ctxt.Cities.Add(newCity);

                so = ctxt.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);
            });
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                DomainOperationException ex = so.Error as DomainOperationException;
                Assert.IsNotNull(ex);
                Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
                Assert.AreEqual(Resource.DomainContext_SubmitOperationFailed_Validation, ex.Message);

                EntityChangeSet cs = so.ChangeSet;

                City city = (City)cs.AddedEntities.Single();
                Assert.AreEqual("CityMethodValidator.ValidateMethod Failed (InsertCity)!", city.ValidationErrors.Single().ErrorMessage);

                city = (City)cs.ModifiedEntities.Single();
                ValidationResult[] validationResults = city.ValidationErrors.ToArray();
                Assert.AreEqual("CityMethodValidator.ValidateMethod Failed (UpdateCity)!", validationResults[0].ErrorMessage);
                Assert.AreEqual("CityMethodValidator.ValidateMethod Failed (AssignCityZone)!", validationResults[1].ErrorMessage);

                city = (City)cs.RemovedEntities.Single();
                Assert.AreEqual("CityMethodValidator.ValidateMethod Failed (DeleteCity)!", city.ValidationErrors.Single().ErrorMessage);
            });

            EnqueueTestComplete();
        }
        public void Cities_TestLoad()
        {
            CityDomainContext dp = new CityDomainContext(TestURIs.Cities);    // Abs URI so runs on desktop too

            LoadOperation lo = dp.Load(dp.GetCitiesQuery(), false);

            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(() => 
                {
                    if (lo.Error != null)
                        Assert.Fail("LoadOperation.Error: " + lo.Error.Message);
                    IEnumerable<City> expected = new CityData().Cities;
                    AssertSame(expected, dp.Cities);
                });

            EnqueueTestComplete();
        }
        public void Exceptions()
        {
            Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);

            Action<LoadOperation<City>> loCallback = (op) =>
            {
                if (op.HasError)
                {
                    op.MarkErrorAsHandled();
                }

                throw new InvalidOperationException("Fnord!");
            };

            Action<SubmitOperation> soCallback = (op) =>
            {
                if (op.HasError)
                {
                    op.MarkErrorAsHandled();
                }

                throw new InvalidOperationException("Fnord!");
            };

            Action<InvokeOperation> ioCallback = (op) =>
            {
                if (op.HasError)
                {
                    op.MarkErrorAsHandled();
                }

                throw new InvalidOperationException("Fnord!");
            };

            LoadOperation lo = new LoadOperation<City>(cities.GetCitiesQuery(), LoadBehavior.MergeIntoCurrent, loCallback, null, loCallback);

            // verify completion callbacks that throw
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                try
                {
                    lo.Complete(DomainClientResult.CreateQueryResult(new Entity[0], new Entity[0], 0, new ValidationResult[0]));
                }
                catch (Exception ex)
                {
                    Assert.IsTrue(ex.StackTrace.Contains("at OpenRiaServices.DomainServices.Client.Test.OperationTests"), "Stacktrace not preserved.");

                    throw;
                }
            }, "Fnord!");

            // verify cancellation callbacks for all fx operation types
            lo = new LoadOperation<City>(cities.GetCitiesQuery(), LoadBehavior.MergeIntoCurrent, null, null, loCallback);
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                lo.Cancel();
            }, "Fnord!");

            SubmitOperation so = new SubmitOperation(cities.EntityContainer.GetChanges(), soCallback, null, soCallback);
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                so.Cancel();
            }, "Fnord!");

            InvokeOperation io = new InvokeOperation("Fnord", null, null, null, ioCallback);
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                io.Cancel();
            }, "Fnord!");
        }
        public void Bug706066_CancelInCallback()
        {
            Cities.CityDomainContext cities = new CityDomainContext(TestURIs.Cities);

            bool callbackCalled = false;
            InvalidOperationException expectedException = null;
            Action<LoadOperation<City>> callback = (op) =>
            {
                if (op.HasError)
                {
                    op.MarkErrorAsHandled();
                }

                // verify that CanCancel is false even though we'll
                // ignore this and try below
                Assert.IsFalse(op.CanCancel);

                try
                {
                    op.Cancel();
                }
                catch (InvalidOperationException io)
                {
                    expectedException = io;
                }
                callbackCalled = true;
            };

            var q = cities.GetCitiesQuery().Take(1);
            LoadOperation lo = cities.Load(q, callback, null);

            EnqueueConditional(() => lo.IsComplete && callbackCalled);
            EnqueueCallback(delegate
            {
                Assert.IsFalse(lo.IsCanceled);
                Assert.AreEqual(Resources.AsyncOperation_AlreadyCompleted, expectedException.Message);
            });
            EnqueueTestComplete();
        }
        public void Cities_TestLoad_Demo()
        {
            CityDomainContext dp = new CityDomainContext(TestURIs.Cities);    // Abs URI so runs on desktop too

            LoadOperation lo = dp.Load(dp.GetCitiesQuery(), false);

            After(() => lo.IsComplete);

            Then(() => {
                if (lo.Error != null)
                    Assert.Fail("LoadOperation.Error: " + lo.Error.Message);
            });

            Then(() => AssertSame(new CityData().Cities, dp.Cities));

            EnqueueTestComplete();
        }
        public void DomainContext_Submit_ValidationErrorDuringClientSubmit()
        {
            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);
            Zip newZip = new Zip() { Code = 98765, FourDigit = 1234 };
            Zip validZip = new Zip() { Code = 90000, FourDigit = 1000, CityName = "MyCity", StateName = "MY" };
            City deletedCity = null;

            SubmitOperation so = null;
            LoadOperation loadCitiesOperation = citiesProvider.Load(citiesProvider.GetCitiesQuery(), false);
            LoadOperation loadZipsOperation = citiesProvider.Load(citiesProvider.GetZipsQuery(), false);

            // wait for Load to complete, then invoke domain method that throws on server. Submit.
            EnqueueConditional(() => loadCitiesOperation.IsComplete && loadZipsOperation.IsComplete);
            EnqueueCallback(delegate
            {
                // update entity in a way that caused entity validation to fail on client
                Zip[] zips = citiesProvider.Zips.ToArray();
                zips[0].CityName = zips[0].StateName;

                // internally set domain method invocation to cause method param validation to fail on client
                zips[0].CustomMethodInvocation = new EntityAction("ReassignZipCode", new object[] { -10000, true });

                // insert entity that caused object/property validation to fail on client
                citiesProvider.Zips.Add(newZip);

                // Add a temporary error to that invalid object to ensure errors are reset during submit
                newZip.ValidationErrors.Add(new ValidationResult("Temporary Error", new string[] { "StateName" }));

                // insert entity that is valid
                citiesProvider.Zips.Add(validZip);

                // Add a temporary error to that valid object to ensure errors are reset during submit
                validZip.ValidationErrors.Add(new ValidationResult("Temporary Error", new string[] { "StateName" }));

                // remove city
                City[] cities = citiesProvider.Cities.ToArray();
                deletedCity = cities[1];
                citiesProvider.Cities.Remove(deletedCity);

                so = citiesProvider.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);
            });

            // wait for submitted event being fired and verify Entity.ValidationErrors is not empty
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                DomainOperationException ex = so.Error as DomainOperationException;
                Assert.IsNotNull(ex);
                Assert.AreEqual(OperationErrorStatus.ValidationFailed, ex.Status);
                Assert.AreEqual(Resource.DomainContext_SubmitOperationFailed_Validation, ex.Message);

                // verify errors are generated on the client side
                Zip[] zips = citiesProvider.Zips.ToArray();
                IEnumerable<ValidationResult> errors = zips[0].ValidationErrors;
                LogErrorListContents("citiesProvider.Zips[0].ValidationErrors", errors);
                Assert.AreEqual(2, errors.Count());
                UnitTestHelper.AssertListContains<ValidationResult>(errors, (e => e.ErrorMessage == "The field offset must be between -9999 and 9999."));
                UnitTestHelper.AssertListContains<ValidationResult>(errors, (e => e.ErrorMessage == "Zip codes cannot have matching city and state names" && e.MemberNames.Contains("StateName") && e.MemberNames.Contains("CityName")));

                LogErrorListContents("newZip.ValidationErrors", newZip.ValidationErrors);
                errors = newZip.ValidationErrors;

                // Expect only 2 errors for the properties.  The entity level error is not checked if property level checks fail
                Assert.AreEqual(2, errors.Count());
                UnitTestHelper.AssertListContains<ValidationResult>(errors, (e => e.ErrorMessage == "The CityName field is required."));
                UnitTestHelper.AssertListContains<ValidationResult>(errors, (e => e.ErrorMessage == "The StateName field is required."));

                Assert.AreEqual(0, deletedCity.ValidationErrors.Count(), "The deleted city shouldn't have any validation errors");
                Assert.AreEqual(0, validZip.ValidationErrors.Count(), "The valid city shouldn't have any validation errors");
            });

            EnqueueTestComplete();
        }
        public void Cities_Cities_In_County_Serialized_Query()
        {
            CityDomainContext dp = new CityDomainContext(TestURIs.Cities);    // Abs URI so runs on desktop too

            // Pass the query to the server to select only cities in King county
            var cityQuery = dp.GetCitiesQuery().Where(c => c.CountyName == "King");
            LoadOperation lo = dp.Load(cityQuery, false);

            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(() =>
            {
                if (lo.Error != null)
                    Assert.Fail("LoadOperation.Error: " + lo.Error.Message);
                IEnumerable<City> expected = new CityData().Cities.Where(c => c.CountyName == "King");
                AssertSame(expected, dp.Cities);
            });

            EnqueueTestComplete();
        }
        public void DomainContext_Submit_DomainMethodOnly()
        {
            EntityChangeSet changeset;
            List<string> propChanged = new List<string>();
            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);

            LoadOperation lo = citiesProvider.Load(citiesProvider.GetCitiesQuery(), false);
            SubmitOperation so = null;

            City firstRootCity = null;
            City lastRootCity = null;

            // wait for Load to complete, then invoke some domain methods
            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                changeset = citiesProvider.EntityContainer.GetChanges();
                Assert.IsTrue(changeset.IsEmpty);

                // Find a root city.  This test specifically does not want to accidently use a derived type
                firstRootCity = citiesProvider.Cities.Where(c => c.GetType() == typeof(City)).FirstOrDefault();
                Assert.IsNotNull(firstRootCity, "Expected to find a root City type in entity list");

                lastRootCity = citiesProvider.Cities.Where(c => c.GetType() == typeof(City)).LastOrDefault();
                Assert.IsNotNull(lastRootCity, "Expected to find a root City type in entity list");

                Assert.AreNotEqual(firstRootCity, lastRootCity, "Expected first and last city to be different");

                firstRootCity.PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    bool isEntityBaseProperty = typeof(City).GetProperty(e.PropertyName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) == null;
                    if (!isEntityBaseProperty)
                    {
                        propChanged.Add(e.PropertyName);
                    }
                };

                Assert.IsTrue(firstRootCity.CanAssignCityZone);
                firstRootCity.AssignCityZone("Zone15");
            });

            // wait for prop changed for domain method guards
            EnqueueConditional(() => propChanged.Count > 0);
            EnqueueCallback(delegate
            {
                Assert.IsTrue(propChanged.Contains("CanAssignCityZone"));
                Assert.IsTrue(propChanged.Contains("IsAssignCityZoneInvoked"));
                Assert.IsFalse(propChanged.Contains("CanAutoAssignCityZone"));
                propChanged.Clear();

                Assert.IsTrue(lastRootCity.CanAutoAssignCityZone);
                lastRootCity.AutoAssignCityZone();

                changeset = citiesProvider.EntityContainer.GetChanges();
                Assert.AreEqual(2, changeset.ModifiedEntities.Count);

                so = citiesProvider.SubmitChanges(TestHelperMethods.DefaultOperationAction, null);

                Assert.AreEqual(2, so.ChangeSet.ModifiedEntities.Count);
                Assert.AreEqual(0, so.ChangeSet.AddedEntities.Count);
                Assert.AreEqual(0, so.ChangeSet.RemovedEntities.Count);
            });
            // wait for submit to complete, then verify invoked entities in changeset
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                Assert.IsNull(so.Error);
                Assert.AreEqual(2, so.ChangeSet.ModifiedEntities.Count);

                // verify we got the property change notification for the city entity as a result of autosync
                Assert.AreEqual(8, propChanged.Count);
                Assert.AreEqual(1, propChanged.Count(prop => prop == "ZoneName"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "ZoneID"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "CanAssignCityZone"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "IsAssignCityZoneInvoked"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanAutoAssignCityZone"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanAssignCityZoneIfAuthorized"));

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                Assert.AreEqual(15, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Zone15")).ZoneID);
                Assert.AreEqual(1, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Auto_Zone1")).ZoneID);

                // verify unchanged entities
                Assert.AreEqual(0, citiesProvider.Cities.First(c => (c.ZoneName == null)).ZoneID);
            });

            EnqueueTestComplete();
        }
        public void Inherit_Run_Call_Base_Custom_Method_On_Derived_Entity()
        {
            EntityChangeSet changeset;
            List<string> propChanged = new List<string>();
            CityDomainContext citiesProvider = new CityDomainContext(TestURIs.Cities);

            LoadOperation lo = citiesProvider.Load(citiesProvider.GetCitiesQuery());
            SubmitOperation so = null;

            CityWithInfo cityWithInfo = null;

            // wait for Load to complete, then invoke some domain methods
            EnqueueConditional(() => lo.IsComplete);
            EnqueueCallback(delegate
            {
                changeset = citiesProvider.EntityContainer.GetChanges();
                Assert.IsTrue(changeset.IsEmpty);

                cityWithInfo = citiesProvider.Cities.OfType<CityWithInfo>().FirstOrDefault();
                Assert.IsNotNull(cityWithInfo, "Expected to find a CityWithInfo type in entity list");

                cityWithInfo.PropertyChanged += delegate(object sender, System.ComponentModel.PropertyChangedEventArgs e)
                {
                    // We filter to only those properties we see in the City hierarchy
                    BindingFlags flags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly;
                    bool isCityProperty = (typeof(CityWithInfo).GetProperty(e.PropertyName, flags) != null ||
                                           typeof(CityWithEditHistory).GetProperty(e.PropertyName, flags) != null ||
                                           typeof(City).GetProperty(e.PropertyName, flags) != null);
                    if (isCityProperty)
                    {
                        propChanged.Add(e.PropertyName);
                    }
                };

                Assert.IsTrue(cityWithInfo.CanAssignCityZone);
                cityWithInfo.AssignCityZone("Zone15");
            });

            // wait for prop changed for domain method guards
            EnqueueConditional(() => propChanged.Count > 0);
            EnqueueCallback(delegate
            {
                Assert.IsTrue(propChanged.Contains("CanAssignCityZone"));
                propChanged.Clear();

                changeset = citiesProvider.EntityContainer.GetChanges();
                Assert.AreEqual(1, changeset.ModifiedEntities.Count);
                so = citiesProvider.SubmitChanges();

                Assert.AreEqual(1, so.ChangeSet.ModifiedEntities.Count);
                Assert.AreEqual(0, so.ChangeSet.AddedEntities.Count);
                Assert.AreEqual(0, so.ChangeSet.RemovedEntities.Count);
            });
            // wait for submit to complete, then verify invokedEntities in changeset
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                if (so.Error != null)
                {
                    Assert.Fail(so.Error.Message);
                }
                Assert.AreEqual(1, so.ChangeSet.ModifiedEntities.Count);
                // verify we got the property change notification for the city entity as a result of autosync
                Assert.AreEqual(13, propChanged.Count, "Received different property notifications than expected:\r\n" + string.Join(",", propChanged.ToArray()));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "EditHistory"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "ZoneName"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "ZoneID"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "CanAssignCityZone"));
                Assert.AreEqual(1, propChanged.Count(prop => prop == "IsAssignCityZoneInvoked"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanAutoAssignCityZone"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanAssignCityZoneIfAuthorized"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanSetCityInfo"));
                Assert.AreEqual(2, propChanged.Count(prop => prop == "CanTouchHistory"));

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                Assert.AreEqual(15, citiesProvider.Cities.Single<City>(c => (c.ZoneName == "Zone15")).ZoneID);

                // verify unchanged entities
                Assert.AreEqual(0, citiesProvider.Cities.First(c => (c.ZoneName == null)).ZoneID);
            });

            EnqueueTestComplete();
        }
        public void LinqQueryWhenLoadingData()
        {
            EnqueueCallback(() =>
            {
                CityDomainContext context = new CityDomainContext();
                this._dds.QueryName = "GetCitiesQuery";
                this._dds.DomainContext = context;
                this._dds.LoadingData += (object sender, OpenRiaServices.Controls.LoadingDataEventArgs e) => e.Query = context.GetCitiesQuery().Where(c => c.StateName == "WA");
                this._dds.Load();
            });

            this.AssertLoadingData();

            EnqueueCallback(() =>
            {
                Assert.AreEqual(6, this._view.Count);
            });

            EnqueueTestComplete();
        }
        public void Inherit_Run_CUD_Insert_Derived()
        {
            // Inheritance is City <-- CityWithEditHistory <-- CityWithInfo
            CityDomainContext citiesContext= new CityDomainContext(TestURIs.Cities);
            DateTime priorLastUpdated = DateTime.Now;

            // Load all cities, not just derived ones
            LoadOperation lo = citiesContext.Load(citiesContext.GetCitiesQuery());
            SubmitOperation so = null;

            // wait for Load to complete
            EnqueueConditional(() => lo.IsComplete);

            EnqueueCallback(delegate
            {

                CityWithInfo newCity = new CityWithInfo() { Name = "CocoaVille", StateName = "WA", CountyName = "King", Info="stuff" };
                citiesContext.Cities.Add(newCity);

                so = citiesContext.SubmitChanges();
            });
            // wait for submit to complete
            EnqueueConditional(() => so.IsComplete);
            EnqueueCallback(delegate
            {
                if (so.Error != null)
                {
                    Assert.Fail("Unexpected error on submit: " + so.Error.Message);
                }

                // verify entities are auto-synced back to the client as a result of the domain method execution on server
                CityWithInfo newCity = citiesContext.Cities.OfType<CityWithInfo>().SingleOrDefault<CityWithInfo>(c => (c.Name == "CocoaVille"));
                Assert.IsNotNull(newCity, "Did not find modified City after the submit");
                Assert.IsTrue(newCity.EditHistory.Contains("insert"), "EditHistory was" + newCity.EditHistory);
            });

            EnqueueTestComplete();
        }