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);

            this.EnqueueCompletion(() => lo);

            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();
        }
Esempio n. 2
0
        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();
        }
Esempio n. 3
0
        public void Query_MaximumUriLengthExceeded()
        {
            Thread.CurrentThread.CurrentCulture = new CultureInfo("tr-TR");
            CityDomainContext dc = new CityDomainContext(GenerateUriBase(1000)); // --> the length when localized to Turkish is > 2083

            ExceptionHelper.ExpectException <InvalidOperationException>(() => dc.Load(dc.GetCitiesQuery()),
                                                                        String.Format(SSmDsWeb::OpenRiaServices.DomainServices.Client.Resource.WebDomainClient_MaximumUriLengthExceeded, 2083));
        }
Esempio n. 4
0
        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 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
            this.EnqueueCompletion(() => so);
            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 DomainContext_Submit_CUDOperationMethodValidation()
        {
            CityDomainContext ctxt = new CityDomainContext(TestURIs.Cities);

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

            this.EnqueueCompletion(() => lo);
            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);
            });
            this.EnqueueCompletion(() => so);
            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 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_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(14, 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(2, 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();
        }
Esempio n. 9
0
 public async Task <LoadResult <OpenRiaServices.Client.Benchmarks.Client.Cities.City> > GetCititesReuseContext()
 {
     return(await _ctx.LoadAsync(_ctx.GetCitiesQuery()).ConfigureAwait(false));
 }
Esempio n. 10
0
        public async Task <LoadResult <OpenRiaServices.Client.Benchmarks.Client.Cities.City> > GetCititesUniqueContext()
        {
            CityDomainContext ctx = new CityDomainContext(_clientUri);

            return(await ctx.LoadAsync(ctx.GetCitiesQuery()).ConfigureAwait(false));
        }
Esempio n. 11
0
        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!");
            };

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

            // verify completion callbacks that throw
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                try
                {
                    lo.Complete(new LoadResult <City>(query, loadBehaviour, Array.Empty <City>(), Array.Empty <Entity>(), 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, true);
            lo.CancellationToken.Register(() => throw new InvalidOperationException("Fnord!"));
            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, true);

            io.CancellationToken.Register(() => throw new InvalidOperationException("Fnord!"));
            ExceptionHelper.ExpectInvalidOperationException(delegate
            {
                io.Cancel();
            }, "Fnord!");
        }