/// <summary> /// Initializes a new instance of the <see cref="UATypeInfo"/> class. /// </summary> /// <param name="builtInType">Type of the built in.</param> /// <param name="valueRank">The value rank.</param> /// <param name="arrayDimensions">The array dimensions.</param> /// <exception cref="System.ArgumentOutOfRangeException">$for {nameof(valueRank)} == {valueRank} {nameof(ArrayDimensions)} must be provided.</exception> public UATypeInfo(BuiltInType builtInType, int valueRank, int[] arrayDimensions) { if ((valueRank == 0 || valueRank > 1) && (arrayDimensions == null || arrayDimensions.Length == 0)) throw new ArgumentOutOfRangeException(nameof(valueRank), $"for {nameof(valueRank)} == {valueRank} {nameof(ArrayDimensions)} must be provided."); m_builtInType = builtInType; m_valueRank = valueRank; m_ArrayDimensionsField = (arrayDimensions == null || arrayDimensions.Length == 0) ? null : (int[])arrayDimensions.Clone(); }
/// <summary> /// Prompts the user to edit an array value. /// </summary> public Array ShowDialog(Array value, BuiltInType dataType, bool readOnly, string caption) { if (caption != null) { this.Text = caption; } // detect the data type. if (dataType == BuiltInType.Null) { dataType = TypeInfo.Construct(value).BuiltInType; } m_dataType = dataType; ArrayDV.AllowUserToAddRows = !readOnly; ArrayDV.AllowUserToDeleteRows = !readOnly; ArrayDV.RowHeadersVisible = !readOnly; m_dataset.Tables[0].Clear(); if (value != null) { for (int ii = 0; ii < value.Length; ii++) { DataRow row = m_dataset.Tables[0].NewRow(); row[0] = new Variant(value.GetValue(ii)).ToString(); row[1] = ii; m_dataset.Tables[0].Rows.Add(row); } } m_dataset.AcceptChanges(); if (ShowDialog() != DialogResult.OK) { return null; } m_dataset.AcceptChanges(); if (!readOnly) { value = TypeInfo.CreateArray(dataType, m_dataset.Tables[0].Rows.Count); for (int ii = 0; ii < m_dataset.Tables[0].DefaultView.Count; ii++) { string oldValue = m_dataset.Tables[0].DefaultView[ii].Row[0] as string; object newValue = TypeInfo.Cast(oldValue, m_dataType); value.SetValue(newValue, ii); } } return value; }
/// <summary> /// Helper method that creates the consumer binding. /// </summary> /// <param name="variableName">Name of the variable.</param> /// <returns>IConsumerBinding.</returns> /// <exception cref="System.ArgumentOutOfRangeException">variableName</exception> public IConsumerBinding GetConsumerBinding(string variableName, BuiltInType encoding) { UATypeInfo _uaTypeInfo = new UATypeInfo(encoding); if (variableName == "Value1") { Value1 = new ConsumerBindingMonitoredValue<string>(_uaTypeInfo); return Value1; } else if (variableName == "Value2") { Value2 = new ConsumerBindingMonitoredValue<double>(_uaTypeInfo); return Value2; } throw new ArgumentOutOfRangeException("variableName"); }
/// <summary> /// Adds a simple field to the declaration. /// </summary> public void AddSimpleField(QualifiedName[] browseNames, NodeClass nodeClass, BuiltInType dataType, int valueRank, bool displayInList) { FilterDeclarationField field = new FilterDeclarationField(); field.DisplayInList = displayInList; field.InstanceDeclaration = new InstanceDeclaration(); field.InstanceDeclaration.NodeClass = nodeClass; if (browseNames != null) { field.InstanceDeclaration.BrowseName = browseNames[browseNames.Length - 1]; field.InstanceDeclaration.BrowsePath = new QualifiedNameCollection(); StringBuilder path = new StringBuilder(); for (int ii = 0; ii < browseNames.Length; ii++) { if (path.Length > 0) { path.Append('/'); } path.Append(browseNames[ii]); field.InstanceDeclaration.BrowsePath.Add(browseNames[ii]); } field.InstanceDeclaration.BrowsePathDisplayText = path.ToString(); } field.InstanceDeclaration.BuiltInType = dataType; field.InstanceDeclaration.DataType = (uint)dataType; field.InstanceDeclaration.ValueRank = valueRank; field.InstanceDeclaration.DataTypeDisplayText = dataType.ToString(); if (valueRank >= 0) { field.InstanceDeclaration.DataTypeDisplayText += "[]"; } field.InstanceDeclaration.DisplayName = field.InstanceDeclaration.BrowseName.Name; field.InstanceDeclaration.DisplayPath = field.InstanceDeclaration.BrowsePathDisplayText; field.InstanceDeclaration.RootTypeId = ObjectTypeIds.BaseEventType; Fields.Add(field); }
public Variant?ShowDialog(Variant value, BuiltInType builtInType) { if (value != Variant.Null) { ValueTB.Text = value.ToString(); } if (ShowDialog() != DialogResult.OK) { return(null); } if (String.IsNullOrEmpty(ValueTB.Text)) { return(Variant.Null); } return(new Variant(TypeInfo.Cast(ValueTB.Text, builtInType))); }
private static bool IsAnalogType(BuiltInType builtInType) { switch (builtInType) { case BuiltInType.Byte: case BuiltInType.UInt16: case BuiltInType.UInt32: case BuiltInType.UInt64: case BuiltInType.SByte: case BuiltInType.Int16: case BuiltInType.Int32: case BuiltInType.Int64: case BuiltInType.Float: case BuiltInType.Double: return(true); } return(false); }
public MosaType GetType(BuiltInType builtInType) { switch (builtInType) { case BuiltInType.Void: return(Void); case BuiltInType.Boolean: return(Boolean); case BuiltInType.Char: return(Char); case BuiltInType.SByte: return(I1); case BuiltInType.Byte: return(U1); case BuiltInType.Int16: return(I2); case BuiltInType.UInt16: return(U2); case BuiltInType.Int32: return(I4); case BuiltInType.UInt32: return(U4); case BuiltInType.Int64: return(I8); case BuiltInType.UInt64: return(U8); case BuiltInType.Single: return(R4); case BuiltInType.Double: return(R8); case BuiltInType.String: return(String); case BuiltInType.Object: return(Object); case BuiltInType.IntPtr: return(I); case BuiltInType.UIntPtr: return(U); case BuiltInType.TypedReference: return(TypedRef); default: throw new CompilerException("Invalid BuildInType"); } }
/// <summary> /// Initializes the buffer with enough space to hold the specified number of elements. /// </summary> /// <param name="elementName">The type of element.</param> /// <param name="noOfElements">The number of elements.</param> public void CreateBuffer(string elementName, int noOfElements) { if (String.IsNullOrEmpty(elementName)) { elementName = "UInt32"; } BuiltInType elementType = BuiltInType.UInt32; switch (elementName) { case "Double": { elementType = BuiltInType.Double; break; } } CreateBuffer(elementType, noOfElements); }
public void VariantArrayFromBuiltInType(BuiltInType builtInType, bool useBoundaryValues) { SetRepeatedRandomSeed(); object randomData = DataGenerator.GetRandomArray(builtInType, useBoundaryValues, 100, false); Variant variant1 = new Variant(randomData); if (builtInType == BuiltInType.Byte) { // Without hint, byte array can not be distinguished from bytestring Assert.AreEqual(BuiltInType.ByteString, variant1.TypeInfo.BuiltInType); } else { Assert.AreEqual(builtInType, variant1.TypeInfo.BuiltInType); } Variant variant2 = new Variant(randomData, new TypeInfo(builtInType, ValueRanks.OneDimension)); Assert.AreEqual(builtInType, variant2.TypeInfo.BuiltInType); }
public Variant? ShowDialog(Variant value, BuiltInType builtInType) { if (value != Variant.Null) { ValueTB.Text = value.ToString(); } if (ShowDialog() != DialogResult.OK) { return null; } if (String.IsNullOrEmpty(ValueTB.Text)) { return Variant.Null; } return new Variant(TypeInfo.Cast(ValueTB.Text, builtInType)); }
internal IProducerBinding GetProducerBinding(string variableName, BuiltInType encoding) { UATypeInfo _uaTypeInfo = new UATypeInfo(encoding); if (variableName == "Value1") { Value1 = new ProducerBindingMonitoredValue <string>(variableName, _uaTypeInfo); return(Value1); } else if (variableName == "Value2") { Value2 = new ProducerBindingMonitoredValue <double>(variableName, _uaTypeInfo); return(Value2); } else { throw new ArgumentOutOfRangeException("variableName"); } }
public void ReEncodeBuiltInType( EncodingType encoderType, BuiltInType builtInType ) { SetRepeatedRandomSeed(); object randomData = null; bool getRandom = true; while (getRandom) { getRandom = false; randomData = DataGenerator.GetRandom(builtInType); // filter a few random special cases to skip // as they test for unsupported objects switch (builtInType) { case BuiltInType.NodeId: var nodeId = (NodeId)randomData; if (nodeId.IdType == IdType.Opaque && ((byte[])nodeId.Identifier).Length == 0) { getRandom = true; } break; case BuiltInType.ExpandedNodeId: var expandedNodeId = (ExpandedNodeId)randomData; if (expandedNodeId.IdType == IdType.Opaque && ((byte[])expandedNodeId.Identifier).Length == 0) { getRandom = true; } break; default: break; } } ; EncodeDecode(encoderType, builtInType, randomData); }
public void EncodeArray( EncodingType encoderType, BuiltInType builtInType ) { Assume.That(builtInType != BuiltInType.Null); int arrayDimension = RandomSource.NextInt32(99) + 1; Array randomData = DataGenerator.GetRandomArray(builtInType, false, arrayDimension, true); string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}"; Type type = TypeInfo.GetSystemType(builtInType, -1); TestContext.Out.WriteLine(encodeInfo); TestContext.Out.WriteLine("Expected:"); TestContext.Out.WriteLine(randomData); var encoderStream = new MemoryStream(); IEncoder encoder = CreateEncoder(encoderType, Context, encoderStream, type, true, false); encoder.WriteArray(builtInType.ToString(), randomData, ValueRanks.OneDimension, builtInType); Dispose(encoder); var buffer = encoderStream.ToArray(); switch (encoderType) { case EncodingType.Json: PrettifyAndValidateJson(Encoding.UTF8.GetString(buffer)); break; } var decoderStream = new MemoryStream(buffer); IDecoder decoder = CreateDecoder(encoderType, Context, decoderStream, type); object result = decoder.ReadArray(builtInType.ToString(), ValueRanks.OneDimension, builtInType); Dispose(decoder); TestContext.Out.WriteLine("Result:"); TestContext.Out.WriteLine(result); object expected = AdjustExpectedBoundaryValues(encoderType, builtInType, randomData); Assert.AreEqual(expected, result, encodeInfo); Assert.IsTrue(Opc.Ua.Utils.IsEqual(expected, result), "Opc.Ua.Utils.IsEqual failed to compare expected and result. " + encodeInfo); }
/// <summary> /// Extracts a BuiltInType value from the line. /// </summary> private bool ExtractField(int lineCount, ref string line, out BuiltInType value) { value = BuiltInType.String; var field = ExtractField(ref line); if (field == null) { return(true); } try { value = (BuiltInType)Enum.Parse(typeof(BuiltInType), field); } catch (Exception e) { Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return(false); } return(true); }
/// <inheritdoc/> public VariantValue Encode(Variant?value, out BuiltInType builtinType) { if (value == null || value == Variant.Null) { builtinType = BuiltInType.Null; return(VariantValue.Null); } using (var stream = new MemoryStream()) { using (var encoder = new JsonEncoderEx(stream, Context) { UseAdvancedEncoding = true }) { encoder.WriteVariant(nameof(value), value.Value); } var token = Serializer.Parse(stream.ToArray()); Enum.TryParse((string)token.GetByPath("value.Type"), true, out builtinType); return(token.GetByPath("value.Body")); } }
private void AddDataGridViewArrayRow(NodeId nodeId, out int index) { DateTime dateTimeStart = DateTime.Now; DataValue[] dataValues = ReadOneNodeFiveAttributes(new List <NodeId>() { nodeId }); label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms"; DataValue dataValue = dataValues[1]; if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension) { string access = GetDiscriptionFromAccessLevel(dataValues[2]); BuiltInType type = dataValue.WrappedValue.TypeInfo.BuiltInType; object des = dataValues[4].Value ?? ""; object dis = dataValues[3].Value ?? type; Array array = dataValue.Value as Array; int i = 0; foreach (object obj in array) { while (i >= dataGridView1.Rows.Count) { dataGridView1.Rows.Add(); } DataGridViewRow dgvr = dataGridView1.Rows[i]; dgvr.Tag = null; dgvr.Cells[0].Value = Properties.Resources.Enum_582; dgvr.Cells[1].Value = $"{dis} [{i++}]"; dgvr.Cells[2].Value = obj; dgvr.Cells[3].Value = type; dgvr.Cells[4].Value = access; dgvr.Cells[5].Value = des; } index = i; } else { index = 0; } }
public static void SetExpectedType(Session session, NodeId nodeId) { try { ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (uint attributeId in new uint[] { Attributes.DataType, Attributes.ValueRank }) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = nodeId; nodeToRead.AttributeId = attributeId; nodesToRead.Add(nodeToRead); } DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); NodeId dataTypeId = results[0].GetValue <NodeId>(null); int valueRank = results[1].GetValue <int>(ValueRanks.Scalar); BuiltInType builtInType = DataTypes.GetBuiltInType(dataTypeId, session.NodeCache.TypeTree); _sourceType = new TypeInfo(builtInType, valueRank); } catch (Exception ex) { _logger.Error(ex, "Error WriteValue method: {0}", ex.Message); throw; } }
/// <summary> /// Encode and decode object, validate result. /// </summary> protected void EncodeDecode( EncodingType encoderType, BuiltInType builtInType, object expected ) { string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}"; Type type = TypeInfo.GetSystemType(builtInType, -1); TestContext.Out.WriteLine(encodeInfo); TestContext.Out.WriteLine("Expected:"); TestContext.Out.WriteLine(expected); var encoderStream = new MemoryStream(); IEncoder encoder = CreateEncoder(encoderType, Context, encoderStream, type); Encode(encoder, builtInType, builtInType.ToString(), expected); Dispose(encoder); var buffer = encoderStream.ToArray(); string jsonFormatted; switch (encoderType) { case EncodingType.Json: jsonFormatted = PrettifyAndValidateJson(Encoding.UTF8.GetString(buffer)); break; } var decoderStream = new MemoryStream(buffer); IDecoder decoder = CreateDecoder(encoderType, Context, decoderStream, type); object result = Decode(decoder, builtInType, builtInType.ToString(), type); Dispose(decoder); TestContext.Out.WriteLine("Result:"); TestContext.Out.WriteLine(result); expected = AdjustExpectedBoundaryValues(encoderType, builtInType, expected); if (BuiltInType.DateTime == builtInType) { expected = Utils.ToOpcUaUniversalTime((DateTime)expected); } Assert.AreEqual(expected, result, encodeInfo); Assert.IsTrue(Opc.Ua.Utils.IsEqual(expected, result), "Opc.Ua.Utils.IsEqual failed to compare expected and result. " + encodeInfo); }
/// <summary> /// Encode and decode a DataValue, /// validate the result against the input data. /// </summary> protected void EncodeDecodeDataValue( EncodingType encoderType, BuiltInType builtInType, object data ) { string encodeInfo = $"Encoder: {encoderType} Type:{builtInType}"; TestContext.Out.WriteLine(encodeInfo); TestContext.Out.WriteLine(data); DataValue expected = CreateDataValue(builtInType, data); Assert.IsNotNull(expected, "Expected DataValue is Null, " + encodeInfo); TestContext.Out.WriteLine("Expected:"); TestContext.Out.WriteLine(expected); var encoderStream = new MemoryStream(); IEncoder encoder = CreateEncoder(encoderType, Context, encoderStream, typeof(DataValue)); encoder.WriteDataValue("DataValue", expected); Dispose(encoder); var buffer = encoderStream.ToArray(); string jsonFormatted; switch (encoderType) { case EncodingType.Json: jsonFormatted = PrettifyAndValidateJson(Encoding.UTF8.GetString(buffer)); break; } var decoderStream = new MemoryStream(buffer); IDecoder decoder = CreateDecoder(encoderType, Context, decoderStream, typeof(DataValue)); DataValue result = decoder.ReadDataValue("DataValue"); Dispose(decoder); TestContext.Out.WriteLine("Result:"); TestContext.Out.WriteLine(result); Assert.IsNotNull(result, "Resulting DataValue is Null, " + encodeInfo); expected.Value = AdjustExpectedBoundaryValues(encoderType, builtInType, expected.Value); Assert.AreEqual(expected, result, encodeInfo); Assert.IsTrue(Utils.IsEqual(expected, result), "Opc.Ua.Utils.IsEqual failed to compare expected and result. " + encodeInfo); }
public VariableInfo(NodeId nodeId, string displayName, BuiltInType builtInType) { InitializeClass(nodeId, displayName); object defaultValue; switch (builtInType) { case BuiltInType.String: defaultValue = ""; break; default: defaultValue = TypeInfo.GetDefaultValue(builtInType); break; } var typeInfo = TypeInfo.Construct(defaultValue); var dv = new DataValue(new Variant(defaultValue, typeInfo), StatusCodes.BadWaitingForInitialData); NewDataValue(dv); }
/// <inheritdoc/> public Variant Decode(JToken value, BuiltInType builtinType, ServiceMessageContext context) { // // Sanitize json input from user // value = Sanitize(value, builtinType == BuiltInType.String); JObject json; if (builtinType == BuiltInType.Null || (builtinType == BuiltInType.Variant && value is JObject)) { // // Let the decoder try and decode the json variant. // json = new JObject { { nameof(value), value } }; } else { // // Give decoder a hint as to the type to use to decode. // json = new JObject { { nameof(value), new JObject { { "Body", value }, { "Type", (byte)builtinType } } } }; } // // Decode json to a real variant // using (var decoder = new JsonDecoderEx(json, context ?? Context)) { return(decoder.ReadVariant(nameof(value))); } }
/// <summary> /// Converts a UA value to something the DA server will accept. /// </summary> private static object LocalToRemoteValue(object srcValue, BuiltInType srcType, BuiltInType dstType) { if (srcType <= BuiltInType.DateTime) { return(srcValue); } if (srcType == BuiltInType.Variant) { TypeInfo typeInfo = TypeInfo.Construct(srcValue); srcType = typeInfo.BuiltInType; if (typeInfo.ValueRank != ValueRanks.Scalar) { return(TypeInfo.CastArray((Array)srcValue, srcType, BuiltInType.Null, LocalToRemoteValue)); } return(LocalToRemoteValue(srcValue, srcType, dstType)); } throw new ServiceResultException(StatusCodes.BadTypeMismatch); }
/// <summary> /// Returns the expected data type. /// </summary> private TypeInfo GetExpectedType(Session session, NodeId nodeId) { // build list of attributes to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (uint attributeId in new uint[] { Attributes.DataType, Attributes.ValueRank }) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = nodeId; nodeToRead.AttributeId = attributeId; nodesToRead.Add(nodeToRead); } // read the attributes. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); // this call checks for error and checks the data type of the value. // if an error or mismatch occurs the default value is returned. NodeId dataTypeId = results[0].GetValue <NodeId>(null); int valueRank = results[1].GetValue <int>(ValueRanks.Scalar); // use the local type cache to look up the base type for the data type. BuiltInType builtInType = DataTypes.GetBuiltInType(dataTypeId, session.NodeCache.TypeTree); // the type info object is used in cast and compare functions. return(new TypeInfo(builtInType, valueRank)); }
/// <summary> /// Reads an instance of <see cref="IVariant" /> from UA Binary encoded stream. /// </summary> /// <param name="decoder">The decoder <see cref="IBinaryDecoder" /> to be used to read form the stream.</param> /// <returns>The <see cref="IVariant" /> decoded from the UA binary stream of bytes.</returns> public IVariant ReadVariant(IBinaryDecoder decoder) { byte encodingByte = decoder.ReadByte(); //Read the EncodingMask if (encodingByte == 0x0) { return(null); } Variant value = null; BuiltInType builtInType = (BuiltInType)(encodingByte & (byte)VariantEncodingMask.TypeIdMask); if ((encodingByte & (byte)VariantEncodingMask.IsArray) == 0) { value = ReadValue(decoder, builtInType); } else { Array array = DecodeArray(decoder, builtInType, ((encodingByte & (byte)VariantEncodingMask.ArrayDimensionsPresents) != 0)); value = new Variant(array, builtInType); } return(value); }
/// <summary> /// Initializes the buffer from the configuration. /// </summary> public MemoryBufferState(ISystemContext context, MemoryBufferInstance configuration) : base(null) { Initialize(context); string dataType = "UInt32"; string name = dataType; int count = 10; if (configuration != null) { count = configuration.TagCount; if (!String.IsNullOrEmpty(configuration.DataType)) { dataType = configuration.DataType; } if (!String.IsNullOrEmpty(configuration.Name)) { name = dataType; } } this.SymbolicName = name; BuiltInType elementType = BuiltInType.UInt32; switch (dataType) { case "Double": { elementType = BuiltInType.Double; break; } } CreateBuffer(elementType, count); }
private string ToString(BuiltInType encoding, type value) { switch (encoding) { case BuiltInType.Null: case BuiltInType.Boolean: case BuiltInType.SByte: case BuiltInType.Byte: case BuiltInType.Int16: case BuiltInType.UInt16: case BuiltInType.Int32: case BuiltInType.UInt32: case BuiltInType.Int64: case BuiltInType.UInt64: case BuiltInType.Float: case BuiltInType.Double: case BuiltInType.String: case BuiltInType.DateTime: case BuiltInType.Guid: case BuiltInType.XmlElement: case BuiltInType.NodeId: case BuiltInType.ExpandedNodeId: case BuiltInType.StatusCode: case BuiltInType.QualifiedName: case BuiltInType.LocalizedText: case BuiltInType.ExtensionObject: case BuiltInType.DataValue: case BuiltInType.Variant: case BuiltInType.DiagnosticInfo: case BuiltInType.Enumeration: return(value.ToString()); case BuiltInType.ByteString: byte[] _value = (byte[])(object)value; return($"[{String.Join(", ", new ArraySegment<byte>(_value, 0, Math.Min(_value.Length, 80)).Select<byte, string>(x => x.ToString("X")).ToArray<string>())}]"); } return(base.ToString()); }
/// <summary> /// Gets the local type info. /// </summary> /// <param name="remoteType">The remote type info.</param> /// <returns>The local type info.</returns> private TypeInfo GetLocalTypeInfo(TypeInfo remoteType) { BuiltInType localBuiltInType = BuiltInType.Null; switch (remoteType.BuiltInType) { case BuiltInType.Guid: case BuiltInType.XmlElement: case BuiltInType.NodeId: case BuiltInType.ExpandedNodeId: case BuiltInType.QualifiedName: case BuiltInType.LocalizedText: { localBuiltInType = BuiltInType.String; break; } case BuiltInType.StatusCode: { localBuiltInType = BuiltInType.UInt32; break; } case BuiltInType.ExtensionObject: { localBuiltInType = BuiltInType.ByteString; break; } default: { localBuiltInType = remoteType.BuiltInType; break; } } return(new TypeInfo(localBuiltInType, remoteType.ValueRank)); }
private static Opc.Ua.Range GetAnalogRange(BuiltInType builtInType) { switch (builtInType) { case BuiltInType.UInt16: return(new Opc.Ua.Range(System.UInt16.MaxValue, System.UInt16.MinValue)); case BuiltInType.UInt32: return(new Opc.Ua.Range(System.UInt32.MaxValue, System.UInt32.MinValue)); case BuiltInType.UInt64: return(new Opc.Ua.Range(System.UInt64.MaxValue, System.UInt64.MinValue)); case BuiltInType.SByte: return(new Opc.Ua.Range(System.SByte.MaxValue, System.SByte.MinValue)); case BuiltInType.Int16: return(new Opc.Ua.Range(System.Int16.MaxValue, System.Int16.MinValue)); case BuiltInType.Int32: return(new Opc.Ua.Range(System.Int32.MaxValue, System.Int32.MinValue)); case BuiltInType.Int64: return(new Opc.Ua.Range(System.Int64.MaxValue, System.Int64.MinValue)); case BuiltInType.Float: return(new Opc.Ua.Range(System.Single.MaxValue, System.Single.MinValue)); case BuiltInType.Double: return(new Opc.Ua.Range(System.Double.MaxValue, System.Double.MinValue)); case BuiltInType.Byte: return(new Opc.Ua.Range(System.Byte.MaxValue, System.Byte.MinValue)); default: return(new Opc.Ua.Range(System.SByte.MaxValue, System.SByte.MinValue)); } }
public void ReEncodeBuiltInTypeDefaultValue( EncodingType encoderType, BuiltInType builtInType ) { object randomData = TypeInfo.GetDefaultValue(builtInType); switch (builtInType) { case BuiltInType.Number: case BuiltInType.Integer: case BuiltInType.UInteger: randomData = new Variant(randomData); break; // special case for extension object, default from TypeInfo must be null // or encoding of extension objects fails. case BuiltInType.ExtensionObject: randomData = ExtensionObject.Null; break; } EncodeDecode(encoderType, builtInType, randomData); }
/// <summary> /// Adjust expected values to encoder specific results. /// </summary> protected object AdjustExpectedBoundaryValues(EncodingType encoderType, BuiltInType builtInType, object value) { if (value == null) { return(value); } if (encoderType == EncodingType.Binary) { if (builtInType == BuiltInType.DateTime || builtInType == BuiltInType.Variant) { if (value.GetType() == typeof(DateTime)) { value = AdjustExpectedDateTimeBinaryEncoding((DateTime)value); } if (value.GetType() == typeof(DateTime[])) { DateTime[] valueArray = (DateTime[])value; for (int i = 0; i < valueArray.Length; i++) { valueArray[i] = AdjustExpectedDateTimeBinaryEncoding(valueArray[i]); } } } if (builtInType == BuiltInType.DataValue) { DataValue dataValue = (DataValue)value; if (dataValue.Value?.GetType() == typeof(DateTime) || dataValue.Value?.GetType() == typeof(DateTime[])) { dataValue.Value = AdjustExpectedBoundaryValues(encoderType, BuiltInType.DateTime, dataValue.Value); return(dataValue); } } } return(value); }
public Variant(object value, BuiltInType type) : this(value, new UATypeInfo(type)) { }
private DataItemState CreateAnalogItemVariable(NodeState parent, string path, string name, BuiltInType dataType, int valueRank, object initialValues, Range customRange) { return CreateAnalogItemVariable(parent, path, name, (uint)dataType, valueRank, initialValues, customRange); }
/// <summary> /// Converts a value to a Double /// </summary> private static object ToDouble(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { double[] output = new double[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (double)Cast(array.GetValue(ii), BuiltInType.Double); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.Double: { return (double)value; } case BuiltInType.Boolean: return Convert.ToDouble((bool)value); case BuiltInType.SByte: return Convert.ToDouble((sbyte)value); case BuiltInType.Byte: return Convert.ToDouble((byte)value); case BuiltInType.Int16: return Convert.ToDouble((short)value); case BuiltInType.UInt16: return Convert.ToDouble((ushort)value); case BuiltInType.Int32: return Convert.ToDouble((int)value); case BuiltInType.UInt32: return Convert.ToDouble((uint)value); case BuiltInType.Int64: return Convert.ToDouble((long)value); case BuiltInType.UInt64: return Convert.ToDouble((ulong)value); case BuiltInType.Float: return Convert.ToDouble((float)value); case BuiltInType.String: { return XmlConvert.ToDouble((string)value); } } // conversion not supported. return DBNull.Value; }
/// <summary> /// Returns the data type precedence for the value. /// </summary> private static int GetDataTypePrecedence(BuiltInType type) { switch (type) { case BuiltInType.Double: { return 18; } case BuiltInType.Float: { return 17; } case BuiltInType.Int64: { return 16; } case BuiltInType.UInt64: { return 15; } case BuiltInType.Int32: { return 14; } case BuiltInType.UInt32: { return 13; } case BuiltInType.StatusCode: { return 12; } case BuiltInType.Int16: { return 11; } case BuiltInType.UInt16: { return 10; } case BuiltInType.SByte: { return 9; } case BuiltInType.Byte: { return 8; } case BuiltInType.Boolean: { return 7; } case BuiltInType.Guid: { return 6; } case BuiltInType.String: { return 5; } case BuiltInType.ExpandedNodeId: { return 4; } case BuiltInType.NodeId: { return 3; } case BuiltInType.LocalizedText: { return 2; } case BuiltInType.QualifiedName: { return 1; } } return 0; }
/// <summary> /// Casts a value to the specified target type. /// </summary> private static object Cast(object source, BuiltInType targetType) { BuiltInType sourceType = GetBuiltInType(source); if (sourceType == BuiltInType.Null) { return null; } return Cast(source, sourceType, targetType); }
/// <summary> /// Converts a value to a QualifiedName /// </summary> private static object ToQualifiedName(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { QualifiedName[] output = new QualifiedName[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (QualifiedName)Cast(array.GetValue(ii), BuiltInType.QualifiedName); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.QualifiedName: { return (QualifiedName)value; } case BuiltInType.String: { return QualifiedName.Parse((string)value); } } // conversion not supported. return null; }
/// <summary> /// Converts a value to a ExpandedNodeId /// </summary> private static object ToExpandedNodeId(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { ExpandedNodeId[] output = new ExpandedNodeId[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (ExpandedNodeId)Cast(array.GetValue(ii), BuiltInType.ExpandedNodeId); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.ExpandedNodeId: { return (ExpandedNodeId)value; } case BuiltInType.NodeId: { return (ExpandedNodeId)(NodeId)value; } case BuiltInType.String: { return ExpandedNodeId.Parse((string)value); } } // conversion not supported. return null; }
/// <summary> /// Initializes a new instance of the <see cref="UATypeInfo"/> class representing <see cref="BuiltInType"/> and value rank. /// </summary> /// <param name="builtInType">Type of the an OPC UA entity.</param> /// <param name="valueRank">The value rank.</param> public UATypeInfo(BuiltInType builtInType, int valueRank) : this(builtInType, valueRank, null) { }
/// <summary> /// Initializes a new instance of the <see cref="UATypeInfo"/> class representing <see cref="BuiltInType"/> and value rank. /// </summary> /// <param name="builtInType">Type of the an OPC UA entity.</param> public UATypeInfo(BuiltInType builtInType) : this(builtInType, ValueRanks.Scalar) { }
public UATypeInfo() { m_builtInType = BuiltInType.Null; m_valueRank = ValueRanks.Any; }
/// <summary> /// Checks if the datatype id is a built-in type. /// </summary> private bool IsBuiltInType(ExpandedNodeId nodeId, out BuiltInType builtinType) { builtinType = BuiltInType.Null; if (nodeId.IsAbsolute || nodeId.NamespaceIndex != 0 || nodeId.IdType != IdType.Numeric) { return false; } uint id = (uint)nodeId.Identifier; if (id > 0 && id <= DataTypes.BaseDataType) { builtinType = (BuiltInType)(int)id; return true; } switch (id) { case DataTypes.Enumeration: { builtinType = BuiltInType.Int32; break; } case DataTypes.Number: { builtinType = BuiltInType.Double; break; } case DataTypes.Integer: { builtinType = BuiltInType.Int64; break; } case DataTypes.UInteger: { builtinType = BuiltInType.UInt64; break; } default: { return false; } } return true; }
/// <summary> /// Converts a UA value to something the DA server will accept. /// </summary> private static object LocalToRemoteValue(object srcValue, BuiltInType srcType, BuiltInType dstType) { if (srcType <= BuiltInType.DateTime) { return srcValue; } if (srcType == BuiltInType.Variant) { TypeInfo typeInfo = TypeInfo.Construct(srcValue); srcType = typeInfo.BuiltInType; if (typeInfo.ValueRank != ValueRanks.Scalar) { return TypeInfo.CastArray((Array)srcValue, srcType, BuiltInType.Null, LocalToRemoteValue); } return LocalToRemoteValue(srcValue, srcType, dstType); } throw new ServiceResultException(StatusCodes.BadTypeMismatch); }
/// <summary> /// Converts a value to a StatusCode /// </summary> private static object ToStatusCode(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { StatusCode[] output = new StatusCode[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (StatusCode)Cast(array.GetValue(ii), BuiltInType.StatusCode); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.StatusCode: { return (StatusCode)value; } case BuiltInType.UInt16: { uint code = Convert.ToUInt32((ushort)value); code <<= 16; return (StatusCode)code; } case BuiltInType.Int32: { return (StatusCode)Convert.ToUInt32((int)value); } case BuiltInType.UInt32: { return (StatusCode)(uint)value; } case BuiltInType.Int64: { return (StatusCode)Convert.ToUInt32((long)value); } case BuiltInType.UInt64: { return (StatusCode)Convert.ToUInt32((ulong)value); } } // conversion not supported. return null; }
/// <summary> /// Converts a value to something the UA client can accept. /// </summary> private static object RemoteToLocalValue(object srcValue, BuiltInType srcType, BuiltInType dstType) { if (typeof(decimal).IsInstanceOfType(srcValue)) { return ((decimal)srcValue).ToString(); } if (typeof(decimal[]).IsInstanceOfType(srcValue)) { return TypeInfo.CastArray((Array)srcValue, BuiltInType.Null, BuiltInType.String, RemoteToLocalValue); } return srcValue; }
/// <summary> /// Converts a value to a LocalizedText /// </summary> private static object ToLocalizedText(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { LocalizedText[] output = new LocalizedText[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (LocalizedText)Cast(array.GetValue(ii), BuiltInType.LocalizedText); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.LocalizedText: { return (LocalizedText)value; } case BuiltInType.String: { return new LocalizedText((string)value); } } // conversion not supported. return null; }
private Variant ReadVariantArrayBody(string fieldName, BuiltInType type) { switch (type) { case BuiltInType.Boolean: { return new Variant(ReadBooleanArray(fieldName), TypeInfo.Arrays.Boolean); } case BuiltInType.SByte: { return new Variant(ReadSByteArray(fieldName), TypeInfo.Arrays.SByte); } case BuiltInType.Byte: { return new Variant(ReadByteArray(fieldName), TypeInfo.Arrays.Byte); } case BuiltInType.Int16: { return new Variant(ReadInt16Array(fieldName), TypeInfo.Arrays.Int16); } case BuiltInType.UInt16: { return new Variant(ReadUInt16Array(fieldName), TypeInfo.Arrays.UInt16); } case BuiltInType.Int32: { return new Variant(ReadInt32Array(fieldName), TypeInfo.Arrays.Int32); } case BuiltInType.UInt32: { return new Variant(ReadUInt32Array(fieldName), TypeInfo.Arrays.UInt32); } case BuiltInType.Int64: { return new Variant(ReadInt64Array(fieldName), TypeInfo.Arrays.Int64); } case BuiltInType.UInt64: { return new Variant(ReadUInt64Array(fieldName), TypeInfo.Arrays.UInt64); } case BuiltInType.Float: { return new Variant(ReadFloatArray(fieldName), TypeInfo.Arrays.Float); } case BuiltInType.Double: { return new Variant(ReadDoubleArray(fieldName), TypeInfo.Arrays.Double); } case BuiltInType.String: { return new Variant(ReadStringArray(fieldName), TypeInfo.Arrays.String); } case BuiltInType.ByteString: { return new Variant(ReadByteStringArray(fieldName), TypeInfo.Arrays.ByteString); } case BuiltInType.DateTime: { return new Variant(ReadDateTimeArray(fieldName), TypeInfo.Arrays.DateTime); } case BuiltInType.Guid: { return new Variant(ReadGuidArray(fieldName), TypeInfo.Arrays.Guid); } case BuiltInType.NodeId: { return new Variant(ReadNodeIdArray(fieldName), TypeInfo.Arrays.NodeId); } case BuiltInType.ExpandedNodeId: { return new Variant(ReadExpandedNodeIdArray(fieldName), TypeInfo.Arrays.ExpandedNodeId); } case BuiltInType.QualifiedName: { return new Variant(ReadQualifiedNameArray(fieldName), TypeInfo.Arrays.QualifiedName); } case BuiltInType.LocalizedText: { return new Variant(ReadLocalizedTextArray(fieldName), TypeInfo.Arrays.LocalizedText); } case BuiltInType.StatusCode: { return new Variant(ReadStatusCodeArray(fieldName), TypeInfo.Arrays.StatusCode); } case BuiltInType.XmlElement: { return new Variant(ReadXmlElementArray(fieldName), TypeInfo.Arrays.XmlElement); } case BuiltInType.ExtensionObject: { return new Variant(ReadExtensionObjectArray(fieldName), TypeInfo.Arrays.ExtensionObject); } case BuiltInType.Variant: { return new Variant(ReadVariantArray(fieldName), TypeInfo.Arrays.Variant); } } return Variant.Null; }
/// <summary> /// Casts a value to the specified target type. /// </summary> private static object Cast(object source, BuiltInType sourceType, BuiltInType targetType) { // null always casts to null. if (source == null) { return null; } // extract the value from a Variant if specified. if (source is Variant) { return Cast(((Variant)source).Value, targetType); } // call the appropriate function if a conversion is supported for the target type. try { switch (targetType) { case BuiltInType.Boolean: return ToBoolean(source, sourceType); case BuiltInType.SByte: return ToSByte(source, sourceType); case BuiltInType.Byte: return ToByte(source, sourceType); case BuiltInType.Int16: return ToInt16(source, sourceType); case BuiltInType.UInt16: return ToUInt16(source, sourceType); case BuiltInType.Int32: return ToInt32(source, sourceType); case BuiltInType.UInt32: return ToUInt32(source, sourceType); case BuiltInType.Int64: return ToInt64(source, sourceType); case BuiltInType.UInt64: return ToUInt64(source, sourceType); case BuiltInType.Float: return ToFloat(source, sourceType); case BuiltInType.Double: return ToDouble(source, sourceType); case BuiltInType.String: return ToString(source, sourceType); case BuiltInType.DateTime: return ToDateTime(source, sourceType); case BuiltInType.Guid: return ToGuid(source, sourceType); case BuiltInType.ByteString: return ToByteString(source, sourceType); case BuiltInType.NodeId: return ToNodeId(source, sourceType); case BuiltInType.ExpandedNodeId: return ToExpandedNodeId(source, sourceType); case BuiltInType.StatusCode: return ToStatusCode(source, sourceType); case BuiltInType.QualifiedName: return ToQualifiedName(source, sourceType); case BuiltInType.LocalizedText: return ToLocalizedText(source, sourceType); } } catch (Exception e) { Utils.Trace(e, "Error converting a {1} (Value={0}) to {2}.", source, sourceType, targetType); } // conversion not supported. return null; }
/// <summary> /// Initializes the buffer with enough space to hold the specified number of elements. /// </summary> /// <param name="elementType">The type of element.</param> /// <param name="noOfElements">The number of elements.</param> public void CreateBuffer(BuiltInType elementType, int noOfElements) { lock (m_dataLock) { m_elementType = elementType; m_elementSize = 1; switch (m_elementType) { case BuiltInType.UInt32: { m_elementSize = 4; break; } case BuiltInType.Double: { m_elementSize = 8; break; } } m_lastScanTime = DateTime.UtcNow; m_maximumScanRate = 1000; m_buffer = new byte[m_elementSize * noOfElements]; SizeInBytes.Value = (uint)m_buffer.Length; } }
/// <summary> /// Converts a value to a Byte /// </summary> private static object ToByte(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { throw new NotImplementedException("Arrays of Byte not supported. Use ByteString instead."); } // handle for supported conversions. switch (sourceType) { case BuiltInType.Byte: { return (byte)value; } case BuiltInType.Boolean: return Convert.ToByte((bool)value); case BuiltInType.SByte: return Convert.ToByte((sbyte)value); case BuiltInType.Int16: return Convert.ToByte((short)value); case BuiltInType.UInt16: return Convert.ToByte((ushort)value); case BuiltInType.Int32: return Convert.ToByte((int)value); case BuiltInType.UInt32: return Convert.ToByte((uint)value); case BuiltInType.Int64: return Convert.ToByte((long)value); case BuiltInType.UInt64: return Convert.ToByte((ulong)value); case BuiltInType.Float: return Convert.ToByte((float)value); case BuiltInType.Double: return Convert.ToByte((double)value); case BuiltInType.String: { return XmlConvert.ToByte((string)value); } } // conversion not supported. return DBNull.Value; }
/// <summary> /// Changes the data type. /// </summary> public void SetType(BuiltInType builtInType) { if (!CanChangeType) { return; } AccessInfo info = NavigationMENU.Items[NavigationMENU.Items.Count - 1].Tag as AccessInfo; TypeInfo currentType = info.TypeInfo; object currentValue = info.Value; try { EndEdit(); currentValue = info.Value; } catch (Exception) { currentValue = TypeInfo.GetDefaultValue(currentType.BuiltInType); } if (info.Value is Variant) { Variant variant = (Variant)info.Value; currentValue = variant.Value; if (currentValue != null) { currentType = variant.TypeInfo; if (currentType == null) { currentType = TypeInfo.Construct(currentValue); } } } TypeInfo targetType = new TypeInfo(builtInType, currentType.ValueRank); object newValue = Convert(currentValue, currentType, targetType, true); NavigationMENU.Items.RemoveAt(NavigationMENU.Items.Count - 1); info.TypeInfo = targetType; info.Value = newValue; ShowValueNoNotify(info); }
/// <summary> /// Converts a value to a String /// </summary> private static object ToString(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { String[] output = new String[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (String)Cast(array.GetValue(ii), BuiltInType.String); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.String: { return (string)value; } case BuiltInType.Boolean: { return XmlConvert.ToString((bool)value); } case BuiltInType.SByte: { return XmlConvert.ToString((sbyte)value); } case BuiltInType.Byte: { return XmlConvert.ToString((byte)value); } case BuiltInType.Int16: { return XmlConvert.ToString((short)value); } case BuiltInType.UInt16: { return XmlConvert.ToString((ushort)value); } case BuiltInType.Int32: { return XmlConvert.ToString((int)value); } case BuiltInType.UInt32: { return XmlConvert.ToString((uint)value); } case BuiltInType.Int64: { return XmlConvert.ToString((long)value); } case BuiltInType.UInt64: { return XmlConvert.ToString((ulong)value); } case BuiltInType.Float: { return XmlConvert.ToString((float)value); } case BuiltInType.Double: { return XmlConvert.ToString((double)value); } case BuiltInType.DateTime: { return XmlConvert.ToString((DateTime)value, XmlDateTimeSerializationMode.Unspecified); } case BuiltInType.Guid: { return ((Guid)value).ToString(); } case BuiltInType.NodeId: { return ((NodeId)value).ToString(); } case BuiltInType.ExpandedNodeId: { return ((ExpandedNodeId)value).ToString(); } case BuiltInType.LocalizedText: { return ((LocalizedText)value).Text; } case BuiltInType.QualifiedName: { return ((QualifiedName)value).ToString(); } } // conversion not supported. return DBNull.Value; }
/// <summary> /// Creates a new variable type. /// </summary> private BaseVariableTypeState CreateVariableType(NodeState parent, IDictionary<NodeId, IList<IReference>> externalReferences, string path, string name, BuiltInType dataType, int valueRank) { BaseDataVariableTypeState type = new BaseDataVariableTypeState(); type.SymbolicName = name; type.SuperTypeId = VariableTypeIds.BaseDataVariableType; type.NodeId = new NodeId(path, NamespaceIndex); type.BrowseName = new QualifiedName(name, NamespaceIndex); type.DisplayName = type.BrowseName.Name; type.WriteMask = AttributeWriteMask.None; type.UserWriteMask = AttributeWriteMask.None; type.IsAbstract = false; type.DataType = (uint)dataType; type.ValueRank = valueRank; type.Value = null; IList<IReference> references = null; if (!externalReferences.TryGetValue(VariableTypeIds.BaseDataVariableType, out references)) { externalReferences[VariableTypeIds.BaseDataVariableType] = references = new List<IReference>(); } references.Add(new NodeStateReference(ReferenceTypes.HasSubtype, false, type.NodeId)); if (parent != null) { parent.AddReference(ReferenceTypes.Organizes, false, type.NodeId); type.AddReference(ReferenceTypes.Organizes, true, parent.NodeId); } AddPredefinedNode(SystemContext, type); return type; }
private DataItemState CreateAnalogItemVariable(NodeState parent, string path, string name, BuiltInType dataType, int valueRank, object initialValues) { return (CreateAnalogItemVariable(parent, path, name, dataType, valueRank, initialValues, null)); }
private BaseDataVariableState[] CreateDynamicVariables(NodeState parent, string path, string name, BuiltInType dataType, int valueRank, uint numVariables) { return CreateDynamicVariables(parent, path, name, (uint)dataType, valueRank, numVariables); }
public Variant(Array value, BuiltInType type) : this(value, new UATypeInfo(type, value.Rank)) { }
/// <summary> /// Creates a new variable. /// </summary> private BaseDataVariableState CreateVariable(NodeState parent, string path, string name, BuiltInType dataType, int valueRank) { return CreateVariable(parent, path, name, (uint)dataType, valueRank); }
//methods private Variant ReadValue(IBinaryDecoder encoder, BuiltInType encodingByte) { switch (encodingByte) { case BuiltInType.Boolean: return(new Variant(encoder.ReadBoolean(), encodingByte)); case BuiltInType.SByte: return(new Variant(encoder.ReadSByte(), encodingByte)); case BuiltInType.Byte: return(new Variant(encoder.ReadByte(), encodingByte)); case BuiltInType.Int16: return(new Variant(encoder.ReadInt16(), encodingByte)); case BuiltInType.UInt16: return(new Variant(encoder.ReadUInt16(), encodingByte)); case BuiltInType.Int32: case BuiltInType.Enumeration: return(new Variant(encoder.ReadInt32(), encodingByte)); case BuiltInType.UInt32: return(new Variant(encoder.ReadUInt32(), encodingByte)); case BuiltInType.Int64: return(new Variant(encoder.ReadInt64(), encodingByte)); case BuiltInType.UInt64: return(new Variant(encoder.ReadUInt64(), encodingByte)); case BuiltInType.Float: return(new Variant(encoder.ReadSingle(), encodingByte)); case BuiltInType.Double: return(new Variant(encoder.ReadDouble(), encodingByte)); case BuiltInType.String: return(new Variant(ReadString(encoder), encodingByte)); case BuiltInType.DateTime: return(new Variant(ReadDateTime(encoder), encodingByte)); case BuiltInType.Guid: return(new Variant(ReadGuid(encoder), encodingByte)); case BuiltInType.ByteString: return(new Variant(ReadByteString(encoder), encodingByte)); case BuiltInType.XmlElement: return(new Variant(ReadXmlElement(encoder), encodingByte)); case BuiltInType.NodeId: return(new Variant(ReadNodeId(encoder), encodingByte)); case BuiltInType.ExpandedNodeId: return(new Variant(ReadExpandedNodeId(encoder), encodingByte)); case BuiltInType.StatusCode: return(new Variant(ReadStatusCode(encoder), encodingByte)); case BuiltInType.QualifiedName: return(new Variant(ReadQualifiedName(encoder), encodingByte)); case BuiltInType.LocalizedText: return(new Variant(ReadLocalizedText(encoder), encodingByte)); case BuiltInType.ExtensionObject: return(new Variant(ReadExtensionObject(encoder), encodingByte)); case BuiltInType.DataValue: return(new Variant(ReadDataValue(encoder), encodingByte)); default: throw new ArgumentOutOfRangeException($"Cannot decode unknown type in Variant object (0x{encodingByte:X})."); } }
/// <summary> /// Converts a value to a DateTime /// </summary> private static object ToDateTime(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { DateTime[] output = new DateTime[array.Length]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (DateTime)Cast(array.GetValue(ii), BuiltInType.DateTime); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.DateTime: { return (DateTime)value; } case BuiltInType.String: { return XmlConvert.ToDateTimeOffset((string) value); } } // conversion not supported. return null; }
private Array DecodeArray(IBinaryDecoder decoder, BuiltInType builtInType, bool arrayDimensionsPresents) { switch (builtInType) { case BuiltInType.Boolean: return(DecodeArray <bool>(decoder, decoder.ReadBoolean, arrayDimensionsPresents)); case BuiltInType.SByte: return(DecodeArray <sbyte>(decoder, decoder.ReadSByte, arrayDimensionsPresents)); case BuiltInType.Byte: return(DecodeArray <byte>(decoder, decoder.ReadByte, arrayDimensionsPresents)); case BuiltInType.Int16: return(DecodeArray <short>(decoder, decoder.ReadInt16, arrayDimensionsPresents)); case BuiltInType.UInt16: return(DecodeArray <ushort>(decoder, decoder.ReadUInt16, arrayDimensionsPresents)); case BuiltInType.Int32: case BuiltInType.Enumeration: return(DecodeArray <int>(decoder, decoder.ReadInt32, arrayDimensionsPresents)); case BuiltInType.UInt32: return(DecodeArray <uint>(decoder, decoder.ReadUInt32, arrayDimensionsPresents)); case BuiltInType.Int64: return(DecodeArray <long>(decoder, decoder.ReadInt64, arrayDimensionsPresents)); case BuiltInType.UInt64: return(DecodeArray <ulong>(decoder, decoder.ReadUInt64, arrayDimensionsPresents)); case BuiltInType.Float: return(DecodeArray <float>(decoder, decoder.ReadSingle, arrayDimensionsPresents)); case BuiltInType.Double: return(DecodeArray <double>(decoder, decoder.ReadDouble, arrayDimensionsPresents)); case BuiltInType.String: return(DecodeArray <string>(decoder, () => ReadString(decoder), arrayDimensionsPresents)); case BuiltInType.DateTime: return(DecodeArray <DateTime>(decoder, () => ReadDateTime(decoder), arrayDimensionsPresents)); case BuiltInType.Guid: return(DecodeArray <Guid>(decoder, () => ReadGuid(decoder), arrayDimensionsPresents)); case BuiltInType.ByteString: return(DecodeArray <byte[]>(decoder, () => ReadByteString(decoder), arrayDimensionsPresents)); case BuiltInType.XmlElement: return(DecodeArray <XmlElement>(decoder, () => ReadXmlElement(decoder), arrayDimensionsPresents)); case BuiltInType.NodeId: return(DecodeArray <INodeId>(decoder, () => ReadNodeId(decoder), arrayDimensionsPresents)); case BuiltInType.ExpandedNodeId: return(DecodeArray <IExpandedNodeId>(decoder, () => ReadExpandedNodeId(decoder), arrayDimensionsPresents)); case BuiltInType.StatusCode: return(DecodeArray <IStatusCode>(decoder, () => ReadStatusCode(decoder), arrayDimensionsPresents)); case BuiltInType.QualifiedName: return(DecodeArray <IQualifiedName>(decoder, () => ReadQualifiedName(decoder), arrayDimensionsPresents)); case BuiltInType.LocalizedText: return(DecodeArray <ILocalizedText>(decoder, () => ReadLocalizedText(decoder), arrayDimensionsPresents)); case BuiltInType.ExtensionObject: return(DecodeArray <IExtensionObject>(decoder, () => ReadExtensionObject(decoder), arrayDimensionsPresents)); case BuiltInType.DataValue: return(DecodeArray <IDataValue>(decoder, () => ReadDataValue(decoder), arrayDimensionsPresents)); case BuiltInType.Variant: return(DecodeArray <IVariant>(decoder, () => ReadVariant(decoder), arrayDimensionsPresents)); default: throw new ArgumentOutOfRangeException($"Cannot decode unknown type in Variant object (0x{(int)builtInType:X2})."); } }
/// <summary> /// Converts a value to a ByteString /// </summary> private static object ToByteString(object value, BuiltInType sourceType) { // check for array conversions. Array array = value as Array; if (array != null) { byte[][] output = new byte[array.Length][]; for (int ii = 0; ii < array.Length; ii++) { output[ii] = (byte[])Cast(array.GetValue(ii), BuiltInType.ByteString); } return output; } // handle for supported conversions. switch (sourceType) { case BuiltInType.ByteString: { return (byte[])value; } case BuiltInType.Guid: { return ((Guid)value).ToByteArray(); } } // conversion not supported. return null; }