public SumHandleWrite(IAdsConnection connection, IDictionary <uint, Type> handleTypeDict) : base(connection, TwinCAT.Ads.SumCommand.SumCommand.SumAccessMode.ValueByHandle) { this._converter = PrimitiveTypeConverter.Default; base.sumEntities = new List <SumDataEntity>(); foreach (KeyValuePair <uint, Type> pair in handleTypeDict) { base.sumEntities.Add(new HandleSumWriteAnyEntity(pair.Key, pair.Value, this._converter)); } }
//public Type GetChoiceType(string choiceSuffix) //{ // string suffix = choiceSuffix.ToUpperInvariant(); // if(!HasChoices) return null; // return _choices // .Where(cattr => cattr.TypeName.ToUpperInvariant() == suffix) // .Select(cattr => cattr.Type) // .FirstOrDefault(); //} private static bool isAllowedNativeTypeForDataTypeValue(Type type) { // Special case, allow Nullable<enum> if (ReflectionHelper.IsNullableType(type)) type = ReflectionHelper.GetNullableArgument(type); return type.IsEnum() || PrimitiveTypeConverter.CanConvert(type); }
public DateTime?ToDateTime() { if (this.Value == null) { return(null); } return(PrimitiveTypeConverter.ConvertTo <DateTime>(this.Value)); }
private static bool TryParseSubRange(IDataType baseType, TypeAttributeCollection attributes, IBinder binder, out ISubRangeType subRange) { string str; string str2; if (((attributes != null) && ((attributes.Count >= 2) && (baseType.Category == DataTypeCategory.Primitive))) && (attributes.TryGetValue("LowerBorder", out str2) & attributes.TryGetValue("UpperBorder", out str))) { object obj2; object obj3; IManagedMappableType type = (IManagedMappableType)baseType; System.Type managedType = type.ManagedType; System.Type type3 = type.ManagedType; if (managedType == typeof(byte)) { type3 = typeof(sbyte); } else if (managedType == typeof(ushort)) { type3 = typeof(short); } else if (managedType == typeof(uint)) { type3 = typeof(int); } else if (managedType == typeof(ulong)) { type3 = typeof(long); } if (DataTypeStringParser.TryParse(str, type3, out obj3) & DataTypeStringParser.TryParse(str2, type3, out obj2)) { object obj4; object obj5; if (managedType == type3) { obj4 = obj2; obj5 = obj3; } else { PrimitiveTypeConverter converter = PrimitiveTypeConverter.Default; byte[] data = converter.Marshal(obj2); byte[] buffer2 = converter.Marshal(obj3); converter.UnmarshalPrimitive(managedType, data, 0, data.Length, out obj4); converter.UnmarshalPrimitive(managedType, buffer2, 0, buffer2.Length, out obj5); } string name = $"{baseType.Name} ({obj4}..{obj5})"; IDataType type4 = null; if (binder.TryResolveType(name, out type4)) { subRange = (ISubRangeType)type4; return(true); } } } subRange = null; return(false); }
public SumHandleWrite(IAdsConnection connection, uint[] serverHandles, Type[] valueTypes) : base(connection, TwinCAT.Ads.SumCommand.SumCommand.SumAccessMode.ValueByHandle) { this._converter = PrimitiveTypeConverter.Default; base.sumEntities = new List <SumDataEntity>(); for (int i = 0; i < serverHandles.Length; i++) { base.sumEntities.Add(new HandleSumWriteAnyEntity(serverHandles[i], valueTypes[i], this._converter)); } }
internal SubRangeType(string name, string baseType, int size, T lowerBound, T upperBound) : base(name, AdsDatatypeId.ADST_VOID, DataTypeCategory.SubRange, size, typeof(T)) { this.baseTypeName = string.Empty; bool flag = PrimitiveTypeConverter.TryGetDataTypeId(typeof(T), out base.dataTypeId); this.baseTypeName = baseType; this._lowerBound = lowerBound; this._upperBound = upperBound; }
public override string ToString() { var ns = Namespace ?? string.Empty; return(PrimitiveTypeConverter.ConvertTo <string>(Number) + "|" + StringValue.EscapeString(ns) + "|" + StringValue.EscapeString(Unit)); }
internal int InitializeEnum(string typeName, Type managedType, AdsDatatypeId dataType, int size, AdsBinaryReader reader, int readerPosition, out object value) { AdsDatatypeId typeId = dataType; if (typeId == AdsDatatypeId.ADST_BIGTYPE) { PrimitiveTypeConverter.TryGetDataTypeId(managedType, out typeId); } return(this.InitializePrimitiveType(typeName, managedType, typeId, size, reader, readerPosition, out value)); }
public override string ToString() { // The primitive can exist without a value (when there is an extension present) // so we need to be able to handle when there is no extension present if (this.ObjectValue == null) { return(null); } return(PrimitiveTypeConverter.ConvertTo <string>(this.ObjectValue)); }
public void TestStringToBool() { var result = PrimitiveTypeConverter.ConvertTo <bool>("false"); Assert.IsFalse(result); Assert.AreEqual("false", PrimitiveTypeConverter.ConvertTo <string>(result)); result = PrimitiveTypeConverter.ConvertTo <bool>("true"); Assert.IsTrue(result); Assert.AreEqual("true", PrimitiveTypeConverter.ConvertTo <string>(result)); }
public HandleSumWriteAnyEntity(uint handle, System.Type tp, PrimitiveTypeConverter converter) : base(handle, 0, -1, converter) { this.Type = tp; if (tp == typeof(string)) { base.writeLength = -1; } else { base.writeLength = PrimitiveTypeConverter.MarshalSize(tp); } }
/// <summary>Harvest the value of the current element into a property bag.</summary> /// <param name="nav">An <see cref="ISourceNode"/> instance.</param> /// <param name="properties">A property bag to store harvested summary information.</param> /// <param name="key">A property key.</param> public static bool HarvestValue(this ISourceNode nav, IDictionary <string, object> properties, string key) { var value = nav.Text; if (value != null) { var s = PrimitiveTypeConverter.ConvertTo <string>(value); properties[key] = s; return(true); } return(false); }
public void TestStringToUri() { var result = PrimitiveTypeConverter.ConvertTo <Uri>("http://www.nu.nl/test"); Assert.IsTrue(result.IsAbsoluteUri); Assert.AreEqual("www.nu.nl", result.Host); Assert.AreEqual("http://www.nu.nl/test", PrimitiveTypeConverter.ConvertTo <string>(result)); result = PrimitiveTypeConverter.ConvertTo <Uri>("service/patient/3"); Assert.IsFalse(result.IsAbsoluteUri); Assert.AreEqual("service/patient/3", PrimitiveTypeConverter.ConvertTo <string>(result)); }
/// <summary>Add the value of the current element to a list, if not missing or empty.</summary> /// <param name="nav">An <see cref="ISourceNode"/> instance.</param> /// <param name="values">A list of values.</param> public static bool HarvestValue(this ISourceNode nav, IList <string> values) { var value = nav.Text; if (value != null) { var s = PrimitiveTypeConverter.ConvertTo <string>(value); values.Add(s); return(true); } return(false); }
/// <summary>Add the value of the current element to a list, if not missing or empty.</summary> /// <param name="nav">An <see cref="IElementNavigator"/> instance.</param> /// <param name="values">A list of values.</param> public static bool HarvestValue(this IElementNavigator nav, IList <string> values) { var value = nav.Value; if (value != null) { var s = PrimitiveTypeConverter.ConvertTo <string>(value); values.Add(s); return(true); } return(false); }
public static ComparisonResult IsEqualTo(this IElementNavigator expected, IElementNavigator actual) { if (!valuesEqual(expected.Value, actual.Value)) { return(ComparisonResult.Fail(actual.Location, $"value: was '{actual.Value}', expected '{expected.Value}'")); } if (!namesEqual(expected.Name, actual.Name)) { return(ComparisonResult.Fail(actual.Location, $"name: was '{actual.Name}', expected '{expected.Name}'")); } // Allow the expected navigator to have more type info than the actual navigator if (expected.Type != actual.Type && actual.Type != null) { return(ComparisonResult.Fail(actual.Location, $"type: was '{actual.Type}', expected '{expected.Type}'")); } if (expected.Location != actual.Location) { ComparisonResult.Fail(actual.Location, $"location: was '{actual.Location}', expected '{expected.Location}'"); } // Ignore ordering (only relevant to xml) var childrenExp = expected.Children().OrderBy(e => e.Name).ToArray(); var childrenActual = actual.Children().OrderBy(e => e.Name).ToArray(); if (childrenExp.Length != childrenActual.Length) { ComparisonResult.Fail(actual.Location, $"number of children was {childrenActual.Length}, expected {childrenExp.Length}"); } for (var index = 0; index < childrenExp.Length; index++) { var result = childrenExp[index].IsEqualTo(childrenActual[index]); if (!result.Success) { return(result); } } return(ComparisonResult.OK); bool valuesEqual(object e, object a) { string eVal = e != null?PrimitiveTypeConverter.ConvertTo <string>(e) : null; string aVal = a != null?PrimitiveTypeConverter.ConvertTo <string>(a) : null; return(eVal == aVal); } bool namesEqual(string e, string a) => e == a || (a != null && e != null && (a.StartsWith(e))); }
protected override IEnumerable <ISearchValue> Convert(ITypedElement value) { string stringValue = value.Value?.ToString(); if (stringValue == null) { yield break; } var val = PrimitiveTypeConverter.ConvertTo <DateTimeOffset>(stringValue); yield return(new DateTimeSearchValue(val)); }
public void OnBeforeSerializeComplexType(object instance, IFhirWriter writer) { if (instance is Base b) { var ann = b.Annotation <YadaYadaAnnotation>(); if (ann != null) { writer.WriteStartProperty("yada"); writer.WritePrimitiveContents(PrimitiveTypeConverter.ConvertTo <string>(ann.Num), Introspection.XmlSerializationHint.Attribute); writer.WriteEndProperty(); } } }
private int unmarshal(byte[] buffer, int offset, ITcAdsDataType dataType, out object value) { AdsDatatypeId dataTypeId = dataType.DataTypeId; value = null; int size = dataType.Size; if (!PrimitiveTypeConverter.CanMarshal(dataType.Category)) { throw new MarshalException($"Cannot unmarshal complex type '{dataType.Name}'"); } return(PrimitiveTypeConverter.Default.Unmarshal(dataType, buffer, offset, out value)); }
/// <summary> /// Converts this Fhir DateTime as a .NET DateTimeOffset /// </summary> /// <param name="zone">Ensures the returned DateTimeOffset uses the the specified zone.</param> /// <remarks>In .NET the minimal value for DateTimeOffset is 1/1/0001 12:00:00 AM +00:00. That means,for example, /// a FhirDateTime of "0001-01-01T00:00:00+01:00" could not be converted to a DateTimeOffset. In that case a /// ArgumentOutOfRangeException will be thrown.</remarks> /// <returns>A DateTimeOffset filled out to midnight, january 1 (UTC) in case of a partial date/time. If the Fhir DateTime /// does not specify a timezone, the UTC (Coordinated Universal Time) is assumed. Note that the zone parameter has no /// effect on this, this merely converts the given Fhir datetime to the desired timezone</returns> public DateTimeOffset ToDateTimeOffset(TimeSpan zone) { if (this.Value == null) { throw new InvalidOperationException("FhirDateTime's value is null"); } // ToDateTimeOffset() will convert partial date/times by filling out to midnight/january 1 UTC // When there's no timezone, the UTC is assumed var dto = PrimitiveTypeConverter.ConvertTo <DateTimeOffset>(this.Value); return(dto.ToOffset(zone)); }
public static PartialDateTime FromDateTime(DateTime dt) { #if NETSTANDARD // todo: check equivalence return(new PartialDateTime { _value = XmlConvert.ToString(dt) }); #else return(new PartialDateTime { _value = PrimitiveTypeConverter.ConvertTo <string>(dt) }); #endif }
internal void WritePointerValue(string symbolPath, object value, AdsDatatypeId dataType, int byteSize, AdsBinaryWriter writer, int writerOffset) { if (string.IsNullOrEmpty(symbolPath)) { throw new ArgumentNullException("symbolPath"); } if ((byteSize < 0) || ((byteSize != 4) && (byteSize != 8))) { throw new ArgumentOutOfRangeException("byteSize"); } if (writer == null) { throw new ArgumentNullException("writer"); } if (writerOffset < 0) { throw new ArgumentOutOfRangeException("writerOffset"); } Type targetType = null; if (byteSize == 4) { targetType = typeof(uint); } else if (byteSize == 8) { targetType = typeof(ulong); } if (targetType != value.GetType()) { try { object obj1 = PrimitiveTypeConverter.Convert(value, targetType); value = obj1; } catch (MarshalException exception) { throw new ArgumentException($"Cannot convert value type '{value.GetType()}' to symbol type '{targetType}'!", "value", exception); } } writer.BaseStream.Position = writerOffset; if (byteSize == 4) { writer.Write((uint)value); } else if (byteSize == 8) { writer.Write((ulong)value); } }
public void TestStringToEnum() { Assert.AreEqual(AG.Other, PrimitiveTypeConverter.ConvertTo <AG>("other")); try { PrimitiveTypeConverter.ConvertTo <AG>("otherX"); Assert.Fail(); } catch (NotSupportedException) { // succeeds } }
public bool OnBeforeDeserializeProperty(string name, Base parent, IElementNavigator current) { if (name == "yada") { var num = PrimitiveTypeConverter.ConvertTo <int>(current.Value); parent.AddAnnotation(new YadaYadaAnnotation { Num = num }); return(true); } return(false); }
public static PartialTime Parse(string value) { try { var dummy = PrimitiveTypeConverter.ConvertTo <DateTimeOffset>(toDTOParseable(value)); } catch { throw new FormatException("Time value is in an invalid format, should conform to the time part of ISO8601"); } return(new PartialTime { _value = value }); }
private void AssertConvertToType <T>(string input, T expected, bool expectException) { try { var result = PrimitiveTypeConverter.ConvertTo <T>(input); Assert.IsNotNull(result); Assert.AreEqual(expected, result); } catch (Exception ex) { if (!expectException) { Assert.IsTrue(false, ex.Message); } } }
/// <summary> /// A String representation of the entity that will convert whatever type it is into a string /// (unlike the AsString, which just cases to a string) /// </summary> /// <param name="me"></param> /// <returns></returns> public static string AsStringRepresentation(this IFluentPathValue me) { if (me.Value == null) { return(null); } if (me.Value is PartialDateTime) { return(me.Value.ToString()); } else { return(PrimitiveTypeConverter.ConvertTo <string>(me.Value)); } }
private void AssertConvertToDateTimeOffset(string input, DateTimeOffset?expected, bool expectException) { try { var result = PrimitiveTypeConverter.ConvertTo <DateTimeOffset>(input); Assert.IsNotNull(result); Assert.AreEqual(expected, result); } catch (Exception) { if (!expectException) { Assert.IsTrue(false); } } }
public static bool?ParseBoolParameter(string value) { if (value == null) { return(null); } try { bool b = PrimitiveTypeConverter.ConvertTo <bool>(value); return((bool.TryParse(value, out b)) ? b : default(bool?)); } catch { return(null); } }
private int readArraySize() { int num = 0; IValueSymbol arraySizeSymbol = (IValueSymbol)this.ArraySizeSymbol; if (arraySizeSymbol != null) { try { num = PrimitiveTypeConverter.Convert <int>(arraySizeSymbol.ReadValue()); } catch (Exception) { } } return(num); }