Beispiel #1
0
        public void DollarValueFailsOpenTypes()
        {
            DSPUnitTestServiceDefinition roadTripServiceDefinition    = GetRoadTripServiceDefinition(typeof(GeographyPoint), TestPoint.DefaultValues, false, true);
            Action <TestWebRequest>      sendRequestAndAssertBehavior = (req) =>
            {
                if (req.HttpMethod == "GET")
                {
                    //WebException e = TestUtil.RunCatching<WebException>(() => req.SendRequest());
                    //TestUtil.AssertExceptionStatusCode(e, 400, "get can't be serialized, will be an instream error");
                    req.SendRequest();
                    Assert.AreEqual(200, req.ResponseStatusCode);
                }
                else if (req.HttpMethod == "POST")
                {
                    WebException e = TestUtil.RunCatching <WebException>(() => req.SendRequest());
                    TestUtil.AssertExceptionStatusCode(e, 400, "get can't be serialized, will be an instream error");
                }
                else
                {
                    // PUT/PATCH/DELETE
                    req.SendRequest();
                    Assert.AreEqual(204, req.ResponseStatusCode);
                }
            };

            DollarValueGivesErrorForAllVerbs(roadTripServiceDefinition, sendRequestAndAssertBehavior);
        }
        public void OpenSpatialProperties()
        {
            // Verify that the client round tripping works with spatial open properties
            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(
                typeof(GeographyPoint),
                TestPoint.DefaultValues,
                false, // useComplexType
                true,  // useOpenType
                null);

            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcessWcf())
            {
                request.StartService();

                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                //context.EnableAtom = true;
                //context.Format.UseAtom();

                // Query the top level set
                List <TripLeg <Geography> > results = context.CreateQuery <TripLeg <Geography> >("TripLegs").ToList();
                Assert.IsTrue(results.Count == 1, "one trip leg should get materialized");
                Assert.IsTrue(context.Entities.Count == 1, "One trip leg instance should get populated in the context");

                // Update the property value
                results[0].GeographyProperty1 = GeographyFactory.Point(22, 45);
                context.UpdateObject(results[0]);
                context.SaveChanges();

                var data = roadTripServiceDefinition.CurrentDataSource.GetResourceSetEntities("TripLegs");
                Assert.AreEqual(1, data.Count, "there should one instance of TripLeg in the set");
                GeographyPoint point = (GeographyPoint)((DSPResource)data[0]).GetOpenPropertyValue("GeographyProperty1");
                Assert.AreEqual(45, point.Longitude, "Make sure longitude value is updated");
                Assert.AreEqual(22, point.Latitude, "Make sure latitude value is updated");
            }
        }
Beispiel #3
0
        public void DollarValueFailsClosedTypes()
        {
            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(typeof(GeographyPoint), TestPoint.DefaultValues);
            Action <TestWebRequest>      sendRequestAndAssertError = (req) =>
            {
                // we only support $value for spatial type for GET and DELETE now.
                if (req.HttpMethod == "GET")
                {
                    req.SendRequest();
                    Assert.AreEqual(200, req.ResponseStatusCode);
                }
                else if (req.HttpMethod == "POST")
                {
                    WebException e = TestUtil.RunCatching <WebException>(() => req.SendRequest());
                    TestUtil.AssertExceptionStatusCode(e, 405, "get can't be serialized, will be an instream error");
                }
                else if (req.HttpMethod == "DELETE")
                {
                    req.SendRequest();
                    Assert.AreEqual(204, req.ResponseStatusCode);
                }
                else
                {
                    WebException e = TestUtil.RunCatching <WebException>(() => req.SendRequest());
                    TestUtil.AssertExceptionStatusCode(e, 400, "get can't be serialized, will be an instream error");
                }
            };

            DollarValueGivesErrorForAllVerbs(roadTripServiceDefinition, sendRequestAndAssertError);
        }
