The table of namespace uris for a server.
Inheritance: StringTable
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaSoapXmlOverTcpBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {                   
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                SymmetricSecurityBindingElement bootstrap = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement();
                
                bootstrap.MessageProtectionOrder       = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
                bootstrap.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                bootstrap.IncludeTimestamp             = true;
                bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                // bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.RequireSignatureConfirmation = false;
                bootstrap.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;
                
                m_security = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap, true);
                
                m_security.MessageProtectionOrder       = MessageProtectionOrder.EncryptBeforeSign;
                m_security.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                m_security.IncludeTimestamp             = true;
                m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                // m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.RequireSignatureConfirmation = false;
                m_security.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;

                m_security.SetKeyDerivation(true);
            }
            
            m_encoding = new BinaryMessageEncodingBindingElement();
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new System.ServiceModel.Channels.TcpTransportBindingElement();

            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferPoolSize      = Int32.MaxValue;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
        }
 /// <summary>
 /// Initializes the binding.
 /// </summary>
 /// <param name="namespaceUris">The namespace uris.</param>
 /// <param name="factory">The factory.</param>
 /// <param name="configuration">The configuration.</param>
 /// <param name="descriptions">The descriptions.</param>
 public UaTcpBinding(
     NamespaceTable               namespaceUris,
     EncodeableFactory            factory,
     EndpointConfiguration        configuration,
     params EndpointDescription[] descriptions)
 :
     base(namespaceUris, factory, configuration)
 {
     m_transport = new TcpTransportBindingElement();
     m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
 }
Exemple #3
0
 /// <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;
 }
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaSoapXmlBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                TransportSecurityBindingElement bootstrap = SecurityBindingElement.CreateUserNameOverTransportBindingElement();
                bootstrap.IncludeTimestamp = true;
                bootstrap.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                bootstrap.SecurityHeaderLayout = SecurityHeaderLayout.Strict;

                m_security = SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap);
                m_security.IncludeTimestamp = true;
                m_security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                m_security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
            }

            m_encoding  = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8);
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new HttpTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
        }
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        public UaBasicHttpBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {                       
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                // TBD
            }
                        
            m_encoding  = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8);
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new HttpTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.BypassProxyOnLocal     = true;
            m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            m_transport.KeepAliveEnabled       = true;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferPoolSize      = Int32.MaxValue;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
            m_transport.UseDefaultWebProxy     = false;
        }
Exemple #6
0
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="descriptions">The descriptions.</param>
        public UaTcpBinding(
            NamespaceTable               namespaceUris,
            EncodeableFactory            factory,
            EndpointConfiguration        configuration,
            params EndpointDescription[] descriptions)
        :
            base(namespaceUris, factory, configuration)
        {
            m_transport = new UaTcpTransportBindingElement();

            m_transport.MessageContext = base.MessageContext;
            m_transport.Configuration = configuration;

            if (descriptions != null)
            {
                m_transport.Descriptions = new EndpointDescriptionCollection(descriptions);
            }

            m_transport.MaxBufferPoolSize = Int32.MaxValue;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
        }
Exemple #7
0
        /// <summary>
        /// Constructs the server.
        /// </summary>
        public ServerObject(string applicationUri, NodeManager nodeManager)
        {
            // the namespace table is used for the namepace indexes in NodeIds and QualifiedNames
            // The first index (added by default) is the UA namespace. The second is the application uri.
            m_namespaceUris = new NamespaceTable();
            m_namespaceUris.Append(applicationUri);

            // the server table is used for the server index in remote NodeIds (a.k.a. ExpandedNodeIds)
            // The first index is always the current server.
            m_serverUris = new StringTable();
            m_serverUris.Append(applicationUri);

            m_serviceLevel = 100;

            m_serverStatus = new ServerStatusDataType();
            m_serverStatus.StartTime = DateTime.UtcNow;
            m_serverStatus.CurrentTime = DateTime.UtcNow;
            m_serverStatus.State = ServerState.Running_0;
            m_serverStatus.SecondsTillShutdown = 0;
            m_serverStatus.ShutdownReason = null;

            m_serverStatus.BuildInfo = new BuildInfo();
            m_serverStatus.BuildInfo.BuildDate = new DateTime(2008, 7, 1);
            m_serverStatus.BuildInfo.SoftwareVersion = "1.00";
            m_serverStatus.BuildInfo.BuildNumber = "218.0";
            m_serverStatus.BuildInfo.ManufacturerName = "My Company";
            m_serverStatus.BuildInfo.ProductName = "My Sample Server";
            m_serverStatus.BuildInfo.ProductUri = "http://mycompany.com/MySampleServer/v1.0";

            // tell the node manager to call this object whenever the value of these attributes are read.
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_NamespaceArray), GetNamespaceArray);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServerArray), GetServerArray);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServiceLevel), GetServiceLevel);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServerStatus), GetServerStatus);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServerStatus_StartTime), GetServerStatus_StartTime);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServerStatus_CurrentTime), GetServerStatus_CurrentTime);
            nodeManager.SetReadValueCallback(new NodeId(Variables.Server_ServerStatus_State), GetServerStatus_State);
        }
        /// <summary>
        /// Reads the application description from the GDS.
        /// </summary>
        private ApplicationDescription Read(NodeId nodeId)
        {
            NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
            wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);

            string[] browsePaths = new string[] 
            {
                "1:ApplicationName",
                "1:ApplicationType",
                "1:ApplicationUri",
                "1:ProductUri",
                "1:GatewayServerUri",
                "1:DiscoveryUrls"
            };

            List<NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
                ServerCTRL.Session,
                nodeId,
                wellKnownNamespaceUris,
                browsePaths);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (NodeId propertyId in propertyIds)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId = propertyId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ServerCTRL.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            ApplicationDescription application = new ApplicationDescription();

            application.ApplicationName = results[0].GetValue<LocalizedText>(null);
            application.ApplicationType = (ApplicationType)results[1].GetValue<int>((int)ApplicationType.Server);
            application.ApplicationUri = results[2].GetValue<string>(null);
            application.ProductUri = results[3].GetValue<string>(null);
            application.GatewayServerUri = results[4].GetValue<string>(null);

            string[] discoveryUrls = results[5].GetValue<string[]>(null);

            if (discoveryUrls != null)
            {
                application.DiscoveryUrls = new StringCollection(discoveryUrls);
            }

            return application;
        }
