public PublisherForm( ServiceMessageContext context, ApplicationInstance application, PublisherForm masterForm, ApplicationConfiguration configuration) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); m_masterForm = masterForm; m_context = context; m_application = application; m_server = application.Server as Opc.Ua.Server.StandardServer; if (m_masterForm == null) { m_forms = new List<PublisherForm>(); } SessionsCTRL.Configuration = m_configuration = configuration; SessionsCTRL.MessageContext = context; // get list of cached endpoints. m_endpoints = m_configuration.LoadCachedEndpoints(true); m_endpoints.DiscoveryUrls = configuration.ClientConfiguration.WellKnownDiscoveryUrls; EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration); // initialize control state. Disconnect(); //lth: initial MassTransit Publisher m_massTransitPublisher = new MassTransitPublisher(); this.NotificationsCTRL.ItemsAdded += NotificationsCTRL_ItemsAdded; }
/// <summary> /// Displays the dialog. /// </summary> public EndpointDescription ShowDialog( ApplicationConfiguration configuration, ConfiguredEndpointCollection endpoints, X509Certificate2 clientCertificate) { m_configuration = configuration; m_endpoints = endpoints; m_messageContext = configuration.CreateMessageContext(); m_clientCertificate = clientCertificate; m_running = false; m_filePath = @".\perftest.csv"; EndpointSelectorCTRL.Initialize(m_endpoints, configuration); lock (m_lock) { OkBTN.Enabled = m_running = false; } // show dialog. if (ShowDialog() != DialogResult.OK) { return null; } return null; }
public ClientPage( ServiceMessageContext context, ApplicationInstance application, ClientPage masterPage, ApplicationConfiguration configuration) { InitializeComponent(); if (!configuration.SecurityConfiguration.AutoAcceptUntrustedCertificates) { configuration.CertificateValidator.CertificateValidation += new CertificateValidationEventHandler(CertificateValidator_CertificateValidation); } m_masterPage = masterPage; m_context = context; m_application = application; m_server = application.Server as Opc.Ua.Server.StandardServer; if (m_masterPage == null) { m_pages = new List<ClientPage>(); } m_configuration = configuration; SessionsCTRL.Configuration = configuration; SessionsCTRL.MessageContext = context; SessionsCTRL.AddressSpaceCtrl = BrowseCTRL; SessionsCTRL.NodeSelected += SessionCtrl_NodeSelected; // get list of cached endpoints. m_endpoints = m_configuration.LoadCachedEndpoints(true); m_endpoints.DiscoveryUrls = configuration.ClientConfiguration.WellKnownDiscoveryUrls; // hook up endpoint selector EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration); EndpointSelectorCTRL.ConnectEndpoint += EndpointSelectorCTRL_ConnectEndpoint; EndpointSelectorCTRL.EndpointsChanged += EndpointSelectorCTRL_OnChange; BrowseCTRL.SessionTreeCtrl = SessionsCTRL; BrowseCTRL.NodeSelected += BrowseCTRL_NodeSelected; // exception dialog GuiUtils.ExceptionMessageDlg += ExceptionMessageDlg; ServerUrlTB.Text = "None"; m_publishers = AmqpConnectionCollection.Load(configuration); foreach (var publisher in m_publishers) { Task t = publisher.OpenAsync(); } m_MonitoredItem_Notification = new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); }
/// <summary> /// Initializes the binding. /// </summary> protected BaseBinding( NamespaceTable namespaceUris, EncodeableFactory factory, EndpointConfiguration configuration) { m_messageContext = new ServiceMessageContext(); m_messageContext.MaxStringLength = configuration.MaxStringLength; m_messageContext.MaxByteStringLength = configuration.MaxByteStringLength; m_messageContext.MaxArrayLength = configuration.MaxArrayLength; m_messageContext.MaxMessageSize = configuration.MaxMessageSize; m_messageContext.Factory = factory; m_messageContext.NamespaceUris = namespaceUris; }
public void EncodeDecodeQualifiedNameWithNullStringDefaultUri() { var context = new ServiceMessageContext(); var expected = new QualifiedName(null, 0); var s1 = expected.AsString(context); var s2 = expected.AsString(context, true); var result1 = s1.ToQualifiedName(context); var result2 = s2.ToQualifiedName(context); // BUG IN Stack: Assert.Equal(expected, result1); Assert.Equal(expected.Name, result1.Name); Assert.Equal(expected.NamespaceIndex, result1.NamespaceIndex); // BUG IN Stack: Assert.Equal(expected, result2); Assert.Equal(expected.Name, result2.Name); Assert.Equal(expected.NamespaceIndex, result2.NamespaceIndex); // BUG IN Stack: Assert.True(Utils.IsEqual(result1, result2)); }
/// <summary> /// Extracts a BuiltInType value from the line. /// </summary> private bool ExtractField(int lineCount, ref string line, ServiceMessageContext context, BuiltInType valueType, out Variant value) { value = Variant.Null; var field = line; if (field == null) { return(true); } if (valueType == BuiltInType.Null) { return(true); } var builder = new StringBuilder(); builder.AppendFormat("<Value xmlns=\"{0}\">", Opc.Ua.Namespaces.OpcUaXsd); builder.AppendFormat("<{0}>", valueType); builder.Append(line); builder.AppendFormat("</{0}>", valueType); builder.Append("</Value>"); var document = new XmlDocument { InnerXml = builder.ToString() }; XmlDecoder decoder = null; try { decoder = new XmlDecoder(document.DocumentElement, context); value = decoder.ReadVariant(null); } catch (Exception e) { Utils.Trace("PARSE ERROR [Line:{0}] - '{1}': {2}", lineCount, field, e.Message); return(false); } finally { decoder?.Dispose(); } return(true); }
/// <summary> /// Returns a qualified name from a string /// </summary> /// <param name="value"></param> /// <param name="context"></param> /// <returns></returns> public static QualifiedName ToQualifiedName(this string value, ServiceMessageContext context) { if (string.IsNullOrEmpty(value)) { return(QualifiedName.Null); } string nsUri = null; if (Uri.TryCreate(value, UriKind.Absolute, out var uri)) { if (string.IsNullOrEmpty(uri.Fragment)) { value = string.Empty; } else { value = uri.Fragment.TrimStart('#'); } nsUri = uri.NoQueryAndFragment().AbsoluteUri; } else { // Not a real namespace uri - split and decode var parts = value.Split('#'); if (parts.Length == 2) { nsUri = parts[0]; value = parts[1]; } } if (nsUri != null) { return(new QualifiedName(string.IsNullOrEmpty(value) ? null : value.UrlDecode(), context.NamespaceUris.GetIndexOrAppend(nsUri))); } try { return(QualifiedName.Parse(value.UrlDecode())); } catch { // Give up return(new QualifiedName(value)); } }
/// <summary> /// Displays the dialog. /// </summary> public ITransportChannel ShowDialog( ApplicationConfiguration configuration, EndpointDescriptionCollection endpoints) { if (endpoints == null) { throw new ArgumentNullException("endpoints"); } if (configuration == null) { throw new ArgumentNullException("configuration"); } m_endpoints = endpoints; m_configuration = configuration; m_messageContext = configuration.CreateMessageContext(); EndpointCB.Items.Clear(); foreach (EndpointDescription endpoint in endpoints) { EndpointCB.Items.Add(endpoint.EndpointUrl); } if (EndpointCB.Items.Count > 0) { EndpointCB.SelectedIndex = 0; } OperationTimeoutNC.Value = configuration.TransportQuotas.OperationTimeout; MaxMessageSizeNC.Value = configuration.TransportQuotas.MaxMessageSize; MaxArrayLengthNC.Value = configuration.TransportQuotas.MaxArrayLength; MaxStringLengthNC.Value = configuration.TransportQuotas.MaxStringLength; MaxByteStringLengthNC.Value = configuration.TransportQuotas.MaxByteStringLength; if (ShowDialog() != DialogResult.OK) { return(null); } // return the channel. return(m_channel); }
/// <summary> /// Produce Monitored Item Messages from the data set message model for the specified encoding /// </summary> /// <param name="messages"></param> /// <param name="encoding"></param> /// <param name="context"></param> private IEnumerable <MonitoredItemMessage> GetMonitoredItemMessages( IEnumerable <DataSetMessageModel> messages, MessageEncoding encoding, ServiceMessageContext context) { if (context?.NamespaceUris == null) { // Declare all notifications in messages as dropped. int totalNotifications = messages.Sum(m => m?.Notifications?.Count() ?? 0); NotificationsDroppedCount += (uint)totalNotifications; _logger.Warning("Namespace is empty, dropped {totalNotifications} values"); yield break; } foreach (var message in messages) { if (message.WriterGroup?.MessageType.GetValueOrDefault(MessageEncoding.Json) == encoding) { foreach (var notification in message.Notifications) { var result = new MonitoredItemMessage { MessageContentMask = (message.Writer?.MessageSettings? .DataSetMessageContentMask).ToMonitoredItemMessageMask( message.Writer?.DataSetFieldContentMask), ApplicationUri = message.ApplicationUri, EndpointUrl = message.EndpointUrl, ExtensionFields = message.Writer?.DataSet?.ExtensionFields, NodeId = notification.NodeId.ToExpandedNodeId(context.NamespaceUris), Timestamp = message.TimeStamp ?? DateTime.UtcNow, Value = notification.Value, DisplayName = notification.DisplayName, SequenceNumber = notification.SequenceNumber.GetValueOrDefault(0) }; // force published timestamp into to source timestamp for the legacy heartbeat compatibility if (notification.IsHeartbeat && ((result.MessageContentMask & (uint)MonitoredItemMessageContentMask.Timestamp) == 0) && ((result.MessageContentMask & (uint)MonitoredItemMessageContentMask.SourceTimestamp) != 0)) { result.Value.SourceTimestamp = result.Timestamp; } yield return(result); } } } }
public override void Initialize() { base.Initialize(); //SecurityConfiguration securityConfig = new SecurityConfiguration(); //securityConfig.ConfigureFirewall = false; //ApplicationConfiguration appConfig = new ApplicationConfiguration(); //appConfig.ApplicationName = $"OPCClient: {Name}"; //appConfig.ApplicationType = ApplicationType.Client; //appConfig.ProductUri = "https://github.com/GridProtectionAlliance/gsf"; //appConfig.SecurityConfiguration = securityConfig; //string url = "load from configuration"; //EndpointDescription endpointDescription = new EndpointDescription(url); //endpointDescription. //EndpointConfiguration endpointConfig = new EndpointConfiguration(); //endpointConfig.UseBinaryEncoding = true; //SessionChannel channel = SessionChannel.Create(appConfig, endpointConfig, appConfig.ApplicationName); //m_session = new Session() // Initialize the client configuration. ApplicationConfiguration configuration = new ApplicationConfiguration(); // Need to specify the application instance certificate for the client. configuration.SecurityConfiguration.ApplicationCertificate = new CertificateIdentifier(); configuration.SecurityConfiguration.ApplicationCertificate.StoreType = Utils.DefaultStoreType; configuration.SecurityConfiguration.ApplicationCertificate.StorePath = Utils.DefaultStorePath; configuration.SecurityConfiguration.ApplicationCertificate.SubjectName = $"TSL OPC Client: {Name}"; // set the session keep alive to 5 seconds. configuration.ClientConfiguration.DefaultSessionTimeout = 500000; m_configuration = configuration; m_messageContext = configuration.CreateMessageContext(); m_stopped = false; //m_performanceData = new List<PerfData>(); }
private TrustListDataType DecodeTrustListData( ISystemContext context, Stream strm) { TrustListDataType trustList = new TrustListDataType(); ServiceMessageContext messageContext = new ServiceMessageContext() { NamespaceUris = context.NamespaceUris, ServerUris = context.ServerUris, Factory = context.EncodeableFactory }; strm.Position = 0; BinaryDecoder decoder = new BinaryDecoder(strm, messageContext); trustList.Decode(decoder); decoder.Close(); return(trustList); }
public void Constructor_Stream() { var context = new ServiceMessageContext(); var memoryStream = new MemoryStream(); using (var jsonEncoder = new JsonEncoder(context, true, false, memoryStream, true)) { TestEncoding(jsonEncoder); } var result1 = Encoding.UTF8.GetString(memoryStream.ToArray()); Assert.IsNotEmpty(result1); TestContext.Out.WriteLine("Result1:"); _ = PrettifyAndValidateJson(result1); // recycle the StreamWriter, ensure the result is equal using (var jsonEncoder = new JsonEncoder(context, true, false, memoryStream, true)) { TestEncoding(jsonEncoder); } var result2 = Encoding.UTF8.GetString(memoryStream.ToArray()); Assert.IsNotEmpty(result2); TestContext.Out.WriteLine("Result2:"); _ = PrettifyAndValidateJson(result2); Assert.AreEqual(result1, result2); // recycle the StreamWriter, ensure the result is equal, // use reflection to return result in external stream using (var jsonEncoder = new JsonEncoder(context, true, false, memoryStream, false)) { TestEncoding(jsonEncoder); var result3 = jsonEncoder.CloseAndReturnText(); Assert.IsNotEmpty(result3); TestContext.Out.WriteLine("Result3:"); _ = PrettifyAndValidateJson(result3); Assert.AreEqual(result1, result3); } // ensure the memory stream was closed Assert.Throws <ArgumentException>(() => _ = new StreamWriter(memoryStream)); }
public void EncodeDecodeQualifiedNameWithEmptyString() { var context = new ServiceMessageContext(); var expected = new QualifiedName("", context.NamespaceUris.GetIndexOrAppend("http://contoso.com/UA")); var s1 = expected.AsString(context); var s2 = expected.AsString(context, true); var result1 = s1.ToQualifiedName(context); var result2 = s2.ToQualifiedName(context); // BUG IN Stack: Assert.Equal(expected, result1); Assert.Null(result1.Name); Assert.Equal(expected.NamespaceIndex, result1.NamespaceIndex); // BUG IN Stack: Assert.Equal(expected, result2); Assert.Null(result2.Name); Assert.Equal(expected.NamespaceIndex, result2.NamespaceIndex); // BUG IN Stack: Assert.True(Utils.IsEqual(result1, result2)); }
static TestStackRequest Decode(byte[] message, ServiceMessageContext context1, bool binary) { if (binary) { return((TestStackRequest)BinaryDecoder.DecodeMessage(message, null, context1)); } else { ServiceMessageContext.ThreadContext = context1; MemoryStream istrm = new MemoryStream(message); XmlReaderSettings settings = new XmlReaderSettings(); using (XmlReader reader = XmlReader.Create(istrm, settings)) { DataContractSerializer serializer = new DataContractSerializer(typeof(TestStackRequest)); return((TestStackRequest)serializer.ReadObject(reader)); } } }
/// <summary> /// Decodes the message /// </summary> /// <param name="message"></param> /// <param name="dataSetReaders"></param> public override void Decode(byte[] message, IList <DataSetReaderDataType> dataSetReaders) { if (dataSetReaders == null || dataSetReaders.Count == 0) { return; } ServiceMessageContext messageContext = new ServiceMessageContext(); messageContext.NamespaceUris = ServiceMessageContext.GlobalContext.NamespaceUris; messageContext.ServerUris = ServiceMessageContext.GlobalContext.ServerUris; string json = System.Text.Encoding.ASCII.GetString(message); using (JsonDecoder decoder = new JsonDecoder(json, messageContext)) { //decode bytes using dataset reader information DecodeSubscribedDataSets(decoder, dataSetReaders); } }
static TestStackRequest Decode(byte[] message, ServiceMessageContext context1, bool binary) { if (binary) { return (TestStackRequest)BinaryDecoder.DecodeMessage(message, null, context1); } else { ServiceMessageContext.ThreadContext = context1; MemoryStream istrm = new MemoryStream(message); XmlReaderSettings settings = new XmlReaderSettings(); using (XmlReader reader = XmlReader.Create(istrm, settings)) { DataContractSerializer serializer = new DataContractSerializer(typeof(TestStackRequest)); return (TestStackRequest)serializer.ReadObject(reader); } } }
/// <summary> /// Returns a node from a string /// </summary> /// <param name="value"></param> /// <param name="context"></param> /// <returns></returns> public static NodeId ToNodeId(this string value, ServiceMessageContext context) { if (value == null) { return(NodeId.Null); } var parts = value.Split(';'); if (parts.Any(s => s.StartsWith("ns=", StringComparison.CurrentCulture))) { return(NodeId.Parse(value)); } if (parts.Any(s => s.StartsWith("nsu=", StringComparison.CurrentCulture))) { return(ExpandedNodeId.Parse(value).ToNodeId(context.NamespaceUris)); } var identifier = ParseNodeIdUri(value, out var nsUri, out var srvUri); return(new NodeId(identifier, context.NamespaceUris.GetIndexOrAppend(nsUri))); }
/// <summary> /// Compare encoded/decoded dataset messages /// </summary> /// <param name="uadpDataSetMessage"></param> /// <returns></returns> private void CompareEncodeDecode(UadpDataSetMessage uadpDataSetMessage) { ServiceMessageContext messageContextEncode = new ServiceMessageContext(); BinaryEncoder encoder = new BinaryEncoder(messageContextEncode); uadpDataSetMessage.Encode(encoder); byte[] bytes = ReadBytes(encoder.BaseStream); encoder.Dispose(); UadpDataSetMessage uaDataSetMessageDecoded = new UadpDataSetMessage(); BinaryDecoder decoder = new BinaryDecoder(bytes, messageContextEncode); // workaround uaDataSetMessageDecoded.DataSetWriterId = TestDataSetWriterId; uaDataSetMessageDecoded.DecodePossibleDataSetReader(decoder, m_firstDataSetReaderType); decoder.Dispose(); // compare uadpDataSetMessage with uaDataSetMessageDecoded CompareUadpDataSetMessages(uadpDataSetMessage, uaDataSetMessageDecoded); }
/// <summary> /// Encodes a message in a stream. /// </summary> private static void EncodeBinaryMessage(IEncodeable message, Stream stream, ServiceMessageContext context) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (context == null) { throw new ArgumentNullException(nameof(context)); } MemoryStream buffer = null; try { // // Binary encoder unfortunately seeks (to keep track of // position). Therefore we need to wrap a non seeking stream. // var output = stream.CanSeek ? stream : buffer = new MemoryStream(); using (var encoder = new BinaryEncoder(output, context)) { // convert the namespace uri to an index. var typeId = ExpandedNodeId.ToNodeId(message.BinaryEncodingId, context.NamespaceUris); // write the type id. encoder.WriteNodeId(null, typeId); // write the message. encoder.WriteEncodeable(null, message, message.GetType()); } } finally { if (buffer != null) { stream.Write(buffer.ToArray()); buffer.Dispose(); } } }
public void EncodeDecodePath1() { var path = new string[] { "<!#http://contoso.com/ua#i=44>Test", "<!HasChild>Test", "<#HasChild>Test", "<!#HasProperty>Test", "<HasComponent>Test", "/foo", ".bar", "/!#flah", "!#flah", "xxxx", }; var context = new ServiceMessageContext(); var relative = path.ToRelativePath(context); var result = relative.AsString(context); Assert.Equal(path, result); }
/// <summary> /// Prepare data /// </summary> /// <param name="publisherConnection"></param> /// <returns></returns> private byte[] PrepareData(UadpPubSubConnection publisherConnection) { try { WriterGroupDataType writerGroup0 = publisherConnection.PubSubConnectionConfiguration.WriterGroups[0]; UaNetworkMessage message = publisherConnection.CreateNetworkMessage(writerGroup0); ServiceMessageContext messageContext = new ServiceMessageContext(); BinaryEncoder encoder = new BinaryEncoder(messageContext); message.Encode(encoder); byte[] bytes = ReadBytes(encoder.BaseStream); encoder.Dispose(); return(bytes); } catch (Exception) { } return(new byte[0]); }
public void EncodeDecodeNodeIdWithNullString() { var context = new ServiceMessageContext(); var expected = new NodeId((string)null, context.NamespaceUris.GetIndexOrAppend("http://contoso.com/UA")); var s1 = expected.AsString(context); var s2 = expected.AsString(context, true); var result1 = s1.ToNodeId(context); var result2 = s2.ToNodeId(context); Assert.Equal(expected, result1); Assert.Equal(expected, result2); Assert.True(Utils.IsEqual(result1, result2)); Assert.Equal(string.Empty, result1.Identifier); Assert.Equal(expected.NamespaceIndex, result1.NamespaceIndex); Assert.Equal(string.Empty, result2.Identifier); Assert.Equal(expected.NamespaceIndex, result2.NamespaceIndex); }
/// <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> /// Initializes the datastore with the server configuration. /// </summary> /// <param name="serverDescription">The server description.</param> /// <param name="configuration">The configuration.</param> /// <param name="messageContext">The message context.</param> /// <param name="certificateValidator">The certificate validator.</param> /// <param name="instanceCertificate">The instance certificate.</param> public ServerInternalData( ServerProperties serverDescription, ApplicationConfiguration configuration, ServiceMessageContext messageContext, CertificateValidator certificateValidator, X509Certificate2 instanceCertificate) { m_serverDescription = serverDescription; m_configuration = configuration; m_messageContext = messageContext; m_endpointAddresses = new List <Uri>(); foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses) { Uri url = Utils.ParseUri(baseAddresses); if (url != null) { m_endpointAddresses.Add(url); } } m_namespaceUris = m_messageContext.NamespaceUris; m_factory = m_messageContext.Factory; m_serverUris = new StringTable(); m_typeTree = new TypeTable(m_namespaceUris); #if LEGACY_CORENODEMANAGER m_typeSources = new TypeSourceTable(); #endif // add the server uri to the server table. m_serverUris.Append(m_configuration.ApplicationUri); // create the default system context. m_defaultSystemContext = new ServerSystemContext(this); }
public void ReadWriteDataValueDictionary() { // Create dummy var expected = new Dictionary <string, DataValue> { ["abcd"] = new DataValue(new Variant(1234), StatusCodes.Good, DateTime.Now, DateTime.UtcNow), ["http://microsoft.com"] = new DataValue(new Variant(-222222222), StatusCodes.Bad, DateTime.MinValue, DateTime.Now), ["1111111111111111111111111"] = new DataValue(new Variant(false), StatusCodes.Bad, DateTime.UtcNow, DateTime.MinValue), ["@#$%^&*()_+~!@#$%^*(){}"] = new DataValue(new Variant(new byte[] { 0, 2, 4, 6 }), StatusCodes.Good), ["1245"] = new DataValue(new Variant("hello"), StatusCodes.Bad, DateTime.Now, DateTime.MinValue), ["..."] = new DataValue(new Variant(new Variant("imbricated"))), }; var count = 10000; byte[] buffer; var context = new ServiceMessageContext(); using (var stream = new MemoryStream()) { using (var encoder = new JsonEncoderEx(stream, context, JsonEncoderEx.JsonEncoding.Array)) { for (var i = 0; i < count; i++) { encoder.WriteDataValueDictionary(null, expected); } } buffer = stream.ToArray(); } using (var stream = new MemoryStream(buffer)) { using (var decoder = new JsonDecoderEx(stream, context)) { for (var i = 0; i < count; i++) { var result = decoder.ReadDataValueDictionary(null); Assert.Equal(expected, result); } var eof = decoder.ReadDataValue(null); Assert.Null(eof); } } }
/// <summary> /// Initializes the datastore with the server configuration. /// </summary> /// <param name="serverDescription">The server description.</param> /// <param name="configuration">The configuration.</param> /// <param name="messageContext">The message context.</param> /// <param name="certificateValidator">The certificate validator.</param> /// <param name="instanceCertificate">The instance certificate.</param> public ServerInternalData( ServerProperties serverDescription, ApplicationConfiguration configuration, ServiceMessageContext messageContext, CertificateValidator certificateValidator, X509Certificate2 instanceCertificate) { m_serverDescription = serverDescription; m_configuration = configuration; m_messageContext = messageContext; m_endpointAddresses = new List<Uri>(); foreach (string baseAddresses in m_configuration.ServerConfiguration.BaseAddresses) { Uri url = Utils.ParseUri(baseAddresses); if (url != null) { m_endpointAddresses.Add(url); } } m_namespaceUris = m_messageContext.NamespaceUris; m_factory = m_messageContext.Factory; m_serverUris = new StringTable(); m_typeTree = new TypeTable(m_namespaceUris); #if LEGACY_CORENODEMANAGER m_typeSources = new TypeSourceTable(); #endif // add the server uri to the server table. m_serverUris.Append(m_configuration.ApplicationUri); // create the default system context. m_defaultSystemContext = new ServerSystemContext(this); }
/// <summary> /// Decoder factory for all decoding types. /// </summary> protected IDecoder CreateDecoder( EncodingType decoderType, ServiceMessageContext context, Stream stream, Type systemType ) { switch (decoderType) { case EncodingType.Binary: return(new BinaryDecoder(stream, context)); case EncodingType.Xml: var xmlReader = XmlReader.Create(stream); return(new XmlDecoder(systemType, xmlReader, context)); case EncodingType.Json: var jsonTextReader = new JsonTextReader(new StreamReader(stream)); return(new JsonDecoder(systemType, jsonTextReader, context)); } return(null); }
public PublisherForm( ServiceMessageContext context, ApplicationInstance application, PublisherForm masterForm, ApplicationConfiguration configuration) { InitializeComponent(); this.Icon = ClientUtils.GetAppIcon(); m_masterForm = masterForm; m_context = context; m_application = application; m_server = application.Server as Opc.Ua.Server.StandardServer; if (m_masterForm == null) { m_forms = new List <PublisherForm>(); } SessionsCTRL.Configuration = m_configuration = configuration; SessionsCTRL.MessageContext = context; // get list of cached endpoints. m_endpoints = m_configuration.LoadCachedEndpoints(true); m_endpoints.DiscoveryUrls = configuration.ClientConfiguration.WellKnownDiscoveryUrls; EndpointSelectorCTRL.Initialize(m_endpoints, m_configuration); // initialize control state. Disconnect(); m_publishers = AmqpConnectionCollection.Load(configuration); foreach (var publisher in m_publishers) { Task t = publisher.OpenAsync(); } this.NotificationsCTRL.ItemsAdded += NotificationsCTRL_ItemsAdded; }
/// <summary> /// Creates an encoder to save Variant values. /// </summary> private XmlEncoder CreateEncoder(ISystemContext context) { IServiceMessageContext messageContext = new ServiceMessageContext() { NamespaceUris = context.NamespaceUris, ServerUris = context.ServerUris, Factory = context.EncodeableFactory }; XmlEncoder encoder = new XmlEncoder(messageContext); NamespaceTable namespaceUris = new NamespaceTable(); if (NamespaceUris != null) { for (int ii = 0; ii < NamespaceUris.Length; ii++) { namespaceUris.Append(NamespaceUris[ii]); } } StringTable serverUris = new StringTable(); if (ServerUris != null) { serverUris.Append(context.ServerUris.GetString(0)); for (int ii = 0; ii < ServerUris.Length; ii++) { serverUris.Append(ServerUris[ii]); } } encoder.SetMappingTables(namespaceUris, serverUris); return(encoder); }
/// <summary> /// Displays the dialog. /// </summary> public ITransportChannel ShowDialog( ApplicationConfiguration configuration, EndpointDescriptionCollection endpoints) { if (endpoints == null) throw new ArgumentNullException("endpoints"); if (configuration == null) throw new ArgumentNullException("configuration"); m_endpoints = endpoints; m_configuration = configuration; m_messageContext = configuration.CreateMessageContext(); EndpointCB.Items.Clear(); foreach (EndpointDescription endpoint in endpoints) { EndpointCB.Items.Add(endpoint.EndpointUrl); } if (EndpointCB.Items.Count > 0) { EndpointCB.SelectedIndex = 0; } OperationTimeoutNC.Value = configuration.TransportQuotas.OperationTimeout; MaxMessageSizeNC.Value = configuration.TransportQuotas.MaxMessageSize; MaxArrayLengthNC.Value = configuration.TransportQuotas.MaxArrayLength; MaxStringLengthNC.Value = configuration.TransportQuotas.MaxStringLength; MaxByteStringLengthNC.Value = configuration.TransportQuotas.MaxByteStringLength; if (ShowDialog() != DialogResult.OK) { return null; } // return the channel. return m_channel; }
/// <summary> /// Creates an decoder to restore Variant values. /// </summary> private XmlDecoder CreateDecoder(ISystemContext context, XmlElement source) { ServiceMessageContext messageContext = new ServiceMessageContext(); messageContext.NamespaceUris = context.NamespaceUris; messageContext.ServerUris = context.ServerUris; messageContext.Factory = context.EncodeableFactory; XmlDecoder decoder = new XmlDecoder(source, messageContext); NamespaceTable namespaceUris = new NamespaceTable(); if (NamespaceUris != null) { for (int ii = 0; ii < NamespaceUris.Length; ii++) { namespaceUris.Append(NamespaceUris[ii]); } } StringTable serverUris = new StringTable(); if (ServerUris != null) { serverUris.Append(context.ServerUris.GetString(0)); for (int ii = 0; ii < ServerUris.Length; ii++) { serverUris.Append(ServerUris[ii]); } } decoder.SetMappingTables(namespaceUris, serverUris); return(decoder); }
static byte[] Encode(TestStackRequest request1, ServiceMessageContext context1, bool binary) { if (binary) { return BinaryEncoder.EncodeMessage(request1, context1); } else { ServiceMessageContext.ThreadContext = context1; MemoryStream ostrm = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = System.Text.Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(ostrm, settings)) { DataContractSerializer serializer = new DataContractSerializer(typeof(TestStackRequest)); serializer.WriteObject(writer, request1); } return ostrm.ToArray(); } }
public void EncodeDecodePath2() { var path = new string[] { "<!HasChild>Test", "<#http://opcfoundation.org/ua#i_33>Test", "<#!HasProperty>Test", "<#!http://contoso.com/ua#i_44>Test", "<http://opcfoundation.org/ua#i_33>Test", "#foo", "!.bar", "!#/flah", "!/#flah", "!xxxx", }; var context = new ServiceMessageContext(); var relative = path.ToRelativePath(context); var expected = relative.AsString(context); relative = expected.ToRelativePath(context); var result = relative.AsString(context); Assert.Equal(expected, result); }
static byte[] Encode(TestStackRequest request1, ServiceMessageContext context1, bool binary) { if (binary) { return(BinaryEncoder.EncodeMessage(request1, context1)); } else { ServiceMessageContext.ThreadContext = context1; MemoryStream ostrm = new MemoryStream(); XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = System.Text.Encoding.UTF8; using (XmlWriter writer = XmlWriter.Create(ostrm, settings)) { DataContractSerializer serializer = new DataContractSerializer(typeof(TestStackRequest)); serializer.WriteObject(writer, request1); } return(ostrm.ToArray()); } }
/// <summary> /// Constructs an instance of the data comparer. /// </summary> public DataComparer(ServiceMessageContext context) { m_context = context; m_throwOnError = true; }
/// <summary> /// Connects to the UA server identfied by the CLSID. /// </summary> /// <param name="clsid">The CLSID.</param> /// <returns>The UA server.</returns> private Session Connect(Guid clsid) { // load the endpoint information. ConfiguredEndpoint endpoint = m_endpoint = LoadConfiguredEndpoint(clsid); if (endpoint == null) { throw new ServiceResultException(StatusCodes.BadConfigurationError); } // update security information. if (endpoint.UpdateBeforeConnect) { endpoint.UpdateFromServer(BindingFactory.Default); // check if halted while waiting for a response. if (!m_running) { throw new ServiceResultException(StatusCodes.BadServerHalted); } } // look up the client certificate. X509Certificate2 clientCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true); // create a message context to use with the channel. ServiceMessageContext messageContext = m_configuration.CreateMessageContext(); // create the channel. ITransportChannel channel = SessionChannel.Create( m_configuration, endpoint.Description, endpoint.Configuration, clientCertificate, messageContext); // create the session. Session session = new Session(channel, m_configuration, endpoint, clientCertificate); // create a session name that is useful for debugging. string sessionName = Utils.Format("COM Client ({0})", System.Net.Dns.GetHostName()); // open the session. Opc.Ua.UserIdentity identity = null; if (endpoint.UserIdentity != null) { // need to decode password. UserNameIdentityToken userNameToken = endpoint.UserIdentity as UserNameIdentityToken; if (userNameToken != null) { UserNameIdentityToken copy = new UserNameIdentityToken(); copy.PolicyId = userNameToken.PolicyId; copy.DecryptedPassword = new UTF8Encoding().GetString(userNameToken.Password); copy.UserName = userNameToken.UserName; copy.EncryptionAlgorithm = userNameToken.EncryptionAlgorithm; identity = new Opc.Ua.UserIdentity(copy); } // create the identity object. else { identity = new Opc.Ua.UserIdentity(endpoint.UserIdentity); } } session.Open(sessionName, identity); // return the new session. return(session); }
/// <summary> /// Get ua settings /// </summary> /// <param name="context"></param> /// <returns></returns> internal static JsonSerializerSettings GetSettings(ServiceMessageContext context) { return(JsonConvertEx.GetSettings().AddUaConverters(context)); }
/// <summary> /// Read a message in SOAP/XML. /// </summary> public static IEncodeable ReadSoapMessage( Stream istrm, string typeName, Type messageType, ServiceMessageContext messageContext) { XmlReader reader = XmlReader.Create(istrm); reader.MoveToContent(); reader.ReadStartElement("Envelope", "http://www.w3.org/2003/05/soap-envelope"); reader.MoveToContent(); while (!reader.IsStartElement("Body", "http://www.w3.org/2003/05/soap-envelope")) { reader.Skip(); } XmlDecoder decoder = new XmlDecoder(null, reader, messageContext); decoder.PushNamespace(Namespaces.OpcUaXsd); IEncodeable message = decoder.ReadEncodeable(typeName, messageType); decoder.PopNamespace(); reader.ReadEndElement(); reader.ReadEndElement(); reader.Close(); return message; }
/// <summary> /// Initializes the namespace mappings and updates the proxy configuration. /// </summary> /// <param name="session">The session.</param> /// <param name="configuration">The configuration.</param> public virtual void Initialize(Session session, ComProxyConfiguration configuration) { lock (m_lock) { m_typeTable = session.TypeTree; // index namspace uris. if (configuration.NamespaceUris == null) { configuration.NamespaceUris = new StringCollection(); } m_namespaceUris = new StringTableMapping(); m_namespaceUris.Initialize(configuration.NamespaceUris, session.NamespaceUris); // index server uris. if (configuration.ServerUris == null) { configuration.ServerUris = new StringCollection(); } m_serverUris = new StringTableMapping(); m_serverUris.Initialize(configuration.ServerUris, session.ServerUris); // create message context. ServiceMessageContext context = new ServiceMessageContext(); context.MaxArrayLength = session.MessageContext.MaxArrayLength; context.MaxByteStringLength = session.MessageContext.MaxByteStringLength; context.MaxMessageSize = session.MessageContext.MaxMessageSize; context.MaxStringLength = session.MessageContext.MaxStringLength; context.Factory = session.MessageContext.Factory; context.NamespaceUris = new NamespaceTable(); context.ServerUris = new StringTable(); // copy namespace uris. context.NamespaceUris.Append(session.NamespaceUris.GetString(1)); for (int ii = 0; ii < configuration.NamespaceUris.Count; ii++) { context.NamespaceUris.Append(configuration.NamespaceUris[ii]); } // copy server uris. context.ServerUris.Append(session.ServerUris.GetString(0)); for (int ii = 0; ii < configuration.ServerUris.Count; ii++) { context.ServerUris.Append(configuration.ServerUris[ii]); } m_localMessageContext = context; // index mapping sets by the name assigned. if (configuration.MappingSets != null) { m_mappingSets = new Dictionary<string, NodeIdMappingSet>(); for (int ii = 0; ii < configuration.MappingSets.Count; ii++) { UpdateMappingSet(configuration.MappingSets[ii]); } } } }
/// <summary> /// Creates an decoder to restore Variant values. /// </summary> private XmlDecoder CreateDecoder(ISystemContext context, XmlElement source) { ServiceMessageContext messageContext = new ServiceMessageContext(); messageContext.NamespaceUris = context.NamespaceUris; messageContext.ServerUris = context.ServerUris; messageContext.Factory = context.EncodeableFactory; XmlDecoder decoder = new XmlDecoder(source, messageContext); NamespaceTable namespaceUris = new NamespaceTable(); if (NamespaceUris != null) { for (int ii = 0; ii < NamespaceUris.Length; ii++) { namespaceUris.Append(NamespaceUris[ii]); } } StringTable serverUris = new StringTable(); if (ServerUris != null) { serverUris.Append(context.ServerUris.GetString(0)); for (int ii = 0; ii < ServerUris.Length; ii++) { serverUris.Append(ServerUris[ii]); } } decoder.SetMappingTables(namespaceUris, serverUris); return decoder; }
/// <summary> /// Writes a message in SOAP/XML. /// </summary> public static void WriteSoapMessage( Stream ostrm, string typeName, IEncodeable message, ServiceMessageContext messageContext) { XmlWriterSettings settings = new XmlWriterSettings(); settings.Encoding = System.Text.Encoding.UTF8; settings.OmitXmlDeclaration = false; XmlWriter writer = XmlWriter.Create(ostrm, settings); writer.WriteStartElement("soap12", "Envelope", "http://www.w3.org/2003/05/soap-envelope"); XmlEncoder encoder = new XmlEncoder( new XmlQualifiedName("Body", "http://www.w3.org/2003/05/soap-envelope"), writer, messageContext); encoder.PushNamespace(Namespaces.OpcUaXsd); encoder.WriteEncodeable( typeName, message, null); encoder.PopNamespace(); writer.WriteEndElement(); writer.WriteEndElement(); writer.Flush(); }
/// <summary> /// Function that parses complex types /// </summary> /// <param name="descriptionId"></param> /// <param name="extensionObject"></param> /// <param name="context"></param> /// <param name="generateSchema"></param> /// <returns></returns> public UaValue Parse(string descriptionId, ExtensionObject extensionObject, ServiceMessageContext context, bool generateSchema) { _bd = new BinaryDecoder((byte[])extensionObject.Body, context); return(BuildJsonForObject(descriptionId, generateSchema)); }
/// <summary> /// Initializes contexts for vendor namespaces. /// </summary> /// <param name="serviceMessageContext"> An object value of type ServiceMessageContext</param> public static void InitializeContexts(ServiceMessageContext serviceMessageContext) { FieldInfo[] fields = typeof(VendorNamespaces).GetFields(BindingFlags.Static | BindingFlags.Public); List<string> namespaceUris = new List<string>(); namespaceUris.Add(Namespaces.OpcUa); namespaceUris.Add(Guid.NewGuid().ToString()); foreach (FieldInfo field in fields) { if (field.FieldType == typeof(string)) { namespaceUris.Add((string)field.GetValue(null)); } } serviceMessageContext.NamespaceUris.Update(namespaceUris); serviceMessageContext.Factory.AddEncodeableType(typeof(AcmeWidget)); serviceMessageContext.Factory.AddEncodeableType(typeof(CoyoteGadget)); serviceMessageContext.Factory.AddEncodeableType(typeof(SkyNetRobot)); serviceMessageContext.Factory.AddEncodeableType(typeof(S88Batch)); serviceMessageContext.Factory.AddEncodeableType(typeof(S88Operation)); serviceMessageContext.Factory.AddEncodeableType(typeof(S88Phase)); serviceMessageContext.Factory.AddEncodeableType(typeof(S88UnitProcedure)); serviceMessageContext.Factory.AddEncodeableType(typeof(Driver)); serviceMessageContext.Factory.AddEncodeableType(typeof(Vehicle)); serviceMessageContext.Factory.AddEncodeableType(typeof(Wheel)); serviceMessageContext.Factory.AddEncodeableType(typeof(Car)); serviceMessageContext.Factory.AddEncodeableType(typeof(Truck)); }