Beispiel #4
0
        public void TestCollectionOfSpatialTypes()
        {
            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(typeof(GeographyPoint), TestPoint.DefaultValues, false, false,
                                                                                                  (m) =>
            {
                var resourceType  = m.GetResourceType("TripLeg");
                var primitiveType = Microsoft.OData.Service.Providers.ResourceType.GetPrimitiveResourceType(typeof(GeographyPoint));
                m.AddCollectionProperty(resourceType, "PointsOfInterest", primitiveType);
            },
                                                                                                  (name, values) =>
            {
                if (name == "TripLeg")
                {
                    var list = values.Select(kvp => kvp.Value).ToList();
                    values.Add(new KeyValuePair <string, object>("PointsOfInterest", list));
                }
            });

            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcessWcf())
            {
                request.StartService();

                DataServiceContext context = new DataServiceContext(request.ServiceRoot, ODataProtocolVersion.V4);
                context.EnableAtom = true;
                context.Format.UseAtom();
                var tripLegs = context.CreateQuery <TripLegWithCollection <GeographyPoint> >("TripLegs").Where(t => t.ID == SpatialTestUtil.DefaultId).ToList();
                var tripLeg  = tripLegs.Single();
                Assert.AreEqual(2, tripLeg.PointsOfInterest.Count(), "didn't materialize all the elements");
            }
        }
Beispiel #5
0
        internal static DSPUnitTestServiceDefinition CreateRoadTripServiceDefinition(DSPMetadata roadTripMetadata, GeographyPropertyValues defaultValues, DSPDataProviderKind providerKind, bool useComplexType = false, Action <string, List <KeyValuePair <string, object> > > modifyPropertyValues = null)
        {
            Assert.IsFalse(useComplexType, "Complex type support is not yet added to the property population in DSPUnitTestServiceDefinition.");

            DSPContext defaultData = PopulateRoadTripData(roadTripMetadata, defaultValues, useComplexType, modifyPropertyValues);

            var service = new DSPUnitTestServiceDefinition(roadTripMetadata, providerKind, defaultData);

            service.HostInterfaceType = typeof(IDataServiceHost2);
            service.DataServiceBehavior.AcceptSpatialLiteralsInQuery = true;
            service.Writable = true;
            service.DataServiceBehavior.MaxProtocolVersion = ODataProtocolVersion.V4;

            return(service);
        }
Beispiel #6
0
        public void AllowRedefiningConcurrencyTokenOnDerivedType()
        {
            var metadataProvider = new DSPMetadata("DefaultContainer", "Default");

            var entityType = metadataProvider.AddEntityType("EntityType", null, null, false /*isAbstract*/);

            metadataProvider.AddKeyProperty(entityType, "ID", typeof(int));
            metadataProvider.AddPrimitiveProperty(entityType, "LastUpdatedAuthor", typeof(string), true /*eTag*/);

            var derivedType = metadataProvider.AddEntityType("DerivedType", null, entityType, false /*isAbstract*/);

            metadataProvider.AddPrimitiveProperty(derivedType, "LastModifiedAuthor", typeof(string), true /*eTag*/);

            metadataProvider.AddResourceSet("Customers", entityType);

            var wrapper = new DataServiceMetadataProviderWrapper(metadataProvider);

            DSPResource baseTypeInstance = new DSPResource(entityType);

            baseTypeInstance.SetValue("ID", 1);
            baseTypeInstance.SetValue("LastUpdatedAuthor", "Phani");

            DSPResource derivedTypeInstance = new DSPResource(derivedType);

            derivedTypeInstance.SetValue("ID", 1);
            derivedTypeInstance.SetValue("LastModifiedAuthor", "Raj");

            DSPContext dataContext = new DSPContext();
            var        entities    = dataContext.GetResourceSetEntities("Customers");

            entities.AddRange(new object[] { baseTypeInstance, derivedTypeInstance });

            var service = new DSPUnitTestServiceDefinition(metadataProvider, DSPDataProviderKind.Reflection, dataContext);

            using (TestWebRequest request = service.CreateForInProcess())
            {
                try
                {
                    request.StartService();
                    request.RequestUriString = "/$metadata";
                    request.SendRequestAndCheckResponse();
                }
                finally
                {
                    request.StopService();
                }
            }
        }