Exemple #9
0
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return(Opc.Ua.NodeId.Create(AggregationModel.ObjectTypes.AggregatedServerStatusType, AggregationModel.Namespaces.Aggregation, namespaceUris));
 }
Exemple #10
0
        /// <summary>
        /// Replaces the test nodes in the list.
        /// </summary>
        public void ReplaceNodeList(IList <TestNode> nodes, IList <ILocalNode> newNodes, NamespaceTable namespaceUris)
        {
            nodes.Clear();

            if (newNodes == null)
            {
                return;
            }

            List <string> exportedUris = new List <string>();

            if (NamespaceUris != null)
            {
                exportedUris.AddRange(NamespaceUris);
            }

            for (int ii = 0; ii < newNodes.Count; ii++)
            {
                ILocalNode newNode = newNodes[ii];

                NodeId nodeId = newNode.NodeId;

                if (namespaceUris != null && nodeId.NamespaceIndex > 1)
                {
                    string uri = namespaceUris.GetString(nodeId.NamespaceIndex);

                    if (uri != null)
                    {
                        bool found = false;

                        for (int jj = 0; jj < exportedUris.Count; ii++)
                        {
                            if (exportedUris[jj] == uri)
                            {
                                nodeId = new NodeId(nodeId.Identifier, (ushort)(jj + 2));
                                found  = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            exportedUris.Add(uri);
                            nodeId = new NodeId(nodeId.Identifier, (ushort)(exportedUris.Count + 1));
                        }
                    }
                }

                TestNode testNode = new TestNode();

                testNode.Id   = nodeId.ToString();
                testNode.Name = newNode.BrowseName.ToString();

                nodes.Add(testNode);
            }

            NamespaceUris = new ListOfString();
            NamespaceUris.AddRange(exportedUris);
        }
Exemple #11
0
        /// <summary>
        /// Initializes the channel.
        /// </summary>
        private void Initialize(
            ITransportChannel        channel, 
            ApplicationConfiguration configuration, 
            ConfiguredEndpoint       endpoint,
            X509Certificate2         clientCertificate)
        {
            Initialize();

            // save configuration information.
            m_configuration = configuration;
            m_endpoint = endpoint;
            
            // update the default subscription. 
            m_defaultSubscription.MinLifetimeInterval = (uint)configuration.ClientConfiguration.MinSubscriptionLifetime;

            if (m_endpoint.Description.SecurityPolicyUri != SecurityPolicies.None)
            {
                // update client certificate.
                m_instanceCertificate = clientCertificate;

                if (clientCertificate == null)
                {
                    // load the application instance certificate.
                    if (m_configuration.SecurityConfiguration.ApplicationCertificate == null)
                    {
                        throw new ServiceResultException(
                            StatusCodes.BadConfigurationError,
                            "The client configuration does not specify an application instance certificate.");
                    }

                    m_instanceCertificate = m_configuration.SecurityConfiguration.ApplicationCertificate.Find(true);
                }

                // check for valid certificate.
                if (m_instanceCertificate == null)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadConfigurationError,
                        "Cannot find the application instance certificate. Store={0}, SubjectName={1}, Thumbprint={2}.",
                        m_configuration.SecurityConfiguration.ApplicationCertificate.StorePath,
                        m_configuration.SecurityConfiguration.ApplicationCertificate.SubjectName,
                        m_configuration.SecurityConfiguration.ApplicationCertificate.Thumbprint);
                }

                // check for private key.
                if (!m_instanceCertificate.HasPrivateKey)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadConfigurationError,
                        "Do not have a privat key for the application instance certificate. Subject={0}, Thumbprint={1}.",
                        m_instanceCertificate.Subject,
                        m_instanceCertificate.Thumbprint);
                }

                //load certificate chain
                /*m_instanceCertificateChain = new X509Certificate2Collection(m_instanceCertificate);
                List<CertificateIdentifier> issuers = new List<CertificateIdentifier>();
                configuration.CertificateValidator.GetIssuers(m_instanceCertificate, issuers);
                for (int i = 0; i < issuers.Count; i++)
                {
                    m_instanceCertificateChain.Add(issuers[i].Certificate);
                }*/
            }

            // initialize the message context.
            ServiceMessageContext messageContext = channel.MessageContext;

            if (messageContext != null)
            {
                m_namespaceUris = messageContext.NamespaceUris;
                m_serverUris    = messageContext.ServerUris;
                m_factory       = messageContext.Factory;
            }    
            else
            {
                m_namespaceUris = new NamespaceTable();
                m_serverUris    = new StringTable();
                m_factory       = ServiceMessageContext.GlobalContext.Factory;
            }

            // set the default preferred locales.
            m_preferredLocales = new string[] { CultureInfo.CurrentCulture.Name };

            // create a context to use.
            m_systemContext = new SystemContext();

            m_systemContext.SystemHandle = this;
            m_systemContext.EncodeableFactory = m_factory;
            m_systemContext.NamespaceUris = m_namespaceUris;
            m_systemContext.ServerUris = m_serverUris;
            m_systemContext.TypeTable = this.TypeTree;
            m_systemContext.PreferredLocales = null;
            m_systemContext.SessionId = null;
            m_systemContext.UserIdentity = null;
        }
        /// <summary>
        /// Imports a QualifiedName
        /// </summary>
        private Opc.Ua.QualifiedName ImportQualifiedName(string source, NamespaceTable namespaceUris)
        {
            if (String.IsNullOrEmpty(source))
            {
                return Opc.Ua.QualifiedName.Null;
            }

            Opc.Ua.QualifiedName qname = Opc.Ua.QualifiedName.Parse(source);

            if (qname.NamespaceIndex > 0)
            {
                ushort namespaceIndex = ImportNamespaceIndex(qname.NamespaceIndex, namespaceUris);
                qname = new Opc.Ua.QualifiedName(qname.Name, namespaceIndex);
            }

            return qname;
        }
