Exemple #1
0
 public SpatialFormatterRoundTripTests()
 {
     this.jsonFormatter           = GeoJsonObjectFormatter.Create();
     this.gmlFormatter            = GmlFormatter.Create();
     this.wktFormatter            = WellKnownTextSqlFormatter.Create();
     this.jsonDictionaryFormatter = GeoJsonObjectFormatter.Create();
 }
        private static void TestSpatialLiteral <T>(T value, string prefix) where T : class, ISpatial
        {
            var result = LiteralFormatter.ForConstants.Format(value);
            var wkt    = WellKnownTextSqlFormatter.Create().Write(value);

            Assert.AreEqual(prefix + "'" + Uri.EscapeDataString(wkt) + "'", result);
        }
 public SpatialFormatterRoundTripTests()
 {
     this.jsonFormatter = GeoJsonObjectFormatter.Create();
     this.gmlFormatter = GmlFormatter.Create();
     this.wktFormatter = WellKnownTextSqlFormatter.Create();
     this.jsonDictionaryFormatter = GeoJsonObjectFormatter.Create();
 }
        public void NullPipelineTest()
        {
            var nullPipelineFormatter = WellKnownTextSqlFormatter.Create(true);
            var point = nullPipelineFormatter.Read <GeometryPoint>(new StringReader("POINT(12345 567890)"));

            Assert.Equal(12345, point.X);
            Assert.Equal(567890, point.Y);
        }
        /// <summary>
        /// Получает строку в формате EWKT из объекта Geography.
        /// </summary>
        /// <param name="geo">Объект Geography.</param>
        /// <returns>Cтрока в формате EWKT.</returns>
        public static string GetEWKT(this Geography geo)
        {
            WellKnownTextSqlFormatter wktFormatter = WellKnownTextSqlFormatter.Create();
            StringWriter wr = new StringWriter();

            wktFormatter.Write(geo, wr);
            return(wr.ToString());
        }
Exemple #6
0
        public string GeographyToWKT <T>(T input)
            where T : class, ISpatial
        {
            var wktFormatter = WellKnownTextSqlFormatter.Create();
            var result       = wktFormatter.Write(input);

            return(result);
        }
Exemple #7
0
        public T GeographyFromWKT <T>(string input)
            where T : class, ISpatial
        {
            var        wktFormatter = WellKnownTextSqlFormatter.Create();
            TextReader reader       = new StringReader(input);
            var        result       = wktFormatter.Read <T>(reader);

            return((T)result);
        }
        private static void GeographyToWktTest(WellKnownTextSqlFormatter formatter, Action <GeographyPipeline> pipelineAction, string expectedWkt)
        {
            var stringWriter = new StringWriter();
            var w            = formatter.CreateWriter(stringWriter);

            w.GeographyPipeline.SetCoordinateSystem(CoordinateSystem.DefaultGeography);
            pipelineAction(w);

            Assert.Equal(expectedWkt, stringWriter.GetStringBuilder().ToString());
        }
Exemple #9
0
        internal static T ParseSpatialLiteral <T>(string literalText, string prefix, WellKnownTextSqlFormatter formatter) where T : class, ISpatial
        {
            string str;

            if (!TryExtractWellKnownTextSqlFromSpatialLiteral(literalText, prefix, out str))
            {
                str = literalText;
            }
            using (StringReader reader = new StringReader(str))
            {
                return(formatter.Read <T>(reader));
            }
        }
Exemple #10
0
        private static bool TryParseSpatialLiteral(Type literalType, string literalText, out object literalValue)
        {
            Geometry geometry;

            if (typeof(Geography).IsAssignableFrom(literalType))
            {
                Geography geography;
                bool      flag = TryParseSpatialLiteral <Geography>(literalText, "geography", WellKnownTextSqlFormatter.Create(), out geography);
                literalValue = geography;
                return(flag);
            }
            bool flag2 = TryParseSpatialLiteral <Geometry>(literalText, "geometry", WellKnownTextSqlFormatter.Create(), out geometry);

            literalValue = geometry;
            return(flag2);
        }