Beispiel #7
0
        private static void TestSpatialMetadata(DSPDataProviderKind providerKind)
        {
            DSPMetadata metadata = new DSPMetadata("SpatialMetadata", "AstoriaUnitTests.Tests");

            // Entity with all types of geography properties
            KeyValuePair <string, Type>[] geographyProperties = new KeyValuePair <string, Type>[] {
                new KeyValuePair <string, Type>("GeographyProperty", typeof(Geography)),
                new KeyValuePair <string, Type>("PointProperty", typeof(GeographyPoint)),
                new KeyValuePair <string, Type>("LineStringProperty", typeof(GeographyLineString)),
            };
            string entityTypeName = "AllGeographyTypes";

            SpatialTestUtil.AddEntityType(metadata, entityTypeName, geographyProperties, useComplexType: false, useOpenTypes: false);
            metadata.SetReadOnly();

            var service = new DSPUnitTestServiceDefinition(metadata, providerKind, new DSPContext());

            using (TestWebRequest request = service.CreateForInProcess())
            {
                request.StartService();

                request.HttpMethod = "GET";
                XDocument response = UnitTestsUtil.GetResponseAsAtomXLinq(request, "/$metadata");

                XElement   schemaElement = response.Root.Element(UnitTestsUtil.EdmxNamespace + "DataServices").Elements().Single(e => e.Name.LocalName == "Schema");
                XNamespace edmNs         = schemaElement.Name.Namespace;
                XElement   entityElement = schemaElement.Elements(edmNs + "EntityType").Single(e => (string)e.Attribute("Name") == entityTypeName);

                foreach (KeyValuePair <string, Type> property in geographyProperties)
                {
                    XElement propertyElement = entityElement.Elements(edmNs + "Property").Single(e => (string)e.Attribute("Name") == property.Key);

                    // EF provider currently represents all types as Edm.Geography in metadata (property is DbGeography on the entity), otherwise it should reflect the actual type
                    string expectedEdmTypeName = providerKind == DSPDataProviderKind.EF ? "Edm.Geography" : GetExpectedEdmTypeName(property.Value);

                    Assert.AreEqual(expectedEdmTypeName, propertyElement.Attribute("Type").Value, "Wrong property type for property {0},", property.Key);

                    XAttribute attribute = propertyElement.Attributes().Where(a => a.Name == "SRID").Single();
                    Assert.AreEqual("Variable", attribute.Value);
                }
            }
        }
Beispiel #8
0
        public void SerializeGeodeticPropertiesInResource()
        {
            var testCases = new[]
            {
                new
                {
                    GeographyType = typeof(GeographyPoint),
                    DefaultValues = TestPoint.DefaultValues
                },
                new
                {
                    GeographyType = typeof(GeographyLineString),
                    DefaultValues = TestLineString.DefaultValues
                },
            };

            var responseFromats = new string[] { UnitTestsUtil.AtomFormat };

            TestUtil.RunCombinations(testCases, responseFromats, (testCase, responseFormat) =>
            {
                GeographyPropertyValues defaultValues = testCase.DefaultValues;

                DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(testCase.GeographyType, defaultValues);
                using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
                {
                    request.StartService();
                    request.Accept = responseFormat;

                    ResourceVerification verification = GetResourceVerification(responseFormat, SpatialTestUtil.DefaultId, defaultValues, request);

                    // Geography property followed by another geography property
                    verification.GetAndVerifyTripLeg();

                    // Geography property followed by another non-geography property
                    verification.GetAndVerifyAmusementPark();

                    // Geography property at the end of the entry
                    verification.GetAndVerifyRestStop();
                }
            });
        }
Beispiel #9
0
        public void DollarValueGivesErrorForAllVerbs(DSPUnitTestServiceDefinition roadTripServiceDefinition, Action <TestWebRequest> sendRequestAndAssertBehavior)
        {
            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
            {
                request.StartService();


                // GET
                request.Accept             = UnitTestsUtil.MimeTextPlain;
                request.RequestContentType = null;
                request.HttpMethod         = "GET";
                request.RequestUriString   = string.Format("/TripLegs({0})/GeographyProperty1/$value", SpatialTestUtil.DefaultId);
                sendRequestAndAssertBehavior(request);

                // PUT
                request.HttpMethod         = "PUT";
                request.RequestContentType = UnitTestsUtil.MimeTextPlain;
                request.RequestUriString   = string.Format("/TripLegs({0})/GeographyProperty1/$value", SpatialTestUtil.DefaultId);
                string newValue = GmlFormatter.Create().Write(TestPoint.NewValues.TripLegGeography1.AsGeography());
                request.RequestStream = IOUtil.CreateStream(newValue);
                sendRequestAndAssertBehavior(request);

                // POST
                request.HttpMethod = "POST";
                sendRequestAndAssertBehavior(request);

                // PATCH
                request.HttpMethod = "PATCH";
                sendRequestAndAssertBehavior(request);

                // DELETE
                request.HttpMethod = "DELETE";
                string uri = string.Format("/TripLegs({0})/GeographyProperty1/$value", SpatialTestUtil.DefaultId);
                request.RequestUriString = uri;
                sendRequestAndAssertBehavior(request);
            }
        }
