/// <summary> /// Tries to convert the given value if it is of a type specific to the client library but still able to be mapped to EDM. /// </summary> /// <param name="primitiveValue">The value to convert.</param> /// <param name="type">The expected type of the value or null.</param> /// <param name="convertedValue">The converted value, if conversion was possible.</param> /// <returns>Whether or not conversion was possible.</returns> private static bool TryConvertClientSpecificPrimitiveValue(object primitiveValue, IEdmPrimitiveTypeReference type, out IEdmDelayedValue convertedValue) { byte[] byteArray; if (ClientConvert.TryConvertBinaryToByteArray(primitiveValue, out byteArray)) { type = EnsurePrimitiveType(type, EdmPrimitiveTypeKind.Binary); convertedValue = new EdmBinaryConstant((IEdmBinaryTypeReference)type, byteArray); return(true); } PrimitiveType clientPrimitiveType; if (PrimitiveType.TryGetPrimitiveType(primitiveValue.GetType(), out clientPrimitiveType)) { type = EnsurePrimitiveType(type, clientPrimitiveType.PrimitiveKind); if (clientPrimitiveType.PrimitiveKind == EdmPrimitiveTypeKind.String) { { convertedValue = new EdmStringConstant((IEdmStringTypeReference)type, clientPrimitiveType.TypeConverter.ToString(primitiveValue)); return(true); } } } convertedValue = null; return(false); }
/// <summary> /// User hook to resolve name into a type. /// </summary> /// <param name="wireName">Name to resolve.</param> /// <param name="expectedType">Expected type for the name.</param> /// <returns>the type as returned by the resolver. If no resolver is registered or resolver returns null, expected type is returned.</returns> /// <exception cref="InvalidOperationException">if ResolveType function returns a type not assignable to the userType</exception> private Type ResolveTypeFromName(string wireName, Type expectedType) { Debug.Assert(!String.IsNullOrEmpty(wireName), "!String.IsNullOrEmpty(wireName)"); Debug.Assert(expectedType != null, "userType != null"); // If there is a mismatch between the wireName and expected type (For e.g. wireName is Edm.Int32 and expectedType is a complex type) // we will return Edm.Int32 from this method and ODatalib fails stating the type kind do not match. Type payloadType; if (!ClientConvert.ToNamedType(wireName, out payloadType)) { payloadType = this.resolveTypeFromName(wireName); if (payloadType == null) { // if the type resolution method returns null or the ResolveType property was not set #if !PORTABLELIB payloadType = ClientTypeCache.ResolveFromName(wireName, expectedType); #else payloadType = ClientTypeCache.ResolveFromName(wireName, expectedType, this.GetType()); #endif } if (!this.skipTypeAssignabilityCheck && (payloadType != null) && (!expectedType.IsAssignableFrom(payloadType))) { // throw an exception if the type from the resolver is not assignable to the expected type throw Error.InvalidOperation(Strings.Deserialize_Current(expectedType, payloadType)); } } return(payloadType ?? expectedType); }
// Export private void Export(List <ExcelData> exportList) { if (exportList.Count == 0) { MessageBox.Show("列表为空!"); return; } var progress = new ProgressWindow(); progress.Start(exportList.Count * 2, "Convert"); progress.Show(); ClientConvert clientConvert = new ClientConvert(); for (int i = 0; i < exportList.Count; i++) { progress.SetProgress(i + 1, exportList[i].FileName); DoEvents(); clientConvert.Export(exportList[i]); } ServerConvert serverConvert = new ServerConvert(); for (int i = 0; i < exportList.Count; i++) { progress.SetProgress(i + 1 + exportList.Count, exportList[i].FileName); DoEvents(); serverConvert.Export(exportList[i]); } progress.Close(); ProcessUtility.OpenFolder(GlobalDataManager.Instance.Config.OutputPath); }
public void ChangeTypeTest() { TestPrimitiveType value = (TestPrimitiveType)ClientConvert.ChangeType("Property_Value", typeof(TestPrimitiveType)); Assert.AreEqual("Property_Value", value.Data); Assert.AreEqual(1, converter.ParseCall); Assert.AreEqual(0, converter.ToStringCall); }
public void GetEdmTypeTests() { Assert.AreEqual("Edm.TestPrimitive", ClientConvert.GetEdmType(typeof(TestPrimitiveType))); foreach (Type t in new Type[] { typeof(UInt16), typeof(UInt32), typeof(UInt64) }) { Action test = () => ClientConvert.GetEdmType(t); test.ShouldThrow <NotSupportedException>().WithMessage(Strings.ALinq_CantCastToUnsupportedPrimitive(t.Name)); } }
public void ToStringTests() { var str = ClientConvert.ToString(new TestPrimitiveType() { Data = "Property_Value" }); Assert.AreEqual("Property_Value", str); Assert.AreEqual(0, converter.ParseCall); Assert.AreEqual(1, converter.ToStringCall); }
public void ToNamedTypeTests() { Type t; Assert.IsTrue(ClientConvert.ToNamedType(String.Empty, out t)); Assert.AreEqual(typeof(String), t); Assert.IsTrue(ClientConvert.ToNamedType(null, out t)); Assert.AreEqual(typeof(String), t); Assert.IsTrue(ClientConvert.ToNamedType("Edm.TestPrimitive", out t)); Assert.AreEqual(typeof(TestPrimitiveType), t); }
/// <summary> /// Converts a non-spatial primitive value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type of the conversion.</param> /// <returns>The converted value.</returns> private static object ConvertNonSpatialValue(object value, Type targetType) { Debug.Assert(value != null, "value != null"); // These types can be safely converted to directly, as there is no risk of precision being lost. if (CanSafelyConvertTo(targetType)) { return(Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture)); } string stringValue = ClientConvert.ToString(value); return(ClientConvert.ChangeType(stringValue, targetType)); }
private void PopulateData(EpmTargetPathSegment segment, object element, EpmContentSerializer.EpmNullValuedPropertyTree nullValuedProperties, DataServiceProviderWrapper provider) #endif { if (segment.EpmInfo != null) { Object propertyValue; try { #if ASTORIA_CLIENT propertyValue = segment.EpmInfo.ReadPropertyValue(element); #else propertyValue = segment.EpmInfo.ReadPropertyValue(element, provider); #endif } catch #if ASTORIA_CLIENT (System.Reflection.TargetInvocationException) #else (System.Reflection.TargetInvocationException e) #endif { #if !ASTORIA_CLIENT ErrorHandler.HandleTargetInvocationException(e); #endif throw; } #if ASTORIA_CLIENT this.Data = propertyValue == null ? String.Empty : ClientConvert.ToString(propertyValue, false); #else if (propertyValue == null || propertyValue == DBNull.Value) { this.Data = String.Empty; nullValuedProperties.Add(segment.EpmInfo); } else { this.Data = PlainXmlSerializer.PrimitiveToString(propertyValue); } #endif } } }
private void PopulateData(EpmTargetPathSegment segment, object element) { if (segment.EpmInfo != null) { Object propertyValue; try { propertyValue = segment.EpmInfo.PropValReader.DynamicInvoke(element); } catch (System.Reflection.TargetInvocationException) { throw; } this.Data = propertyValue == null ? String.Empty : ClientConvert.ToString(propertyValue, false); } }
private static bool TryGetByteArrayFromBinary(object value, out byte[] array) { // DEVNOTE: the client does not have a reference to System.Data.Linq, but the server does. // So we need to interact with Binary differently. #if ASTORIA_SERVER Binary binary = value as Binary; if (binary != null) { array = binary.ToArray(); return(true); } #endif #if ASTORIA_CLIENT return(ClientConvert.TryConvertBinaryToByteArray(value, out array)); #else array = null; return(false); #endif }
/// <summary> /// Converts a non-spatial primitive value to the target type. /// </summary> /// <param name="value">The value to convert.</param> /// <param name="targetType">The target type of the conversion.</param> /// <returns>The converted value.</returns> private static object ConvertNonSpatialValue(object value, Type targetType) { Debug.Assert(value != null, "value != null"); TypeCode targetTypeCode = PlatformHelper.GetTypeCode(targetType); // These types can be safely converted to directly, as there is no risk of precision being lost. switch (targetTypeCode) { case TypeCode.Boolean: case TypeCode.Byte: case TypeCode.SByte: case TypeCode.Int16: case TypeCode.Int32: case TypeCode.Int64: return(Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture)); } string stringValue = ClientConvert.ToString(value); return(ClientConvert.ChangeType(stringValue, targetType)); }
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); }
/// <summary> /// Materialize by calling the Parse method on the converter /// </summary> /// <param name="clrType">clrType</param> /// <returns>A materialized instance</returns> internal override object Materialize(Type clrType) { return(ClientConvert.ChangeType(this.Text, clrType)); }
/// <summary> /// Adds a data value to the dynamic properties dictionary (where it exists) on the specified <paramref name="instance"/> /// </summary> /// <param name="property">Property containing unmaterialzed value to apply</param> /// <param name="instance">Instance that may optionally contain the dynamic properties dictionary</param> internal void MaterializeDynamicProperty(ODataProperty property, object instance) { Debug.Assert(property != null, "property != null"); Debug.Assert(instance != null, "instance != null"); IDictionary <string, object> containerProperty; // Stop if owning type is not an open type // Or container property is not found // Or key with matching name already exists in the dictionary if (!ClientTypeUtil.IsInstanceOfOpenType(instance, this.MaterializerContext.Model) || !ClientTypeUtil.TryGetContainerProperty(instance, out containerProperty) || containerProperty.ContainsKey(property.Name)) { return; } object value = property.Value; // Handles properties of known types returned with type annotations if (!(value is ODataValue) && PrimitiveType.IsKnownType(value.GetType())) { containerProperty.Add(property.Name, value); return; } // Handle untyped value ODataUntypedValue untypedVal = value as ODataUntypedValue; if (untypedVal != null) { value = CommonUtil.ParseJsonToPrimitiveValue(untypedVal.RawValue); containerProperty.Add(property.Name, value); return; } // Handle enum value ODataEnumValue enumVal = value as ODataEnumValue; if (enumVal != null) { Type clientType = ResolveClientTypeForDynamicProperty(enumVal.TypeName, instance); // Unable to resolve type for dynamic property if (clientType == null) { return; } object materializedEnumValue; if (EnumValueMaterializationPolicy.TryMaterializeODataEnumValue(clientType, enumVal, out materializedEnumValue)) { containerProperty.Add(property.Name, materializedEnumValue); } return; } // Handle collection ODataCollectionValue collectionVal = value as ODataCollectionValue; if (collectionVal != null) { string collectionItemTypeName = CommonUtil.GetCollectionItemTypeName(collectionVal.TypeName, false); // Highly unlikely, but the method return null if the typeName argument does not meet certain expectations if (collectionItemTypeName == null) { return; } Type collectionItemType; // ToNamedType will return true for primitive types if (!ClientConvert.ToNamedType(collectionItemTypeName, out collectionItemType)) { // Non-primitive collection collectionItemType = ResolveClientTypeForDynamicProperty(collectionItemTypeName, instance); } if (collectionItemType == null) { return; } object collectionInstance; if (this.CollectionValueMaterializationPolicy.TryMaterializeODataCollectionValue(collectionItemType, property, out collectionInstance)) { containerProperty.Add(property.Name, collectionInstance); } return; } }
internal static bool TryXmlPrimitiveToString(object value, out string result) { Debug.Assert(value != null, "value != null"); result = null; Type valueType = value.GetType(); valueType = Nullable.GetUnderlyingType(valueType) ?? valueType; if (typeof(String) == valueType) { result = (string)value; } else if (typeof(Boolean) == valueType) { result = XmlConvert.ToString((bool)value); } else if (typeof(Byte) == valueType) { result = XmlConvert.ToString((byte)value); } else if (typeof(DateTime) == valueType) { result = XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.RoundtripKind); } else if (typeof(Decimal) == valueType) { result = XmlConvert.ToString((decimal)value); } else if (typeof(Double) == valueType) { result = XmlConvert.ToString((double)value); } else if (typeof(Guid) == valueType) { result = value.ToString(); } else if (typeof(Int16) == valueType) { result = XmlConvert.ToString((Int16)value); } else if (typeof(Int32) == valueType) { result = XmlConvert.ToString((Int32)value); } else if (typeof(Int64) == valueType) { result = XmlConvert.ToString((Int64)value); } else if (typeof(SByte) == valueType) { result = XmlConvert.ToString((SByte)value); } else if (typeof(Single) == valueType) { result = XmlConvert.ToString((Single)value); } else if (typeof(byte[]) == valueType) { byte[] byteArray = (byte[])value; result = Convert.ToBase64String(byteArray); } #if !ASTORIA_LIGHT else if (ClientConvert.IsBinaryValue(value)) { return(ClientConvert.TryKeyBinaryToString(value, out result)); } #endif else if (typeof(System.Xml.Linq.XElement) == valueType) { result = ((System.Xml.Linq.XElement)value).ToString(System.Xml.Linq.SaveOptions.None); } else { result = null; return(false); } Debug.Assert(result != null, "result != null"); return(true); }
/// <summary> /// Load property data form a raw response /// </summary> /// <param name="property">The property being loaded</param> /// <returns>property values as IEnumerable.</returns> private MaterializeAtom ReadPropertyFromRawData(ClientPropertyAnnotation property) { DataServiceContext context = (DataServiceContext)this.Source; bool merging = context.ApplyingChanges; try { context.ApplyingChanges = true; // if this is the data property for a media entry, what comes back // is the raw value (no markup) string mimeType = null; Encoding encoding = null; Type elementType = property.EntityCollectionItemType ?? property.NullablePropertyType; IList results = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(elementType)); ContentTypeUtil.ReadContentType(this.ContentType, out mimeType, out encoding); using (Stream responseStream = this.GetResponseStream()) { // special case byte[], and for everything else let std conversion kick-in if (property.PropertyType == typeof(byte[])) { int total = checked ((int)this.ContentLength); byte[] buffer = null; if (total >= 0) { buffer = LoadPropertyResult.ReadByteArrayWithContentLength(responseStream, total); } else { buffer = LoadPropertyResult.ReadByteArrayChunked(responseStream); } results.Add(buffer); property.SetValue(this.entity, buffer, this.propertyName, false); } else { // responseStream will disposed, StreamReader doesn't need to dispose of it. StreamReader reader = new StreamReader(responseStream, encoding); object convertedValue = property.PropertyType == typeof(string) ? reader.ReadToEnd() : ClientConvert.ChangeType(reader.ReadToEnd(), property.PropertyType); results.Add(convertedValue); property.SetValue(this.entity, convertedValue, this.propertyName, false); } } if (property.MimeTypeProperty != null) { // an implication of this 3rd-arg-null is that mime type properties cannot be open props property.MimeTypeProperty.SetValue(this.entity, mimeType, null, false); } return(MaterializeAtom.CreateWrapper(context, results)); } finally { context.ApplyingChanges = merging; } }