Exemple #11
0
        private static void PopulateRow(Microsoft.OData.Service.IUpdatable updatable, System.Collections.Generic.Dictionary <string, object> resourceLookup)
        {
            resourceLookup.Add("Row0", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.IndexedRow"));
            updatable.SetValue(resourceLookup["Row0"], "Id", new System.Guid("432f0da9-806e-4a2f-b708-dbd1c57a1c21"));
            updatable.SetValue(resourceLookup["Row0"], "Name", "Chris");


            resourceLookup.Add("Row1", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.IndexedRow"));
            updatable.SetValue(resourceLookup["Row1"], "Id", new System.Guid("02d5d465-edb3-4169-9176-89dd7c86535e"));
            updatable.SetValue(resourceLookup["Row1"], "Description", "Excellent");

            resourceLookup.Add("Row2", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.IndexedRow"));
            updatable.SetValue(resourceLookup["Row2"], "Id", new System.Guid("8f59bcb4-1bed-4b91-ab74-44628f57f160"));
            updatable.SetValue(resourceLookup["Row2"], "Count", 1);

            resourceLookup.Add("Row3", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.IndexedRow"));
            updatable.SetValue(resourceLookup["Row3"], "Id", new System.Guid("5dcbef86-a002-4121-8087-f6160fe9a1ed"));
            updatable.SetValue(resourceLookup["Row3"], "Occurred", new DateTimeOffset(2001, 4, 5, 5, 5, 5, 1, new TimeSpan(0, 1, 0)));

            resourceLookup.Add("Row4", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.Row"));
            updatable.SetValue(resourceLookup["Row4"], "Id", new System.Guid("71f7d0dc-ede4-45eb-b421-555a2aa1e58f"));
            updatable.SetValue(resourceLookup["Row4"], "Double", 1.2626d);

            resourceLookup.Add("Row5", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.Row"));
            updatable.SetValue(resourceLookup["Row5"], "Id", new System.Guid("672b8250-1e6e-4785-80cf-b94b572e42b3"));
            updatable.SetValue(resourceLookup["Row5"], "Decimal", new Decimal(1.26d));

            resourceLookup.Add("Row6", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.Row"));
            updatable.SetValue(resourceLookup["Row6"], "Id", new System.Guid("814d505b-6b6a-45a0-9de0-153b16149d56"));
            updatable.SetValue(resourceLookup["Row6"], "Date", new DateTime(1999, 2, 4));

            resourceLookup.Add("Row7", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.Row"));
            updatable.SetValue(resourceLookup["Row7"], "Id", new System.Guid("2e4904b4-00b0-4e37-9f44-b99a6b208dba"));
            updatable.SetValue(resourceLookup["Row7"], "GeomPolygon", WellKnownTextSqlFormatter.Create().Read <GeometryPolygon>(new System.IO.StringReader("SRID=0;POLYGON EMPTY")));

            resourceLookup.Add("Row8", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.Row"));
            updatable.SetValue(resourceLookup["Row8"], "Id", new System.Guid("5a76c54e-4553-4bf6-8592-04cbcbfb1e65"));

            resourceLookup.Add("Row9", updatable.CreateResource("Row", "Microsoft.Test.OData.Services.OpenTypesService.IndexedRow"));
            updatable.SetValue(resourceLookup["Row9"], "Id", new System.Guid("9f9c963b-5c2f-4e39-8bec-b45d19c5dc85"));
        }
        /// <summary>
        /// Tries to parse a spatial literal.
        /// </summary>
        /// <param name="literalType">Type of the literal.</param>
        /// <param name="literalText">The literal text.</param>
        /// <param name="literalValue">The literal value.</param>
        /// <returns>true if the parse was successful, false otherwise</returns>
        internal static bool TryParseSpatialLiteral(Type literalType, string literalText, out object literalValue)
        {
            Debug.Assert(literalType.IsSpatial(), "the passed in type must implement ISpatial");

            var wellKnownTextSqlFormatter = WellKnownTextSqlFormatter.Create(true);

            if (typeof(Geography).IsAssignableFrom(literalType))
            {
                Geography geography;
                var       worked = TryParseSpatialLiteral(literalText, XmlConstants.LiteralPrefixGeography, wellKnownTextSqlFormatter, out geography);
                literalValue = geography;
                return(worked);
            }
            else
            {
                Geometry geometry;
                var      worked = TryParseSpatialLiteral(literalText, XmlConstants.LiteralPrefixGeometry, wellKnownTextSqlFormatter, out geometry);
                literalValue = geometry;
                return(worked);
            }
        }
Exemple #13
0
 private static void CompareValue <TClient>(TClient expected, TClient actual)
 {
     if (expected == null)
     {
         actual.Should().BeNull();
     }
     else if (typeof(ISpatial).IsAssignableFrom(typeof(TClient)))
     {
         actual.Should().BeAssignableTo <TClient>();
         var formatter = WellKnownTextSqlFormatter.Create();
         formatter.Write((ISpatial)actual).Should().Be(formatter.Write((ISpatial)expected));
     }
     else if (typeof(TClient) != typeof(byte[]))
     {
         actual.Should().Be(expected);
     }
     else
     {
         actual.Should().BeAssignableTo <byte[]>();
         actual.As <byte[]>().Should().HaveCount(expected.As <byte[]>().Length);
         actual.As <byte[]>().Should().ContainInOrder(expected.As <byte[]>());
     }
 }
        /// <summary>
        /// Formats the literal without a type prefix, quotes, or escaping.
        /// </summary>
        /// <param name="value">The non-null value to format.</param>
        /// <returns>The formatted literal, without type marker or quotes.</returns>
        private static string FormatRawLiteral(object value)
        {
            Debug.Assert(value != null, "value != null");

            string stringValue = value as string;

            if (stringValue != null)
            {
                return(stringValue);
            }

            if (value is bool)
            {
                return(XmlConvert.ToString((bool)value));
            }

            if (value is byte)
            {
                return(XmlConvert.ToString((byte)value));
            }

#if ASTORIA_SERVER
            if (value is DateTime)
            {
                // Since the server/client supports DateTime values, convert the DateTime value
                // to DateTimeOffset and use XmlCOnvert to convert to String.
                DateTimeOffset dto = WebUtil.ConvertDateTimeToDateTimeOffset((DateTime)value);
                return(XmlConvert.ToString(dto));
            }
#endif

            if (value is decimal)
            {
                return(XmlConvert.ToString((decimal)value));
            }

            if (value is double)
            {
                string formattedDouble = XmlConvert.ToString((double)value);
                formattedDouble = SharedUtils.AppendDecimalMarkerToDouble(formattedDouble);
                return(formattedDouble);
            }

            if (value is Guid)
            {
                return(value.ToString());
            }

            if (value is short)
            {
                return(XmlConvert.ToString((Int16)value));
            }

            if (value is int)
            {
                return(XmlConvert.ToString((Int32)value));
            }

            if (value is long)
            {
                return(XmlConvert.ToString((Int64)value));
            }

            if (value is sbyte)
            {
                return(XmlConvert.ToString((SByte)value));
            }

            if (value is float)
            {
                return(XmlConvert.ToString((Single)value));
            }

            byte[] array = value as byte[];
            if (array != null)
            {
                return(ConvertByteArrayToKeyString(array));
            }

            if (value is DateTimeOffset)
            {
                return(XmlConvert.ToString((DateTimeOffset)value));
            }

            if (value is TimeSpan)
            {
                return(EdmValueWriter.DurationAsXml((TimeSpan)value));
            }

            Geography geography = value as Geography;
            if (geography != null)
            {
                return(WellKnownTextSqlFormatter.Create(true).Write(geography));
            }

            Geometry geometry = value as Geometry;
            if (geometry != null)
            {
                return(WellKnownTextSqlFormatter.Create(true).Write(geometry));
            }

            throw SharedUtils.CreateExceptionForUnconvertableType(value);
        }
Exemple #15
0
 /// <summary>
 /// Create an instance of the spatial formatter to use
 /// </summary>
 /// <returns>The spatial format to use</returns>
 protected override SpatialFormatter <TextReader, TextWriter> CreateFormatter()
 {
     return(WellKnownTextSqlFormatter.Create());
 }
        /// <summary>
        /// Создаёт объект Geography.
        /// </summary>
        /// <param name="wkt">Строка в формате WKT или EWKT.</param>
        /// <returns>Объект Geography.</returns>
        public static Geography CreateGeography(this string wkt)
        {
            WellKnownTextSqlFormatter wktFormatter = WellKnownTextSqlFormatter.Create();

            return(wktFormatter.Read <Geography>(new StringReader(wkt)));
        }
 /// <summary>
 /// Write the Atom representation of an instance of a primitive type to an TextWriter.
 /// </summary>
 /// <param name="instance">The instance to write.</param>
 /// <param name="writer">The text writer to use to write the instance.</param>
 public void WriteAtom(object instance, TextWriter writer)
 {
     ((Geometry)instance).SendTo(WellKnownTextSqlFormatter.Create().CreateWriter(writer));
 }
Exemple #18
0
        internal static bool TryXmlPrimitiveToString(object value, out string result)
        {
            Type nullableType = value.GetType();

            nullableType = Nullable.GetUnderlyingType(nullableType) ?? nullableType;
            if (typeof(string) == nullableType)
            {
                result = (string)value;
            }
            else if (typeof(bool) == nullableType)
            {
                result = XmlConvert.ToString((bool)value);
            }
            else if (typeof(byte) == nullableType)
            {
                result = XmlConvert.ToString((byte)value);
            }
            else if (typeof(DateTime) == nullableType)
            {
                result = System.Data.Services.Client.PlatformHelper.ConvertDateTimeToString((DateTime)value);
            }
            else if (typeof(decimal) == nullableType)
            {
                result = XmlConvert.ToString((decimal)value);
            }
            else if (typeof(double) == nullableType)
            {
                result = XmlConvert.ToString((double)value);
            }
            else if (typeof(Guid) == nullableType)
            {
                result = value.ToString();
            }
            else if (typeof(short) == nullableType)
            {
                result = XmlConvert.ToString((short)value);
            }
            else if (typeof(int) == nullableType)
            {
                result = XmlConvert.ToString((int)value);
            }
            else if (typeof(long) == nullableType)
            {
                result = XmlConvert.ToString((long)value);
            }
            else if (typeof(sbyte) == nullableType)
            {
                result = XmlConvert.ToString((sbyte)value);
            }
            else if (typeof(float) == nullableType)
            {
                result = XmlConvert.ToString((float)value);
            }
            else if (typeof(byte[]) == nullableType)
            {
                byte[] inArray = (byte[])value;
                result = Convert.ToBase64String(inArray);
            }
            else
            {
                if (ClientConvert.IsBinaryValue(value))
                {
                    return(ClientConvert.TryKeyBinaryToString(value, out result));
                }
                if (typeof(XElement) == nullableType)
                {
                    result = ((XElement)value).ToString(SaveOptions.None);
                }
                else if (typeof(DateTimeOffset) == nullableType)
                {
                    result = XmlConvert.ToString((DateTimeOffset)value);
                }
                else if (typeof(TimeSpan) == nullableType)
                {
                    result = XmlConvert.ToString((TimeSpan)value);
                }
                else if (typeof(Geography).IsAssignableFrom(nullableType))
                {
                    result = WellKnownTextSqlFormatter.Create(true).Write((Geography)value);
                }
                else if (typeof(Geometry).IsAssignableFrom(nullableType))
                {
                    result = WellKnownTextSqlFormatter.Create(true).Write((Geometry)value);
                }
                else
                {
                    result = null;
                    return(false);
                }
            }
            return(true);
        }
        private static void GeographyToWktTest(WellKnownTextSqlFormatter formatter, Action<GeographyPipeline> pipelineAction, string expectedWkt)
        {
            var stringWriter = new StringWriter();
            var w = formatter.CreateWriter(stringWriter);

            w.GeographyPipeline.SetCoordinateSystem(CoordinateSystem.DefaultGeography);
            pipelineAction(w);

            Assert.Equal(expectedWkt, stringWriter.GetStringBuilder().ToString());
        }
Exemple #20
0
 public static void ClassInit(TestContext context)
 {
     wktFormatter  = WellKnownTextSqlFormatter.Create();
     jsonFormatter = GeoJsonObjectFormatter.Create();
     gmlFormatter  = GmlFormatter.Create();
 }
Exemple #21
0
        /// <summary>
        /// Formats the literal without a type prefix, quotes, or escaping.
        /// </summary>
        /// <param name="value">The non-null value to format.</param>
        /// <returns>The formatted literal, without type marker or quotes.</returns>
        private static string FormatRawLiteral(object value)
        {
            Debug.Assert(value != null, "value != null");

            string stringValue = value as string;

            if (stringValue != null)
            {
                return(stringValue);
            }

            if (value is bool)
            {
                return(XmlConvert.ToString((bool)value));
            }

            if (value is byte)
            {
                return(XmlConvert.ToString((byte)value));
            }

            if (value is DateTime)
            {
#if PORTABLELIB
                return(PlatformHelper.ConvertDateTimeToString((DateTime)value));
#else
                return(XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind));
#endif
            }

            if (value is decimal)
            {
                return(XmlConvert.ToString((decimal)value));
            }

            if (value is double)
            {
                string formattedDouble = XmlConvert.ToString((double)value);
                formattedDouble = SharedUtils.AppendDecimalMarkerToDouble(formattedDouble);
                return(formattedDouble);
            }

            if (value is Guid)
            {
                return(value.ToString());
            }

            if (value is short)
            {
                return(XmlConvert.ToString((Int16)value));
            }

            if (value is int)
            {
                return(XmlConvert.ToString((Int32)value));
            }

            if (value is long)
            {
                return(XmlConvert.ToString((Int64)value));
            }

            if (value is sbyte)
            {
                return(XmlConvert.ToString((SByte)value));
            }

            if (value is float)
            {
                return(XmlConvert.ToString((Single)value));
            }

            byte[] array = value as byte[];
            if (array != null)
            {
                return(ConvertByteArrayToKeyString(array));
            }

            if (value is DateTimeOffset)
            {
                return(XmlConvert.ToString((DateTimeOffset)value));
            }

            if (value is TimeSpan)
            {
                return(XmlConvert.ToString((TimeSpan)value));
            }

            Geography geography = value as Geography;
            if (geography != null)
            {
                return(WellKnownTextSqlFormatter.Create(true).Write(geography));
            }

            Geometry geometry = value as Geometry;
            if (geometry != null)
            {
                return(WellKnownTextSqlFormatter.Create(true).Write(geometry));
            }

            throw SharedUtils.CreateExceptionForUnconvertableType(value);
        }
Exemple #22
0
        internal static bool TryXmlPrimitiveToString(object value, out string result)
        {
            Type nullableType = value.GetType();

            nullableType = Nullable.GetUnderlyingType(nullableType) ?? nullableType;
            if (typeof(string) == nullableType)
            {
                result = (string)value;
            }
            else if (typeof(bool) == nullableType)
            {
                result = XmlConvert.ToString((bool)value);
            }
            else if (typeof(byte) == nullableType)
            {
                result = XmlConvert.ToString((byte)value);
            }
            else if (typeof(DateTime) == nullableType)
            {
                result = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind);
            }
            else if (typeof(decimal) == nullableType)
            {
                result = XmlConvert.ToString((decimal)value);
            }
            else if (typeof(double) == nullableType)
            {
                result = XmlConvert.ToString((double)value);
            }
            else if (typeof(Guid) == nullableType)
            {
                result = value.ToString();
            }
            else if (typeof(short) == nullableType)
            {
                result = XmlConvert.ToString((short)value);
            }
            else if (typeof(int) == nullableType)
            {
                result = XmlConvert.ToString((int)value);
            }
            else if (typeof(long) == nullableType)
            {
                result = XmlConvert.ToString((long)value);
            }
            else if (typeof(sbyte) == nullableType)
            {
                result = XmlConvert.ToString((sbyte)value);
            }
            else if (typeof(float) == nullableType)
            {
                result = XmlConvert.ToString((float)value);
            }
            else if (typeof(byte[]) == nullableType)
            {
                byte[] inArray = (byte[])value;
                result = Convert.ToBase64String(inArray);
            }
            else
            {
                if (typeof(Binary) == nullableType)
                {
                    return(TryXmlPrimitiveToString(((Binary)value).ToArray(), out result));
                }
                if (typeof(XElement) == nullableType)
                {
                    result = ((XElement)value).ToString(SaveOptions.None);
                }
                else if (typeof(DateTimeOffset) == nullableType)
                {
                    result = XmlConvert.ToString((DateTimeOffset)value);
                }
                else if (typeof(TimeSpan) == nullableType)
                {
                    result = XmlConvert.ToString((TimeSpan)value);
                }
                else if (typeof(Geography).IsAssignableFrom(nullableType))
                {
                    result = WellKnownTextSqlFormatter.Create(true).Write((Geography)value);
                }
                else if (typeof(Geometry).IsAssignableFrom(nullableType))
                {
                    result = WellKnownTextSqlFormatter.Create(true).Write((Geometry)value);
                }
                else
                {
                    result = null;
                    return(false);
                }
            }
            return(true);
        }
Exemple #23
0
        private static bool TryParseSpatialLiteral <T>(string literalText, string prefix, WellKnownTextSqlFormatter formatter, out T literalValue) where T : class, ISpatial
        {
            string str;
            bool   flag2;

            if (!TryExtractWellKnownTextSqlFromSpatialLiteral(literalText, prefix, out str))
            {
                literalValue = default(T);
                return(false);
            }
            StringReader input = new StringReader(str);

            try
            {
                literalValue = formatter.Read <T>(input);
                flag2        = true;
            }
            catch (Exception exception)
            {
                if (!CommonUtil.IsCatchableExceptionType(exception))
                {
                    throw;
                }
                literalValue = default(T);
                flag2        = false;
            }
            finally
            {
                if (input != null)
                {
                    input.Dispose();
                }
            }
            return(flag2);
        }
        internal static string ConvertToUriPrimitiveLiteral(object value, ODataVersion version)
        {
            ExceptionUtils.CheckArgumentNotNull<object>(value, "value");
            StringBuilder builder = new StringBuilder();
            Type nullableType = value.GetType();
            nullableType = Nullable.GetUnderlyingType(nullableType) ?? nullableType;
            switch (Microsoft.Data.OData.PlatformHelper.GetTypeCode(nullableType))
            {
                case TypeCode.Object:
                    if (!(nullableType == typeof(byte[])))
                    {
                        if (nullableType == typeof(Guid))
                        {
                            builder.Append("guid");
                            builder.Append("'");
                            builder.Append(value.ToString());
                            builder.Append("'");
                        }
                        else if (nullableType == typeof(DateTimeOffset))
                        {
                            builder.Append("datetimeoffset");
                            builder.Append("'");
                            builder.Append(XmlConvert.ToString((DateTimeOffset) value));
                            builder.Append("'");
                        }
                        else if (nullableType == typeof(TimeSpan))
                        {
                            builder.Append("time");
                            builder.Append("'");
                            builder.Append(XmlConvert.ToString((TimeSpan) value));
                            builder.Append("'");
                        }
                        else if (typeof(Geography).IsAssignableFrom(nullableType))
                        {
                            ODataVersionChecker.CheckSpatialValue(version);
                            builder.Append("geography");
                            builder.Append("'");
                            builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geography) value));
                            builder.Append("'");
                        }
                        else
                        {
                            if (!typeof(Geometry).IsAssignableFrom(nullableType))
                            {
                                throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(nullableType.ToString()));
                            }
                            ODataVersionChecker.CheckSpatialValue(version);
                            builder.Append("geometry");
                            builder.Append("'");
                            builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geometry) value));
                            builder.Append("'");
                        }
                        break;
                    }
                    builder.Append(ConvertByteArrayToKeyString((byte[]) value));
                    break;

                case TypeCode.Boolean:
                    builder.Append(XmlConvert.ToString((bool) value));
                    return builder.ToString();

                case TypeCode.SByte:
                    builder.Append(XmlConvert.ToString((sbyte) value));
                    return builder.ToString();

                case TypeCode.Byte:
                    builder.Append(XmlConvert.ToString((byte) value));
                    return builder.ToString();

                case TypeCode.Int16:
                    builder.Append(XmlConvert.ToString((short) value));
                    return builder.ToString();

                case TypeCode.Int32:
                    builder.Append(XmlConvert.ToString((int) value));
                    return builder.ToString();

                case TypeCode.Int64:
                    builder.Append(XmlConvert.ToString((long) value));
                    builder.Append("L");
                    return builder.ToString();

                case TypeCode.Single:
                    builder.Append(XmlConvert.ToString((float) value));
                    builder.Append("f");
                    return builder.ToString();

                case TypeCode.Double:
                    builder.Append(AppendDecimalMarkerToDouble(XmlConvert.ToString((double) value)));
                    builder.Append("D");
                    return builder.ToString();

                case TypeCode.Decimal:
                    builder.Append(XmlConvert.ToString((decimal) value));
                    builder.Append("M");
                    return builder.ToString();

                case TypeCode.DateTime:
                    builder.Append("datetime");
                    builder.Append("'");
                    builder.Append(Microsoft.Data.OData.PlatformHelper.ConvertDateTimeToString((DateTime) value));
                    builder.Append("'");
                    return builder.ToString();

                case TypeCode.String:
                    builder.Append("'");
                    builder.Append(((string) value).Replace("'", "''"));
                    builder.Append("'");
                    return builder.ToString();

                default:
                    throw new ODataException(Microsoft.Data.OData.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(nullableType.ToString()));
            }
            return builder.ToString();
        }