Exemple #13
0
        /// <summary>
        /// Imports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.DataTypeDefinition2 Import(Opc.Ua.Export.DataTypeDefinition source, NamespaceTable namespaceUris)
        {
            if (source == null)
            {
                return(null);
            }

            Opc.Ua.DataTypeDefinition2 definition = new Opc.Ua.DataTypeDefinition2();

            definition.Name             = ImportQualifiedName(source.Name, namespaceUris);
            definition.SymbolicName     = source.SymbolicName;
            definition.DataTypeModifier = DataTypeModifier.None;

            if (source.IsOptionSet)
            {
                definition.DataTypeModifier = DataTypeModifier.OptionSet;
            }
            else if (source.IsUnion)
            {
                definition.DataTypeModifier = DataTypeModifier.Union;
            }

            if (source.Field != null)
            {
                List <Opc.Ua.DataTypeDefinitionField> fields = new List <Opc.Ua.DataTypeDefinitionField>();

                foreach (DataTypeField field in source.Field)
                {
                    Opc.Ua.DataTypeDefinitionField output = new Opc.Ua.DataTypeDefinitionField();

                    output.Name         = field.Name;
                    output.SymbolicName = field.SymbolicName;
                    output.Description  = Import(field.Description);
                    output.DataType     = ImportNodeId(field.DataType, namespaceUris, true);
                    output.ValueRank    = field.ValueRank;
                    output.Value        = field.Value;

                    fields.Add(output);
                }

                definition.Fields = fields;
            }

            return(definition);
        }
        /// <summary>
        /// Imports a ExpandedNodeId
        /// </summary>
        private Opc.Ua.ExpandedNodeId ImportExpandedNodeId(string source, NamespaceTable namespaceUris, StringTable serverUris)
        {
            if (String.IsNullOrEmpty(source))
            {
                return Opc.Ua.ExpandedNodeId.Null;
            }

            // parse the node.
            Opc.Ua.ExpandedNodeId nodeId = Opc.Ua.ExpandedNodeId.Parse(source);

            if (nodeId.ServerIndex <= 0 && nodeId.NamespaceIndex <= 0 && String.IsNullOrEmpty(nodeId.NamespaceUri))
            {
                return nodeId;
            }

            uint serverIndex = ImportServerIndex(nodeId.ServerIndex, serverUris);
            ushort namespaceIndex = ImportNamespaceIndex(nodeId.NamespaceIndex, namespaceUris);

            if (serverIndex > 0)
            {
                string namespaceUri = nodeId.NamespaceUri;

                if (String.IsNullOrEmpty(nodeId.NamespaceUri))
                {
                    namespaceUri = namespaceUris.GetString(namespaceIndex);
                }

                nodeId = new Opc.Ua.ExpandedNodeId(nodeId.Identifier, 0, namespaceUri, serverIndex);
                return nodeId;
            }


            nodeId = new Opc.Ua.ExpandedNodeId(nodeId.Identifier, namespaceIndex, null, 0);
            return nodeId;
        }
Exemple #15
0
        /// <summary>
        /// Returns the node ids for a set of relative paths.
        /// </summary>
        /// <param name="session">An open session with the server to use.</param>
        /// <param name="startNodeId">The starting node for the relative paths.</param>
        /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param>
        /// <param name="relativePaths">The relative paths.</param>
        /// <returns>A collection of local nodes.</returns>
        public static List <NodeId> TranslateBrowsePaths(
            Session session,
            NodeId startNodeId,
            NamespaceTable namespacesUris,
            params string[] relativePaths)
        {
            // build the list of browse paths to follow by parsing the relative paths.
            BrowsePathCollection browsePaths = new BrowsePathCollection();

            if (relativePaths != null)
            {
                for (int ii = 0; ii < relativePaths.Length; ii++)
                {
                    BrowsePath browsePath = new BrowsePath();

                    // The relative paths used indexes in the namespacesUris table. These must be
                    // converted to indexes used by the server. An error occurs if the relative path
                    // refers to a namespaceUri that the server does not recognize.

                    // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object
                    // allows the parser to look up the server's NodeId for the ReferenceType.

                    browsePath.RelativePath = RelativePath.Parse(
                        relativePaths[ii],
                        session.TypeTree,
                        namespacesUris,
                        session.NamespaceUris);

                    browsePath.StartingNode = startNodeId;

                    browsePaths.Add(browsePath);
                }
            }

            // make the call to the server.
            BrowsePathResultCollection results;
            DiagnosticInfoCollection   diagnosticInfos;

            ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds(
                null,
                browsePaths,
                out results,
                out diagnosticInfos);

            // ensure that the server returned valid results.
            Session.ValidateResponse(results, browsePaths);
            Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);

            // collect the list of node ids found.
            List <NodeId> nodes = new List <NodeId>();

            for (int ii = 0; ii < results.Count; ii++)
            {
                // check if the start node actually exists.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    nodes.Add(null);
                    continue;
                }

                // an empty list is returned if no node was found.
                if (results[ii].Targets.Count == 0)
                {
                    nodes.Add(null);
                    continue;
                }

                // Multiple matches are possible, however, the node that matches the type model is the
                // one we are interested in here. The rest can be ignored.
                BrowsePathTarget target = results[ii].Targets[0];

                if (target.RemainingPathIndex != UInt32.MaxValue)
                {
                    nodes.Add(null);
                    continue;
                }

                // The targetId is an ExpandedNodeId because it could be node in another server.
                // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId.
                nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris));
            }

            // return whatever was found.
            return(nodes);
        }
