public SpatialFormatterRoundTripTests() { this.jsonFormatter = GeoJsonObjectFormatter.Create(); this.gmlFormatter = GmlFormatter.Create(); this.wktFormatter = WellKnownTextSqlFormatter.Create(); this.jsonDictionaryFormatter = GeoJsonObjectFormatter.Create(); }
public object TokenizeFromXml(XmlReader reader) { reader.ReadStartElement(); Geography geography = GmlFormatter.Create().Read <Geography>(reader); reader.SkipInsignificantNodes(); return(geography); }
/// <summary> /// Convert GeoJson to GML /// </summary> /// <param name="source">GeoJson Dictionary</param> /// <param name="target">XmlWriter that outputs Gml</param> private static void GeoJsonToGml(Dictionary <string, object> source, XmlWriter target) { GeoJsonObjectFormatter sourceFormatter = GeoJsonObjectFormatter.Create(); GmlFormatter targetFormatter = GmlFormatter.Create(); var converted = ConvertFromDispatch(source); sourceFormatter.Read <Geography>(converted).SendTo(targetFormatter.CreateWriter(target)); }
/// <summary> /// Create an instance of primitive type from the xml reader /// </summary> /// <param name="reader">The xml reader</param> /// <remarks>The reader is expected to be placed at the beginning of the element, and after this method call, the reader will be placed /// at the EndElement, such that the next Element will be read in the next Read call.</remarks> /// <returns>An instance of primitive type</returns> internal override PrimitiveParserToken TokenizeFromXml(XmlReader reader) { Debug.Assert(reader.NodeType == XmlNodeType.Element, "reader at element"); reader.ReadStartElement(); // <d:Property> var g = new InstancePrimitiveParserToken <Geometry>(GmlFormatter.Create().Read <Geometry>(reader)); Debug.Assert(reader.NodeType == XmlNodeType.EndElement, "reader at end of current element"); return(g); }
/// <summary> /// Create a geography instance from the value in an Xml reader. /// </summary> /// <param name="reader">The Xml reader to use to read the value.</param> /// <remarks>In order to be consistent with how we are reading other types of property values elsewhere in the product, the reader /// is expected to be placed at the beginning of the element when entering this method. After this method call, the reader will be placed /// at the EndElement, such that the next Element will be read in the next Read call. The deserializer that uses this value expects /// the reader to be in these states when entering and leaving the method. /// </remarks> /// <returns>Geography instance that was read.</returns> public object TokenizeFromXml(XmlReader reader) { Debug.Assert(reader.NodeType == XmlNodeType.Element, "reader at element"); reader.ReadStartElement(); // <d:Property> Geography geography = GmlFormatter.Create().Read <Geography>(reader); reader.SkipInsignificantNodes(); Debug.Assert(reader.NodeType == XmlNodeType.EndElement, "reader at end of current element"); return(geography); }
public Geography GeographyFromGml(string gml) { try { GmlFormatter gmlFormatter = GmlFormatter.Create(); TextReader reader = new StringReader(gml); var r = XmlReader.Create(reader); return(gmlFormatter.Read <Geography>(r)); } catch { return(null); } }
public string GeographyToGmlV3(Geography geography) { try { GmlFormatter gmlFormatter = GmlFormatter.Create(); var result = gmlFormatter.Write(geography); result = result.Replace(@"gml:srsName=""http://www.opengis.net/def/crs/EPSG/0/4326""", ""); return(result); } catch { return(null); } }
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); } }
/// <summary> /// Converts a spatial value into a string representation suitable for the specified format. If specified, injects a type name into the JSON format(s). /// </summary> /// <param name="format">The format to create the spatial value string representation for.</param> /// <param name="spatial">The spatial value.</param> /// <param name="typeName">The (optional) type name to inject into a JSON string representation.</param> /// <returns>The string representation of the spatial value in the specified format.</returns> /// <remarks>When using a type name with the JSON Light format, the resulting string representation will be invalid /// (since the odata.type annotation is not supported inside of spatial values); only used for error tests.</remarks> public static string GetSpatialStringValue(ODataFormat format, ISpatial spatial, string typeName = null) { if (format == ODataFormat.Atom) { return(GmlFormatter.Create().Write(spatial)); } IDictionary <string, object> dictionary = GeoJsonObjectFormatter.Create().Write(spatial); var converter = new DictionaryToJsonObjectConverter(); ExceptionUtilities.CheckAllRequiredDependencies(converter); var jsonObject = converter.Convert(dictionary); if (typeName != null) { // NOTE: using a type name with the JSON Light format will produce invalid payloads and is only used // for error tests. jsonObject.Insert(0, new JsonProperty(JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName, new JsonPrimitiveValue(typeName))); } return(jsonObject.ToText(format == ODataFormat.Json, indent: false)); }
private static JsonObject ReadJsonSpatialProperty(XElement container, XElement gmlValue, bool isGeography) { GmlFormatter gmlFormatter = GmlFormatter.Create(); GeoJsonObjectFormatter jsonformatter = GeoJsonObjectFormatter.Create(); bool ignoreCrc = !gmlValue.Attributes().Any(a => a.Name.LocalName == "srsName"); ISpatial spatialValue; if (isGeography) { spatialValue = gmlFormatter.Read <Geography>(gmlValue.CreateReader()); } else { spatialValue = gmlFormatter.Read <Geometry>(gmlValue.CreateReader()); } IDictionary <string, object> geoJsonData = jsonformatter.Write(spatialValue); JsonObject json = new JsonObject(); Queue <object> geoJsonScopes = new Queue <object>(); Queue <object> jsonScopes = new Queue <object>(); geoJsonScopes.Enqueue(geoJsonData); jsonScopes.Enqueue(json); Func <object, object> convertScope = (scope) => { object newScope = scope is List <object> || scope is object[] ? (object)new List <Object>() : scope is IDictionary <string, object>?(object)new JsonObject() : null; if (newScope != null) { geoJsonScopes.Enqueue(scope); jsonScopes.Enqueue(newScope); } return(newScope ?? scope); }; while (jsonScopes.Count > 0) { if (jsonScopes.Peek() is JsonObject) { var currentGeoJson = (IDictionary <string, object>)geoJsonScopes.Dequeue(); var currentJson = (JsonObject)jsonScopes.Dequeue(); foreach (var item in currentGeoJson) { if (!ignoreCrc || item.Key != "crs") { currentJson[item.Key] = convertScope(item.Value); } } } else { var currentGeoJson = (IEnumerable <object>)geoJsonScopes.Dequeue(); var currentJson = (List <object>)jsonScopes.Dequeue(); foreach (var item in currentGeoJson) { currentJson.Add(convertScope(item)); } } } json["__metadata"] = ReaderUtils.CreateEntryPropertyMetadata(GetTypeAttribute(container), false); return(json); }
public void WriteAtom(object instance, XmlWriter writer) { ((Geography)instance).SendTo((GeographyPipeline)GmlFormatter.Create().CreateWriter(writer)); }
internal override PrimitiveParserToken TokenizeFromXml(XmlReader reader) { reader.ReadStartElement(); return(new InstancePrimitiveParserToken <Geometry>(GmlFormatter.Create().Read <Geometry>(reader))); }
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"); } }
/// <summary> /// Create an instance of the spatial formatter to use /// </summary> /// <returns>The spatial format to use</returns> protected override SpatialFormatter <XmlReader, XmlWriter> CreateFormatter() { return(GmlFormatter.Create()); }
/// <summary> /// Write the Atom representation of an instance of a primitive type to an XmlWriter. /// </summary> /// <param name="instance">The instance to write.</param> /// <param name="writer">The Xml writer to use to write the instance.</param> public void WriteAtom(object instance, XmlWriter writer) { ((Geometry)instance).SendTo(GmlFormatter.Create().CreateWriter(writer)); }
public static void ClassInit(TestContext context) { wktFormatter = WellKnownTextSqlFormatter.Create(); jsonFormatter = GeoJsonObjectFormatter.Create(); gmlFormatter = GmlFormatter.Create(); }
private static string GeneratePayload <TServer, TClient>(TServer serverPropertyValue, string contentType, bool complex, bool collection) { if (contentType == UnitTestsUtil.AtomFormat) { const string atomTemplate = @"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?> <entry xml:base=""/"" xmlns:ads=""http://docs.oasis-open.org/odata/ns/data"" xmlns:adsm=""http://docs.oasis-open.org/odata/ns/metadata"" xmlns=""http://www.w3.org/2005/Atom""> <id>http://temp.org/Entities(0)</id> <content type=""application/xml""> <adsm:properties> <ads:ID>0</ads:ID> <ads:Property{0}>{1}</ads:Property> </adsm:properties> </content> </entry>"; string attributes = " adsm:type=\"Edm." + GetPrimitiveTypeKind <TServer>() + "\""; string propertyValue = null; if (serverPropertyValue == null) { attributes += " adsm:null=\"true\""; } else if (typeof(ISpatial).IsAssignableFrom(typeof(TServer))) { var xelement = new XElement("fake"); using (var writer = xelement.CreateWriter()) { GmlFormatter.Create().Write((ISpatial)serverPropertyValue, writer); } propertyValue = xelement.Elements().Single().ToString(); } else { propertyValue = TypeData.XmlValueFromObject(serverPropertyValue).Replace(".0", null); } const string complexTemplate = "<ads:Property{0}>{1}</ads:Property>"; if (complex) { propertyValue = string.Format(complexTemplate, attributes, propertyValue); attributes = null; } const string collectionTemplate = "<adsm:element{0}>{1}</adsm:element>"; if (collection) { propertyValue = string.Format(collectionTemplate, attributes, propertyValue); attributes = null; } return(string.Format(atomTemplate, attributes, propertyValue)); } else { const string jsonTemplate = @"{{ @odata.context:""http://temp.org/$metadata#Fake.Container.Entities/$entity"", ID:0,{0} Property:{1} }}"; string attributes = "\"[email protected]\":\"Edm." + GetPrimitiveTypeKind <TServer>() + "\","; string propertyValue; if (typeof(TServer) == typeof(DateTime)) { propertyValue = '"' + XmlConvert.ToString((DateTime)(object)serverPropertyValue, XmlDateTimeSerializationMode.RoundtripKind) + '"'; } else if (typeof(TServer) == typeof(DateTimeOffset)) { propertyValue = '"' + XmlConvert.ToString((DateTimeOffset)(object)serverPropertyValue) + '"'; } else if (serverPropertyValue == null) { propertyValue = "null"; } else if (typeof(ISpatial).IsAssignableFrom(typeof(TServer))) { var properties = GeoJsonObjectFormatter.Create().Write((ISpatial)serverPropertyValue); StringBuilder builder = new StringBuilder(); AppendGeoJsonProperties(builder, properties); propertyValue = builder.ToString(); } else { propertyValue = JsonPrimitiveTypesUtil.PrimitiveToString(serverPropertyValue, null).Replace(".0", null); } const string complexTemplate = "{{{0}\"Property\":{1}}}"; if (complex) { propertyValue = string.Format(complexTemplate, attributes, propertyValue); attributes = null; } const string collectionTemplate = "[ {0} ]"; if (collection) { propertyValue = string.Format(collectionTemplate, propertyValue); attributes = null; } return(string.Format(jsonTemplate, attributes, propertyValue)); } }