Exemple #25
0
        /// <summary>
        /// Converts a primitive to a string for use in a Url.
        /// </summary>
        /// <param name="value">Value to convert.</param>
        /// <param name="version">OData version to be compliant with.</param>
        /// <returns>A string representation of <paramref name="value"/> to be added to a Url.</returns>
        internal static string ConvertToUriPrimitiveLiteral(object value, ODataVersion version)
        {
            DebugUtils.CheckNoExternalCallers();
            ExceptionUtils.CheckArgumentNotNull(value, "value");

            /* This should have the same behavior of Astoria with these differences: (iawillia, 10/7/11)
             * TODO BUG 292670: Differences betwen Astoria and ODL's Uri literals
             * 1) Cannot handle the System.Data.Linq.Binary type
             * 2) Cannot handle the System.Data.Linq.XElement type
             * 3) Astoria does not put a 'd' or 'D' on double values
             */

            StringBuilder builder = new StringBuilder();

            Type valueType = value.GetType();

            valueType = Nullable.GetUnderlyingType(valueType) ?? valueType;

            TypeCode code = o.PlatformHelper.GetTypeCode(valueType);

            switch (code)
            {
            case TypeCode.Boolean:
                builder.Append(XmlConvert.ToString((bool)value));
                return(builder.ToString());

            case TypeCode.Byte:
                builder.Append(XmlConvert.ToString((byte)value));
                return(builder.ToString());

            case TypeCode.DateTime:
                builder.Append(ExpressionConstants.LiteralPrefixDateTime);
                builder.Append(ExpressionConstants.LiteralSingleQuote);
                builder.Append(o.PlatformHelper.ConvertDateTimeToString((DateTime)value));
                builder.Append(ExpressionConstants.LiteralSingleQuote);
                return(builder.ToString());

            case TypeCode.Decimal:
                builder.Append(XmlConvert.ToString((Decimal)value));
                builder.Append(ExpressionConstants.LiteralSuffixDecimal);
                return(builder.ToString());

            case TypeCode.Double:
                builder.Append(AppendDecimalMarkerToDouble(XmlConvert.ToString((Double)value)));
                builder.Append(ExpressionConstants.LiteralSuffixDouble);
                return(builder.ToString());

            case TypeCode.Int16:
                builder.Append(XmlConvert.ToString((Int16)value));
                return(builder.ToString());

            case TypeCode.Int32:
                builder.Append(XmlConvert.ToString((Int32)value));
                return(builder.ToString());

            case TypeCode.Int64:
                builder.Append(XmlConvert.ToString((Int64)value));
                builder.Append(ExpressionConstants.LiteralSuffixInt64);
                return(builder.ToString());

            case TypeCode.Object:
                if (valueType == typeof(byte[]))
                {
                    builder.Append(ConvertByteArrayToKeyString((byte[])value));
                }
                else if (valueType == typeof(Guid))
                {
                    builder.Append(ExpressionConstants.LiteralPrefixGuid);
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                    builder.Append(value.ToString());
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                }
                else if (valueType == typeof(DateTimeOffset))
                {
                    builder.Append(ExpressionConstants.LiteralPrefixDateTimeOffset);
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                    builder.Append(XmlConvert.ToString((DateTimeOffset)value));
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                }
                else if (valueType == typeof(TimeSpan))
                {
                    builder.Append(ExpressionConstants.LiteralPrefixTime);
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                    builder.Append(XmlConvert.ToString((TimeSpan)value));
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                }
                else if (typeof(Geography).IsAssignableFrom(valueType))
                {
                    ODataVersionChecker.CheckSpatialValue(version);
                    builder.Append(ExpressionConstants.LiteralPrefixGeography);
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                    builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geography)value));
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                }
                else if (typeof(Geometry).IsAssignableFrom(valueType))
                {
                    ODataVersionChecker.CheckSpatialValue(version);
                    builder.Append(ExpressionConstants.LiteralPrefixGeometry);
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                    builder.Append(WellKnownTextSqlFormatter.Create(true).Write((Geometry)value));
                    builder.Append(ExpressionConstants.LiteralSingleQuote);
                }
                else
                {
                    throw new ODataException(o.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(valueType.ToString()));
                }

                return(builder.ToString());

            case TypeCode.SByte:
                builder.Append(XmlConvert.ToString((SByte)value));
                return(builder.ToString());

            case TypeCode.Single:
                builder.Append(XmlConvert.ToString((Single)value));
                builder.Append(ExpressionConstants.LiteralSuffixSingle);
                return(builder.ToString());

            case TypeCode.String:
                builder.Append(ExpressionConstants.LiteralSingleQuote);
                builder.Append(((String)value).Replace("'", "''"));
                builder.Append(ExpressionConstants.LiteralSingleQuote);
                return(builder.ToString());

            default:
                throw new ODataException(o.Strings.ODataUriUtils_ConvertToUriLiteralUnsupportedType(valueType.ToString()));
            }
        }
        private static bool TryParseSpatialLiteral <T>(string literalText, string prefix, WellKnownTextSqlFormatter formatter, out T literalValue) where T : class, ISpatial
        {
            string text;
            var    worked = TryExtractWellKnownTextSqlFromSpatialLiteral(literalText, prefix, out text);

            if (!worked)
            {
                literalValue = null;
                return(false);
            }

            using (var reader = new StringReader(text))
            {
                try
                {
                    literalValue = formatter.Read <T>(reader);
                    return(true);
                }
                catch (Exception e)
                {
                    if (CommonUtil.IsCatchableExceptionType(e))
                    {
                        literalValue = null;
                        return(false);
                    }

                    throw;
                }
            }
        }
Exemple #27
0
        public static string GetUriLiteral(Type type, ISpatial spatial)
        {
            string typePrefix = typeof(Geometry).IsAssignableFrom(type) ? "geometry" : "geography";

            return(string.Format("{0}'{1}'", typePrefix, WellKnownTextSqlFormatter.Create().Write(spatial)));
        }
Exemple #28
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");
            }
        }