Exemple #16
0
        /// <summary>
        /// Exports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.Export.DataTypeDefinition Export(Opc.Ua.UADataTypeDefinition source, NamespaceTable namespaceUris)
        {
            if (source == null)
            {
                return(null);
            }

            DataTypeDefinition definition = new DataTypeDefinition();

            definition.Name         = Export(source.Name, namespaceUris);
            definition.SymbolicName = source.SymbolicName;
            definition.BaseType     = Export(source.BaseType, namespaceUris);

            if (source.Fields != null)
            {
                List <Opc.Ua.Export.DataTypeField> fields = new List <DataTypeField>();

                foreach (DataTypeDefinitionField field in source.Fields)
                {
                    Opc.Ua.Export.DataTypeField output = new Opc.Ua.Export.DataTypeField();

                    output.Name         = field.Name;
                    output.SymbolicName = field.SymbolicName;
                    output.Description  = Export(new Opc.Ua.LocalizedText[] { field.Description });

                    if (NodeId.IsNull(field.DataType))
                    {
                        output.DataType = Export(DataTypeIds.BaseDataType, namespaceUris);
                    }
                    else
                    {
                        output.DataType = Export(field.DataType, namespaceUris);
                    }

                    output.ValueRank  = field.ValueRank;
                    output.Value      = field.Value;
                    output.Definition = Export(field.Definition, namespaceUris);

                    fields.Add(output);
                }

                definition.Field = fields.ToArray();
            }

            return(definition);
        }