Beispiel #10
0
        public static void ClassInitialize(TestContext context)
        {
            DSPDataProviderKind providerKind = DSPDataProviderKind.EF;

            // set up the service
            DSPMetadata metadata    = GetModel(false /*openType*/, false /*namedStreams*/);
            DSPContext  defaultData = GetDefaultData(metadata);

            DSPUnitTestServiceDefinition.ModifyGeneratedCode = (currentCode) =>
            {
                // Add namespace which includes Code First Attributes
                currentCode.Insert(currentCode.ToString().IndexOf("public class PeopleType"), "using System.ComponentModel.DataAnnotations;\n\n");

                // Add the required attributes
                currentCode.Insert(currentCode.ToString().IndexOf("public string Name { get; set; }"), "[Required()]\n");
                currentCode.Insert(currentCode.ToString().IndexOf("public byte[] Body { get; set; }"), "[Required()]\n");
                currentCode.Insert(currentCode.ToString().IndexOf("public int? Age { get; set; }"), "[Required()]\n");

                return(currentCode);
            };

            service          = new DSPUnitTestServiceDefinition(metadata, providerKind, defaultData);
            service.Writable = true;
        }
Beispiel #11
0
        private DSPUnitTestServiceDefinition CreateTestService(bool openType = false)
        {
            DSPMetadata metadata   = new DSPMetadata("SpatialQueryTests", "AstoriaUnitTests.Tests");
            var         entityType = metadata.AddEntityType("SpatialEntity", null, null, false);

            metadata.AddKeyProperty(entityType, "ID", typeof(int));
            entityType.IsOpenType = openType;

            if (!openType)
            {
                metadata.AddPrimitiveProperty(entityType, "Geography", typeof(Geography));
                metadata.AddPrimitiveProperty(entityType, "Point", typeof(GeographyPoint));
                metadata.AddPrimitiveProperty(entityType, "Point2", typeof(GeographyPoint));
                metadata.AddPrimitiveProperty(entityType, "LineString", typeof(GeographyLineString));
                metadata.AddPrimitiveProperty(entityType, "Polygon", typeof(GeographyPolygon));
                metadata.AddPrimitiveProperty(entityType, "GeographyCollection", typeof(GeographyCollection));
                metadata.AddPrimitiveProperty(entityType, "MultiPoint", typeof(GeographyMultiPoint));
                metadata.AddPrimitiveProperty(entityType, "MultiLineString", typeof(GeographyMultiLineString));
                metadata.AddPrimitiveProperty(entityType, "MultiPolygon", typeof(GeographyMultiPolygon));

                metadata.AddPrimitiveProperty(entityType, "Geometry", typeof(Geometry));
                metadata.AddPrimitiveProperty(entityType, "GeometryPoint", typeof(GeometryPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryPoint2", typeof(GeometryPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryLineString", typeof(GeometryLineString));
                metadata.AddPrimitiveProperty(entityType, "GeometryPolygon", typeof(GeometryPolygon));
                metadata.AddPrimitiveProperty(entityType, "GeometryCollection", typeof(GeometryCollection));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiPoint", typeof(GeometryMultiPoint));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiLineString", typeof(GeometryMultiLineString));
                metadata.AddPrimitiveProperty(entityType, "GeometryMultiPolygon", typeof(GeometryMultiPolygon));
            }

            metadata.AddCollectionProperty(entityType, "CollectionOfPoints", typeof(GeographyPoint));
            metadata.AddCollectionProperty(entityType, "GeometryCollectionOfPoints", typeof(GeometryPoint));
            metadata.AddPrimitiveProperty(entityType, "GeographyNull", typeof(Geography));
            metadata.AddPrimitiveProperty(entityType, "GeometryNull", typeof(Geometry));

            metadata.AddResourceSet("Spatials", entityType);

            metadata.SetReadOnly();

            DSPContext context = new DSPContext();
            var        set     = context.GetResourceSetEntities("Spatials");

            for (int i = 0; i < 3; ++i)
            {
                DSPResource spatialEntity = new DSPResource(entityType);
                spatialEntity.SetValue("ID", i);
                spatialEntity.SetValue("Geography", GeographyFactory.Point(32.0 - i, -100.0).Build());
                spatialEntity.SetValue("Point", GeographyFactory.Point(33.1 - i, -110.0).Build());
                spatialEntity.SetValue("Point2", GeographyFactory.Point(32.1 - i, -110.0).Build());
                spatialEntity.SetValue("LineString", GeographyFactory.LineString(33.1 - i, -110.0).LineTo(35.97 - i, -110).Build());
                spatialEntity.SetValue("Polygon", GeographyFactory.Polygon().Ring(33.1 - i, -110.0).LineTo(35.97 - i, -110.15).LineTo(11.45 - i, 87.75).Ring(35.97 - i, -110).LineTo(36.97 - i, -110.15).LineTo(45.23 - i, 23.18).Build());
                spatialEntity.SetValue("GeographyCollection", GeographyFactory.Collection().Point(-19.99 - i, -12.0).Build());
                spatialEntity.SetValue("MultiPoint", GeographyFactory.MultiPoint().Point(10.2 - i, 11.2).Point(11.9 - i, 11.6).Build());
                spatialEntity.SetValue("MultiLineString", GeographyFactory.MultiLineString().LineString(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineString(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).Build());
                spatialEntity.SetValue("MultiPolygon", GeographyFactory.MultiPolygon().Polygon().Ring(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineTo(11.45 - i, 87.75).Ring(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).LineTo(11.45 - i, 87.75).Build());
                spatialEntity.SetValue("CollectionOfPoints", new List <GeographyPoint>()
                {
                    GeographyFactory.Point(10.2, 99.5),
                    GeographyFactory.Point(11.2, 100.5)
                });

                spatialEntity.SetValue("Geometry", GeometryFactory.Point(32.0 - i, -10.0).Build());
                spatialEntity.SetValue("GeometryPoint", GeometryFactory.Point(33.1 - i, -11.0).Build());
                spatialEntity.SetValue("GeometryPoint2", GeometryFactory.Point(32.1 - i, -11.0).Build());
                spatialEntity.SetValue("GeometryLineString", GeometryFactory.LineString(33.1 - i, -11.5).LineTo(35.97 - i, -11).Build());
                spatialEntity.SetValue("GeometryPolygon", GeometryFactory.Polygon().Ring(33.1 - i, -13.6).LineTo(35.97 - i, -11.15).LineTo(11.45 - i, 87.75).Ring(35.97 - i, -11).LineTo(36.97 - i, -11.15).LineTo(45.23 - i, 23.18).Build());
                spatialEntity.SetValue("GeometryCollection", GeometryFactory.Collection().Point(-19.99 - i, -12.0).Build());
                spatialEntity.SetValue("GeometryMultiPoint", GeometryFactory.MultiPoint().Point(10.2 - i, 11.2).Point(11.9 - i, 11.6).Build());
                spatialEntity.SetValue("GeometryMultiLineString", GeometryFactory.MultiLineString().LineString(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineString(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).Build());
                spatialEntity.SetValue("GeometryMultiPolygon", GeometryFactory.MultiPolygon().Polygon().Ring(10.2 - i, 11.2).LineTo(11.9 - i, 11.6).LineTo(11.45 - i, 87.75).Ring(16.2 - i, 17.2).LineTo(18.9 - i, 19.6).LineTo(11.45 - i, 87.75).Build());
                spatialEntity.SetValue("GeometryCollectionOfPoints", new List <GeometryPoint>()
                {
                    GeometryFactory.Point(10.2, 99.5),
                    GeometryFactory.Point(11.2, 100.5)
                });

                spatialEntity.SetValue("GeographyNull", null);
                spatialEntity.SetValue("GeometryNull", null);

                set.Add(spatialEntity);
            }

            var service = new DSPUnitTestServiceDefinition(metadata, DSPDataProviderKind.CustomProvider, context);

            service.DataServiceBehavior.AcceptSpatialLiteralsInQuery = true;
            service.Writable = true;

            return(service);
        }
Beispiel #12
0
        public void TestEqualityHandling()
        {
            string geographyLiteral = GetUriLiteral(typeof(GeographyPoint),
                                                    TestPoint.DefaultValues.TripLegGeography1.AsGeography());
            string geometryLiteral = GetUriLiteral(typeof(GeometryPoint),
                                                   TestPoint.DefaultValues.TripLegGeography1.AsGeography());
            var testCases = new[]
            {
                new
                {
                    Type         = typeof(GeographyPoint),
                    Left         = "GeographyProperty1",
                    Right        = geographyLiteral,
                    Operator     = "eq",
                    OperatorName = "Equal"
                },
                new
                {
                    Type         = typeof(GeographyPoint),
                    Left         = geographyLiteral,
                    Right        = "GeographyProperty1",
                    Operator     = "eq",
                    OperatorName = "Equal"
                },
                new
                {
                    Type         = typeof(GeometryPoint),
                    Left         = "GeographyProperty1",
                    Right        = geometryLiteral,
                    Operator     = "eq",
                    OperatorName = "Equal"
                },
                new
                {
                    Type         = typeof(GeometryPoint),
                    Left         = geometryLiteral,
                    Right        = "GeographyProperty1",
                    Operator     = "eq",
                    OperatorName = "Equal"
                },
            };

            TestUtil.RunCombinations(testCases,
                                     (testCase) =>
            {
                DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(testCase.Type, TestPoint.DefaultValues);
                using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
                {
                    request.StartService();
                    // GET
                    request.Accept             = UnitTestsUtil.MimeAny;
                    request.RequestContentType = null;
                    request.HttpMethod         = "GET";
                    request.RequestUriString   = string.Format("/TripLegs/?$filter={0} {1} {2}", testCase.Left, testCase.Operator, testCase.Right);
                    int operatorPos            = testCase.Left.Length + 1;
                    WebException e             = TestUtil.RunCatching <WebException>(() => request.SendRequest());
                    Assert.IsNotNull(e, "didn't get the exception we should have gotten");
                    string expectedMessage = ODataLibResourceUtil.GetString(
                        "MetadataBinder_IncompatibleOperandsError",
                        "Edm." + testCase.Type.Name,
                        "Edm." + testCase.Type.Name,
                        testCase.OperatorName,
                        operatorPos);
                    Assert.AreEqual(expectedMessage, e.InnerException.Message, "didn't get the correct error");
                }
            });
        }
Beispiel #13
0
        public void InsertAndUpdateGeodeticProperties()
        {
            var testCases = new[]
            {
                new
                {
                    GeographyType = typeof(Geography),
                    DefaultValues = TestLineString.DefaultValues,
                    NewValues     = TestLineString.NewValues,
                },
                new
                {
                    GeographyType = typeof(GeographyPoint),
                    DefaultValues = TestPoint.DefaultValues,
                    NewValues     = TestPoint.NewValues,
                },
                new
                {
                    GeographyType = typeof(GeographyLineString),
                    DefaultValues = TestLineString.DefaultValues,
                    NewValues     = TestLineString.NewValues,
                },
            };

            TestUtil.RunCombinations(testCases, UnitTestsUtil.BooleanValues, UnitTestsUtil.ResponseFormats, (testCase, enableTypeConversion, payloadFormat) =>
            {
                GeographyPropertyValues defaultValues = testCase.DefaultValues;
                bool useComplexType = false;
                DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(testCase.GeographyType, defaultValues, useComplexType);

                // EnableTypeConversion is interesting here because it affects whether or not we pay attention to the type that's specified on the wire, instead of metadata
                // Since spatial types can specify Geography in metadata but GeographyPoint as the value, we need to verify it works either way
                roadTripServiceDefinition.EnableTypeConversion = enableTypeConversion;

                using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
                {
                    request.StartService();

                    TestUtil.RunCombinations(
                        new string[] { "POST", "PUT", "PATCH", "PATCH" },
                        new string[] { null, "return=representation", "return=minimal" },
                        UnitTestsUtil.BooleanValues,
                        (httpMethod, preferHeader, useBatch) =>
                    {
                        bool isPost = httpMethod == "POST";
                        bool expectedReturnContent = preferHeader == "return=representation" || isPost && preferHeader == null;

                        DSPMetadata roadTripMetadata = roadTripServiceDefinition.Metadata;
                        DSPContext changeScopeData   = SpatialTestUtil.PopulateRoadTripData(roadTripMetadata, defaultValues, useComplexType);
                        using (IDisposable changeScope = roadTripServiceDefinition.CreateChangeScope(changeScopeData))
                        {
                            int id = isPost ? 2 : SpatialTestUtil.DefaultId;

                            ResourceVerification verification = GetResourceVerification(payloadFormat, id, testCase.NewValues, request);

                            TestTripLegUpdate(verification, httpMethod, preferHeader, useBatch, roadTripMetadata);
                            TestAmusementParkUpdate(verification, httpMethod, preferHeader, useBatch, roadTripMetadata);
                            TestRestStopUpdate(verification, httpMethod, preferHeader, useBatch, roadTripMetadata);
                        }
                    });
                }
            });
        }
Beispiel #14
0
        public void TestServiceOperationsWithSpatialParameters()
        {
            Action <string, Type, DSPMetadata> AddIdentityServiceOp = (name, type, dspMetadata) =>
            {
                var primitiveType = Microsoft.OData.Service.Providers.ResourceType.GetPrimitiveResourceType(type);
                var parameter     = new ServiceOperationParameter("param1", primitiveType);
                dspMetadata.AddServiceOperation(name, ServiceOperationResultKind.DirectValue, primitiveType, null, "GET",
                                                new ServiceOperationParameter[] { parameter });
            };

            DSPUnitTestServiceDefinition roadTripServiceDefinition = GetRoadTripServiceDefinition(typeof(GeographyPoint), TestPoint.DefaultValues, false, false,
                                                                                                  (m) =>
            {
                AddIdentityServiceOp("GetGeographyPoint", typeof(GeographyPoint), m);
                AddIdentityServiceOp("GetGeometryPoint", typeof(GeometryPoint), m);
                AddIdentityServiceOp("GetDouble", typeof(double), m);
            });


            Func <object[], object> sopCallBack = (args) =>
            {
                return(args[0]);
            };

            roadTripServiceDefinition.CreateDataSource = (metadata) =>
            {
                return(new DSPContext()
                {
                    ServiceOperations =
                        new Dictionary
                        <string, Func <object[], object> >()
                    {
                        { "GetGeographyPoint", sopCallBack },
                        { "GetGeometryPoint", sopCallBack },
                        { "GetDouble", sopCallBack },
                    }
                });
            };

            using (TestWebRequest request = roadTripServiceDefinition.CreateForInProcess())
            {
                request.StartService();

                // GET
                request.Accept             = "application/xml";
                request.RequestContentType = null;
                request.HttpMethod         = "GET";
                request.RequestUriString   = "/GetDouble?param1=1.2";
                request.SendRequest();
                var response = request.GetResponseStreamAsText();
                StringAssert.Contains(response, "1.2", "didn't get the identity back");

                const string wellKnownText = "SRID=4326;POINT (177.508 51.9917)";

                // GET
                request.Accept = "application/xml";

                request.RequestContentType = null;
                request.HttpMethod         = "GET";
                request.RequestUriString   = string.Format("/GetGeographyPoint?param1=geography'{0}'", wellKnownText);
                request.SendRequest();
                response = request.GetResponseStreamAsText();
                var    geographyPoint       = WellKnownTextSqlFormatter.Create().Read <Geography>(new StringReader(wellKnownText));
                string geographyPointReturn = GmlFormatter.Create().Write(geographyPoint);
                // The gml namespace is already declared on the top-level element
                geographyPointReturn = geographyPointReturn.Replace(" xmlns:gml=\"http://www.opengis.net/gml\"", string.Empty);
                StringAssert.Contains(response, geographyPointReturn, "didn't get the identity back");

                // GET
                request.Accept             = "application/xml";
                request.RequestContentType = null;
                request.HttpMethod         = "GET";
                request.RequestUriString   = string.Format("/GetGeometryPoint?param1=geometry'{0}'", wellKnownText);
                request.SendRequest();
                response = request.GetResponseStreamAsText();
                var    geometryPoint       = WellKnownTextSqlFormatter.Create().Read <Geometry>(new StringReader(wellKnownText));
                string geometryPointReturn = GmlFormatter.Create().Write(geometryPoint);
                // The gml namespace is already declared on the top-level element
                geometryPointReturn = geometryPointReturn.Replace(" xmlns:gml=\"http://www.opengis.net/gml\"", string.Empty);
                StringAssert.Contains(response, geometryPointReturn, "didn't get the identity back");
            }
        }