Exemple #17
0
        private void BoilerCB_SelectedIndexChanged(object sender, EventArgs e)
        {
            try
            {
                if (m_session == null)
                {
                    return;
                }

                if (m_subscription != null)
                {
                    m_session.RemoveSubscription(m_subscription);
                    m_subscription = null;
                }

                ReferenceDescription boiler = (ReferenceDescription)BoilerCB.SelectedItem;

                if (boiler == null)
                {
                    return;
                }

                m_subscription = new Subscription();

                m_subscription.PublishingEnabled          = true;
                m_subscription.PublishingInterval         = 1000;
                m_subscription.Priority                   = 1;
                m_subscription.KeepAliveCount             = 10;
                m_subscription.LifetimeCount              = 20;
                m_subscription.MaxNotificationsPerPublish = 1000;

                m_session.AddSubscription(m_subscription);
                m_subscription.Create();

                NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
                wellKnownNamespaceUris.Append(Namespaces.Boiler);

                string[] browsePaths = new string[]
                {
                    "1:PipeX001/1:FTX001/1:Output",
                    "1:DrumX001/1:LIX001/1:Output",
                    "1:PipeX002/1:FTX002/1:Output",
                    "1:LCX001/1:SetPoint",
                };

                List <NodeId> nodes = ClientUtils.TranslateBrowsePaths(
                    m_session,
                    (NodeId)boiler.NodeId,
                    wellKnownNamespaceUris,
                    browsePaths);

                Control[] controls = new Control[]
                {
                    InputPipeFlowTB,
                    DrumLevelTB,
                    OutputPipeFlowTB,
                    DrumLevelSetPointTB
                };

                for (int ii = 0; ii < nodes.Count; ii++)
                {
                    controls[ii].Text = "---";

                    if (nodes[ii] != null)
                    {
                        MonitoredItem monitoredItem = new MonitoredItem();
                        monitoredItem.StartNodeId   = nodes[ii];
                        monitoredItem.AttributeId   = Attributes.Value;
                        monitoredItem.Handle        = controls[ii];
                        monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification);
                        m_subscription.AddItem(monitoredItem);
                    }
                }

                m_subscription.ApplyChanges();
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Exemple #18
0
        static UANodeSet ExportNodeSet(UANodeSet nodeSet, NodeSetModel nodesetModel, Dictionary <string, NodeSetModel> nodesetModels, Dictionary <string, string> aliases)
        {
            nodesetModel.UpdateIndices();
            var namespaceUris = nodesetModel.AllNodesByNodeId.Values.Select(v => v.Namespace).Distinct().ToList();

            var requiredModels = new List <ModelTableEntry>();

            NamespaceTable namespaces;

            // Ensure OPC UA model is the first one
            if (nodeSet.NamespaceUris?.Any() == true)
            {
                namespaces = new NamespaceTable(nodeSet.NamespaceUris);
            }
            else
            {
                // Ensure OPC UA model is the first one
                namespaces = new NamespaceTable(new[] { strOpcNamespaceUri });
            }
            foreach (var nsUri in namespaceUris)
            {
                namespaces.GetIndexOrAppend(nsUri);
            }
            HashSet <string> nodeIdsUsed = new HashSet <string>();
            var items = ExportAllNodes(nodesetModel, aliases, namespaces, nodeIdsUsed);

            // remove unused aliases
            var usedAliases = aliases.Where(pk => nodeIdsUsed.Contains(pk.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);

            // Add aliases for all nodeids from other namespaces
            var  currentNodeSetNamespaceIndex = namespaces.GetIndex(nodesetModel.ModelUri);
            bool bAliasesAdded = false;

            foreach (var nodeId in nodeIdsUsed)
            {
                var parsedNodeId = NodeId.Parse(nodeId);
                if (parsedNodeId.NamespaceIndex != currentNodeSetNamespaceIndex)
                {
                    if (!usedAliases.ContainsKey(nodeId))
                    {
                        var namespaceUri  = namespaces.GetString(parsedNodeId.NamespaceIndex);
                        var nodeIdWithUri = new ExpandedNodeId(parsedNodeId, namespaceUri).ToString();
                        var nodeModel     = nodesetModels.Select(nm => nm.Value.AllNodesByNodeId.TryGetValue(nodeIdWithUri, out var model) ? model : null).Where(n => n != null).FirstOrDefault();
                        var displayName   = nodeModel.DisplayName?.FirstOrDefault()?.Text;
                        if (displayName != null && !usedAliases.ContainsValue(displayName))
                        {
                            usedAliases.Add(nodeId, displayName);
                            aliases.Add(nodeId, displayName);
                            bAliasesAdded = true;
                        }
                    }
                }
            }

            var aliasList = usedAliases
                            .Select(alias => new NodeIdAlias {
                Alias = alias.Value, Value = alias.Key
            })
                            .OrderBy(kv => kv.Value)
                            .ToList();

            nodeSet.Aliases = aliasList.ToArray();

            if (bAliasesAdded)
            {
                // Re-export with new aliases
                items = ExportAllNodes(nodesetModel, aliases, namespaces, null);
            }

            var allNamespaces = namespaces.ToArray();

            nodeSet.NamespaceUris = allNamespaces.Where(ns => ns != strOpcNamespaceUri).ToArray();
            foreach (var uaNamespace in allNamespaces.Except(namespaceUris))
            {
                if (!requiredModels.Any(m => m.ModelUri == uaNamespace))
                {
                    if (nodesetModels.TryGetValue(uaNamespace, out var requiredNodeSetModel))
                    {
                        var requiredModel = new ModelTableEntry
                        {
                            ModelUri        = uaNamespace,
                            Version         = requiredNodeSetModel.Version,
                            PublicationDate = requiredNodeSetModel.PublicationDate != null?DateTime.SpecifyKind(requiredNodeSetModel.PublicationDate.Value, DateTimeKind.Utc) : default,
Exemple #19
0
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return(Opc.Ua.NodeId.Create(MemoryBuffer.ObjectTypes.MemoryBufferType, MemoryBuffer.Namespaces.MemoryBuffer,
                                 namespaceUris));
 }
Exemple #20
0
 /// <summary>
 /// Returns the id of the default data type node for the instance.
 /// </summary>
 protected override NodeId GetDefaultDataTypeId(NamespaceTable namespaceUris)
 {
     return(Opc.Ua.NodeId.Create(Opc.Ua.DataTypes.BaseDataType, Opc.Ua.Namespaces.OpcUa, namespaceUris));
 }
        /// <summary>
        ///  Imports a NodeId
        /// </summary>
        private Opc.Ua.NodeId ImportNodeId(string source, NamespaceTable namespaceUris, bool lookupAlias)
        {
            if (String.IsNullOrEmpty(source))
            {
                return Opc.Ua.NodeId.Null;
            }

            // lookup alias.
            if (lookupAlias && this.Aliases != null)
            {
                for (int ii = 0; ii < this.Aliases.Length; ii++)
                {
                    if (this.Aliases[ii].Alias == source)
                    {
                        source = this.Aliases[ii].Value;
                        break;
                    }
                }
            }

            // parse the string.
            Opc.Ua.NodeId nodeId = Opc.Ua.NodeId.Parse(source);

            if (nodeId.NamespaceIndex > 0)
            {
                ushort namespaceIndex = ImportNamespaceIndex(nodeId.NamespaceIndex, namespaceUris);
                nodeId = new Opc.Ua.NodeId(nodeId.Identifier, namespaceIndex);
            }

            return nodeId;
        }
        /// <summary>
        /// Exports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.Export.DataTypeDefinition Export(Opc.Ua.DataTypeDefinition source, NamespaceTable namespaceUris)
        {
            if (source == null)
            {
                return null;
            }

            DataTypeDefinition definition = new DataTypeDefinition();

            definition.Name = Export(source.Name, namespaceUris);
            definition.SymbolicName = source.SymbolicName;
            definition.BaseType = Export(source.BaseType, namespaceUris);

            if (source.Fields != null)
            {
                List<Opc.Ua.Export.DataTypeField> fields = new List<DataTypeField>();

                foreach (DataTypeDefinitionField field in source.Fields)
                {
                    Opc.Ua.Export.DataTypeField output = new Opc.Ua.Export.DataTypeField();

                    output.Name = field.Name;
                    output.SymbolicName = field.SymbolicName;
                    output.Description = Export(new Opc.Ua.LocalizedText[] { field.Description });

                    if (NodeId.IsNull(field.DataType))
                    {
                        output.DataType = Export(DataTypeIds.BaseDataType, namespaceUris);
                    }
                    else
                    {
                        output.DataType = Export(field.DataType, namespaceUris);
                    }

                    output.ValueRank = field.ValueRank;
                    output.Value = field.Value;
                    output.Definition = Export(field.Definition, namespaceUris);

                    fields.Add(output);
                }

                definition.Field = fields.ToArray();
            }

            return definition;
        }
        /// <summary>
        /// Exports a ExpandedNodeId
        /// </summary>
        private string Export(Opc.Ua.ExpandedNodeId source, NamespaceTable namespaceUris, StringTable serverUris)
        {
            if (Opc.Ua.NodeId.IsNull(source))
            {
                return String.Empty;
            }

            if (source.ServerIndex <= 0 && source.NamespaceIndex <= 0 && String.IsNullOrEmpty(source.NamespaceUri))
            {
                return source.ToString();
            }

            ushort namespaceIndex = 0;

            if (String.IsNullOrEmpty(source.NamespaceUri))
            {
                namespaceIndex = ExportNamespaceIndex(source.NamespaceIndex, namespaceUris);
            }
            else
            {
                namespaceIndex = ExportNamespaceUri(source.NamespaceUri, namespaceUris);
            }

            uint serverIndex = ExportServerIndex(source.ServerIndex, serverUris);
            source = new Opc.Ua.ExpandedNodeId(source.Identifier, namespaceIndex, null, serverIndex);
            return source.ToString();
        }
Exemple #24
0
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return(NodeId.Create(VariableTypes.MemoryTagType, Namespaces.MemoryBuffer, namespaceUris));
 }
        /// <summary>
        /// Exports a QualifiedName
        /// </summary>
        private string Export(Opc.Ua.QualifiedName source, NamespaceTable namespaceUris)
        {
            if (Opc.Ua.QualifiedName.IsNull(source))
            {
                return String.Empty;
            }

            if (source.NamespaceIndex > 0)
            {
                ushort namespaceIndex = ExportNamespaceIndex(source.NamespaceIndex, namespaceUris);
                source = new Opc.Ua.QualifiedName(source.Name, namespaceIndex);
            }

            return source.ToString();
        }
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return Opc.Ua.NodeId.Create(ObjectTypeTest.ObjectTypes.ComplexObjectType, ObjectTypeTest.Namespaces.cas, namespaceUris);
 }
        /// <summary>
        /// Imports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.DataTypeDefinition Import(Opc.Ua.Export.DataTypeDefinition source, NamespaceTable namespaceUris)
        {
            if (source == null)
            {
                return null;
            }

            Opc.Ua.DataTypeDefinition definition = new Opc.Ua.DataTypeDefinition();

            definition.Name = ImportQualifiedName(source.Name, namespaceUris);
            definition.SymbolicName = source.SymbolicName;
            definition.BaseType = ImportQualifiedName(source.BaseType, namespaceUris);

            if (source.Field != null)
            {
                List<Opc.Ua.DataTypeDefinitionField> fields = new List<Opc.Ua.DataTypeDefinitionField>();

                foreach (DataTypeField field in source.Field)
                {
                    Opc.Ua.DataTypeDefinitionField output = new Opc.Ua.DataTypeDefinitionField();

                    output.Name = field.Name;
                    output.SymbolicName = field.SymbolicName;
                    output.Description = Import(field.Description);
                    output.DataType = ImportNodeId(field.DataType, namespaceUris, true);
                    output.ValueRank = field.ValueRank;
                    output.Value = field.Value;
                    output.Definition = Import(field.Definition, namespaceUris);

                    fields.Add(output);
                }

                definition.Fields = fields;
            }

            return definition;
        }
        /// <summary>
        /// Replaces the test nodes in the list.
        /// </summary>        
        public void ReplaceNodeList(IList<TestNode> nodes, IList<ILocalNode> newNodes, NamespaceTable namespaceUris)
        {
            nodes.Clear();

            if (newNodes == null)
            {
                return;
            }

            List<string> exportedUris = new List<string>();

            if (NamespaceUris != null)
            {
                exportedUris.AddRange(NamespaceUris);
            }
                
            for (int ii = 0; ii < newNodes.Count; ii++)
            {
                ILocalNode newNode = newNodes[ii];

                NodeId nodeId = newNode.NodeId;

                if (namespaceUris != null && nodeId.NamespaceIndex > 1)
                {
                    string uri = namespaceUris.GetString(nodeId.NamespaceIndex);
                    
                    if (uri != null)
                    {
                        bool found = false;

                        for (int jj = 0; jj < exportedUris.Count; ii++)
                        {
                            if (exportedUris[jj] == uri)
                            {
                                nodeId = new NodeId(nodeId.Identifier, (ushort)(jj+2));
                                found = true;
                                break;
                            }
                        }

                        if (!found)
                        {
                            exportedUris.Add(uri);
                            nodeId = new NodeId(nodeId.Identifier, (ushort)(exportedUris.Count+1));
                        }
                    }
                }

                TestNode testNode = new TestNode();

                testNode.Id = nodeId.ToString();
                testNode.Name = newNode.BrowseName.ToString();

                nodes.Add(testNode);
            }

            NamespaceUris = new ListOfString();
            NamespaceUris.AddRange(exportedUris);
        }
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return(Opc.Ua.NodeId.Create(Quickstarts.DataTypes.Types.ObjectTypes.DriverType, Quickstarts.DataTypes.Types.Namespaces.DataTypes, namespaceUris));
 }
        /// <summary>
        /// Initializes the binding.
        /// </summary>
        /// <param name="namespaceUris">The namespace uris.</param>
        /// <param name="factory">The factory.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="description">The description.</param>
        public UaSoapXmlBinding(
            NamespaceTable        namespaceUris,
            EncodeableFactory     factory,
            EndpointConfiguration configuration,
            EndpointDescription   description)
        :
            base(namespaceUris, factory, configuration)
        {                       
            if (description != null && description.SecurityMode != MessageSecurityMode.None)
            {
                SymmetricSecurityBindingElement bootstrap = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateMutualCertificateBindingElement();
                
                bootstrap.MessageProtectionOrder       = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
                bootstrap.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                bootstrap.IncludeTimestamp             = true;
                bootstrap.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                bootstrap.RequireSignatureConfirmation = false;
                bootstrap.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;

                bootstrap.SetKeyDerivation(true);
                
                m_security = (SymmetricSecurityBindingElement)SecurityBindingElement.CreateSecureConversationBindingElement(bootstrap, true);
                
                m_security.MessageProtectionOrder       = MessageProtectionOrder.EncryptBeforeSign;
                m_security.DefaultAlgorithmSuite        = SecurityPolicies.ToSecurityAlgorithmSuite(description.SecurityPolicyUri);
                m_security.IncludeTimestamp             = true;
                m_security.KeyEntropyMode               = SecurityKeyEntropyMode.CombinedEntropy;
                m_security.MessageSecurityVersion       = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10;
                m_security.RequireSignatureConfirmation = false;
                m_security.SecurityHeaderLayout         = SecurityHeaderLayout.Strict;

                m_security.SetKeyDerivation(true);
            }
            
            m_encoding  = new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressing10, Encoding.UTF8);
           
            // WCF does not distinguish between arrays and byte string.
            int maxArrayLength = configuration.MaxArrayLength;

            if (configuration.MaxArrayLength < configuration.MaxByteStringLength)
            {
                maxArrayLength = configuration.MaxByteStringLength;
            }

            m_encoding.ReaderQuotas.MaxArrayLength         = maxArrayLength;
            m_encoding.ReaderQuotas.MaxStringContentLength = configuration.MaxStringLength;
            m_encoding.ReaderQuotas.MaxBytesPerRead        = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxDepth               = Int32.MaxValue;
            m_encoding.ReaderQuotas.MaxNameTableCharCount  = Int32.MaxValue;

            m_transport = new HttpTransportBindingElement();

            m_transport.AllowCookies           = false;
            m_transport.AuthenticationScheme   = System.Net.AuthenticationSchemes.Anonymous;
            m_transport.BypassProxyOnLocal     = true;
            m_transport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            m_transport.KeepAliveEnabled       = true;
            m_transport.ManualAddressing       = false;
            m_transport.MaxBufferPoolSize      = Int32.MaxValue;
            m_transport.MaxBufferSize          = configuration.MaxMessageSize;
            m_transport.MaxReceivedMessageSize = configuration.MaxMessageSize;
            m_transport.TransferMode           = TransferMode.Buffered;
            m_transport.UseDefaultWebProxy     = false;
        }
        /// <summary>
        /// Exports a namespace index.
        /// </summary>
        private ushort ExportNamespaceIndex(ushort namespaceIndex, NamespaceTable namespaceUris)
        {
            // nothing special required for indexes 0.
            if (namespaceIndex < 1)
            {
                return namespaceIndex;
            }

            // return a bad value if parameters are bad.
            if (namespaceUris == null || namespaceUris.Count <= namespaceIndex)
            {
                return UInt16.MaxValue;
            }

            // find an existing index.
            int count = 1;
            string targetUri = namespaceUris.GetString(namespaceIndex);

            if (this.NamespaceUris != null)
            {
                for (int ii = 0; ii < this.NamespaceUris.Length; ii++)
                {
                    if (this.NamespaceUris[ii] == targetUri)
                    {
                        return (ushort)(ii+1); // add 1 to adjust for the well-known URIs which are not stored.
                    }
                }

                count += this.NamespaceUris.Length;
            }

            // add a new entry.
            string[] uris = new string[count];

            if (this.NamespaceUris != null)
            {
                Array.Copy(this.NamespaceUris, uris, count - 1);
            }

            uris[count-1] = targetUri;
            this.NamespaceUris = uris;

            // return the new index.
            return (ushort)count;
        }
Exemple #32
0
 /// <summary>
 /// Returns the id of the default type definition node for the instance.
 /// </summary>
 protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris)
 {
     return(Opc.Ua.NodeId.Create(ITSOPCCourseCode.OPCUA.SampleServer.ObjectTypes.BikeType, ITSOPCCourseCode.OPCUA.SampleServer.Namespaces.SamplePlant, namespaceUris));
 }
        /// <summary>
        /// Returns the node ids of the test nodes in the list.
        /// </summary>
        public List<NodeId> GetNodeList(IList<TestNode> nodes, NamespaceTable namespaceUris)
        {
            List<NodeId> nodeIds = new List<NodeId>();

            if (nodes != null)
            {
                for (int ii = 0; ii < nodes.Count; ii++)
                {
                    TestNode node = nodes[ii];

                    if (node == null || String.IsNullOrEmpty(node.Id))
                    {
                        continue;
                    }

                    try
                    {
                        NodeId nodeId = NodeId.Parse(node.Id);

                        // translate namespace index.
                        if (nodeId.NamespaceIndex > 1 && namespaceUris != null)
                        {
                            string uri = null;

                            if (NamespaceUris != null && NamespaceUris.Count >= nodeId.NamespaceIndex-2)
                            {
                                uri = NamespaceUris[nodeId.NamespaceIndex-2];
                            }

                            if (uri != null)
                            {
                                int index = namespaceUris.GetIndex(uri);

                                if (index >= 0)
                                {
                                    nodeId = new NodeId(nodeId.Identifier, (ushort)index);
                                }
                            }
                        }

                        nodeIds.Add(nodeId);
                    }
                    catch
                    {
                        // ignore parsing errors.
                    }
                }
            }

            return nodeIds;
        }
        /// <summary>
        /// Exports a namespace index.
        /// </summary>
        private ushort ImportNamespaceIndex(ushort namespaceIndex, NamespaceTable namespaceUris)
        {
            // nothing special required for indexes 0 and 1.
            if (namespaceIndex < 1)
            {
                return namespaceIndex;
            }

            // return a bad value if parameters are bad.
            if (namespaceUris == null || this.NamespaceUris == null || this.NamespaceUris.Length <= namespaceIndex-1)
            {
                return UInt16.MaxValue;
            }

            // find or append uri.
            return namespaceUris.GetIndexOrAppend(this.NamespaceUris[namespaceIndex-1]);
        }
Exemple #35
0
        /// <summary>
        /// Calls the TraslateBrowsePathsToNodeIds service to get the nodeIds for each of the Relative Paths in the list
        /// </summary>
        /// <param name="RelativePaths">The List of Relative Paths</param>
        public BrowsePathResultCollection GetBrowseTargets(List<String> RelativePaths)
        {
            BrowsePathCollection browsePaths = new BrowsePathCollection();
            NamespaceTable clientUris = null;
            try
            {
                clientUris = new NamespaceTable(m_configFile.SavedNamespaceTable);
            }
            catch (Exception)
            {
                return null;
            }

            foreach (string relativePath in RelativePaths)
            {
                BrowsePath browsePath = new BrowsePath();
                browsePath.RelativePath = RelativePath.Parse(relativePath, m_session.TypeTree, clientUris, m_session.NamespaceUris);
                browsePath.StartingNode = Objects.Server;
                browsePaths.Add(browsePath);
            }

            BrowsePathResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = m_session.TranslateBrowsePathsToNodeIds(
                null,
                browsePaths,
                out results,
                out diagnosticInfos);

            // ensure that the server returned valid results.
            Session.ValidateResponse(results, browsePaths);
            Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);

            return results;
        }
        /// <summary>
        /// Exports a namespace uri.
        /// </summary>
        private ushort ExportNamespaceUri(string namespaceUri, NamespaceTable namespaceUris)
        {
            // return a bad value if parameters are bad.
            if (namespaceUris == null)
            {
                return UInt16.MaxValue;
            }

            int namespaceIndex = namespaceUris.GetIndex(namespaceUri);

            // nothing special required for the first two URIs.
            if (namespaceIndex == 0)
            {
                return (ushort)namespaceIndex;
            }

            // find an existing index.
            int count = 1;;

            if (this.NamespaceUris != null)
            {
                for (int ii = 0; ii < this.NamespaceUris.Length; ii++)
                {
                    if (this.NamespaceUris[ii] == namespaceUri)
                    {
                        return (ushort)(ii + 1); // add 1 to adjust for the well-known URIs which are not stored.
                    }
                }

                count += this.NamespaceUris.Length;
            }

            // add a new entry.
            string[] uris = new string[count];

            if (this.NamespaceUris != null)
            {
                Array.Copy(this.NamespaceUris, uris, count - 1);
            }

            uris[count - 1] = namespaceUri;
            this.NamespaceUris = uris;

            // return the new index.
            return (ushort)(count + 1);
        }
Exemple #37
0
        /// <summary>
        /// Returns the node ids for a set of relative paths.
        /// </summary>
        /// <param name="session">An open session with the server to use.</param>
        /// <param name="startNodeId">The starting node for the relative paths.</param>
        /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param>
        /// <param name="relativePaths">The relative paths.</param>
        /// <returns>A collection of local nodes.</returns>
        public static List<NodeId> TranslateBrowsePaths(
            Session session,
            NodeId startNodeId,
            NamespaceTable namespacesUris,
            params string[] relativePaths)
        {
            // build the list of browse paths to follow by parsing the relative paths.
            BrowsePathCollection browsePaths = new BrowsePathCollection();

            if (relativePaths != null)
            {
                for (int ii = 0; ii < relativePaths.Length; ii++)
                {
                    BrowsePath browsePath = new BrowsePath();

                    // The relative paths used indexes in the namespacesUris table. These must be 
                    // converted to indexes used by the server. An error occurs if the relative path
                    // refers to a namespaceUri that the server does not recognize.

                    // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object
                    // allows the parser to look up the server's NodeId for the ReferenceType.

                    browsePath.RelativePath = RelativePath.Parse(
                        relativePaths[ii],
                        session.TypeTree,
                        namespacesUris,
                        session.NamespaceUris);

                    browsePath.StartingNode = startNodeId;

                    browsePaths.Add(browsePath);
                }
            }

            // make the call to the server.
            BrowsePathResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds(
                null,
                browsePaths,
                out results,
                out diagnosticInfos);

            // ensure that the server returned valid results.
            Session.ValidateResponse(results, browsePaths);
            Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);

            // collect the list of node ids found.
            List<NodeId> nodes = new List<NodeId>();

            for (int ii = 0; ii < results.Count; ii++)
            {
                // check if the start node actually exists.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    nodes.Add(null);
                    continue;
                }

                // an empty list is returned if no node was found.
                if (results[ii].Targets.Count == 0)
                {
                    nodes.Add(null);
                    continue;
                }

                // Multiple matches are possible, however, the node that matches the type model is the
                // one we are interested in here. The rest can be ignored.
                BrowsePathTarget target = results[ii].Targets[0];

                if (target.RemainingPathIndex != UInt32.MaxValue)
                {
                    nodes.Add(null);
                    continue;
                }

                // The targetId is an ExpandedNodeId because it could be node in another server. 
                // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId.
                nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris));
            }

            // return whatever was found.
            return nodes;
        }
        /// <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;
        }
Exemple #39
0
        /// <summary>
        /// Sets the object members to default values.
        /// </summary>
        private void Initialize()
        {
            m_sessionTimeout        = 0;
            m_namespaceUris         = new NamespaceTable();
            m_serverUris            = new StringTable();
            m_factory               = EncodeableFactory.GlobalFactory;
            m_nodeCache             = new NodeCache(this);
            m_configuration         = null;
            m_instanceCertificate   = null;
            m_endpoint              = null;
            m_subscriptions         = new List<Subscription>();
            m_dictionaries          = new Dictionary<NodeId,DataDictionary>();
            m_acknowledgementsToSend = new SubscriptionAcknowledgementCollection();
            m_latestAcknowledgementsSent = new Dictionary<uint, uint>();
            m_identityHistory       = new List<IUserIdentity>();
            m_outstandingRequests   = new LinkedList<AsyncRequestState>();
            m_keepAliveInterval     = 5000;
            
            m_defaultSubscription = new Subscription();

            m_defaultSubscription.DisplayName        = "Subscription";
            m_defaultSubscription.PublishingInterval = 1000;
            m_defaultSubscription.KeepAliveCount     = 10;
            m_defaultSubscription.LifetimeCount      = 1000;
            m_defaultSubscription.Priority           = 255;
            m_defaultSubscription.PublishingEnabled  = true;
        }
        /// <summary>
        /// Exports a NodeId as an alias.
        /// </summary>
        private string ExportAlias(Opc.Ua.NodeId source, NamespaceTable namespaceUris)
        {
            string nodeId = Export(source, namespaceUris);

            if (!String.IsNullOrEmpty(nodeId))
            {
                if (this.Aliases != null)
                {
                    for (int ii = 0; ii < this.Aliases.Length; ii++)
                    {
                        if (this.Aliases[ii].Value == nodeId)
                        {
                            return this.Aliases[ii].Alias;
                        }
                    }
                }
            }

            return nodeId;
        }
        /// <summary>
        /// Exports a NodeId
        /// </summary>
        private string Export(Opc.Ua.NodeId source, NamespaceTable namespaceUris)
        {
            if (Opc.Ua.NodeId.IsNull(source))
            {
                return String.Empty;
            }

            if (source.NamespaceIndex > 0)
            {
                ushort namespaceIndex = ExportNamespaceIndex(source.NamespaceIndex, namespaceUris);
                source = new Opc.Ua.NodeId(source.Identifier, namespaceIndex);
            }

            return source.ToString();
        }
Exemple #42
0
        /// <summary>
        /// Reads the application description from the GDS.
        /// </summary>
        private ApplicationDescription Read(NodeId nodeId)
        {
            NamespaceTable wellKnownNamespaceUris = new NamespaceTable();

            wellKnownNamespaceUris.Append(Namespaces.OpcUaGds);

            string[] browsePaths = new string[]
            {
                "1:ApplicationName",
                "1:ApplicationType",
                "1:ApplicationUri",
                "1:ProductUri",
                "1:GatewayServerUri",
                "1:DiscoveryUrls"
            };

            List <NodeId> propertyIds = ClientUtils.TranslateBrowsePaths(
                ServerCTRL.Session,
                nodeId,
                wellKnownNamespaceUris,
                browsePaths);

            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            foreach (NodeId propertyId in propertyIds)
            {
                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = propertyId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            ServerCTRL.Session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out results,
                out diagnosticInfos);

            ClientBase.ValidateResponse(results, nodesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead);

            ApplicationDescription application = new ApplicationDescription();

            application.ApplicationName  = results[0].GetValue <LocalizedText>(null);
            application.ApplicationType  = (ApplicationType)results[1].GetValue <int>((int)ApplicationType.Server);
            application.ApplicationUri   = results[2].GetValue <string>(null);
            application.ProductUri       = results[3].GetValue <string>(null);
            application.GatewayServerUri = results[4].GetValue <string>(null);

            string[] discoveryUrls = results[5].GetValue <string[]>(null);

            if (discoveryUrls != null)
            {
                application.DiscoveryUrls = new StringCollection(discoveryUrls);
            }

            return(application);
        }