Exemplo n.º 1
0
        public SimpleNodeManager(IServerInternal server, ApplicationConfiguration configuration)
            : base(server, configuration)
        {
            SystemContext.NodeIdFactory = this;

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

            foreach (string nodesetFile in BrowserController._nodeSetFilenames)
            {
                // workaround for bug https://github.com/dotnet/runtime/issues/67622
                File.WriteAllText(nodesetFile, File.ReadAllText(nodesetFile).Replace("<Value/>", "<Value xsi:nil='true' />"));

                using (Stream stream = new FileStream(nodesetFile, FileMode.Open))
                {
                    UANodeSet nodeSet = UANodeSet.Read(stream);
                    if ((nodeSet.NamespaceUris != null) && (nodeSet.NamespaceUris.Length > 0))
                    {
                        foreach (string ns in nodeSet.NamespaceUris)
                        {
                            if (!namespaces.Contains(ns))
                            {
                                namespaces.Add(ns);
                            }
                        }
                    }

                    DTDL.Generate(nodeSet);
                }
            }

            NamespaceUris = namespaces.ToArray();
        }
        public void CreateUAModelContextAddressSpaceContextNull()
        {
            UANodeSet      _tm = TestData.CreateNodeSetModel();
            UAModelContext _mc = new UAModelContext(_tm.Aliases, _tm.NamespaceUris, null);

            Assert.IsNotNull(_mc);
        }
Exemplo n.º 3
0
        public static UANodeSet getInformationModel(string filename)
        {
            string    path                = filename;
            UANodeSet InformationModel    = new UANodeSet();
            string    executebaleLocation = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
            string    location            = Path.Combine(executebaleLocation, path);
            string    xml = System.IO.File.ReadAllText(path);

            XmlSerializer serializer = new XmlSerializer(typeof(UANodeSet));

            using (TextReader reader = new StringReader(xml))
            {
                try
                {
                    InformationModel = (UANodeSet)serializer.Deserialize(reader);
                }
                catch (Exception ex)
                {
                    MessageBoxResult result = MessageBox.Show("Error in XML formatting\n\n" + ex.ToString(),
                                                              "Error",
                                                              MessageBoxButton.OK);
                    throw ex;
                }
            }
            return(InformationModel);
        }
        public void AddressSpaceContextImportUANodeSetNullTestMethod1()
        {
            IAddressSpaceContext _as = new AddressSpaceContext(x => { });
            UANodeSet            _ns = null;

            _as.ImportUANodeSet(_ns);
        }
Exemplo n.º 5
0
        public void ExportBrowseNameTest()
        {
            UANodeSet _tm = TestData.CreateNodeSetModel();
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();

            _asMock.Setup(x => x.GetNamespace(0)).Returns <ushort>(x => "tempuri.org");
            UANode _nodeFactory = new UAVariable()
            {
                NodeId       = "ns=1;i=47",
                BrowseName   = "EURange",
                ParentNodeId = "ns=1;i=43",
                DataType     = "i=884",
                DisplayName  = new XML.LocalizedText[] { new XML.LocalizedText()
                                                         {
                                                             Value = "EURange"
                                                         } }
            };
            UANodeContext _node = new UANodeContext(NodeId.Parse("ns=1;i=47"), _asMock.Object);

            _node.Update(_nodeFactory, x => Assert.Fail());
            XmlQualifiedName _resolvedName = _node.ExportNodeBrowseName();

            _asMock.Verify(x => x.GetNamespace(0), Times.Once);
            Assert.IsNotNull(_resolvedName);
            Assert.AreEqual <string>("tempuri.org:EURange", _resolvedName.ToString());
        }
Exemplo n.º 6
0
        private void ImportNodeset2Xml(IDictionary <NodeId, IList <IReference> > externalReferences, string resourcepath, int pass)
        {
            // workaround for bug https://github.com/dotnet/runtime/issues/67622
            File.WriteAllText(resourcepath, File.ReadAllText(resourcepath).Replace("<Value/>", "<Value xsi:nil='true' />"));

            using (Stream stream = new FileStream(resourcepath, FileMode.Open))
            {
                UANodeSet nodeSet = UANodeSet.Read(stream);

                NodeStateCollection predefinedNodes = new NodeStateCollection();
                nodeSet.Import(SystemContext, predefinedNodes);
# if DEBUG
                DebugOutput(nodeSet, predefinedNodes);
#endif
                for (int i = 0; i < predefinedNodes.Count; i++)
                {
                    try
                    {
                        AddPredefinedNode(SystemContext, predefinedNodes[i]);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Pass " + pass.ToString() + ": Importing node ns=" + predefinedNodes[i].NodeId.NamespaceIndex + ";i=" + predefinedNodes[i].NodeId.Identifier + " (" + predefinedNodes[i].DisplayName + ") failed with error: " + ex.Message);
                    }
                }
            }
Exemplo n.º 7
0
        public void ReadUADefinedTypesTestMethod()
        {
            UANodeSet _standard = UANodeSet.ReadUADefinedTypes();

            Assert.IsNotNull(_standard);
            Assert.IsNull(_standard.NamespaceUris);
        }
Exemplo n.º 8
0
        public virtual void Initialise(CustomNodeManager2 nodeManager)
        {
            ApplicationNodeManager = nodeManager;
            if (string.IsNullOrEmpty(ResourcePath))
            {
                return;
            }
            NamespaceUris = new List <string>();
            NodeStateCollection predefinedNodeStateCollection = new NodeStateCollection();
            Stream    stream    = new FileStream(ResourcePath, FileMode.Open);
            UANodeSet uaNodeSet = UANodeSet.Read(stream);

            NamespaceUris.AddRange(ApplicationNodeManager.NamespaceUris);
            // Update namespace table
            if (uaNodeSet.NamespaceUris != null)
            {
                foreach (string namespaceUri in uaNodeSet.NamespaceUris)
                {
                    NamespaceUris.Add(namespaceUri);
                    ApplicationNodeManager.SystemContext.NamespaceUris.GetIndexOrAppend(namespaceUri);
                }
            }
            // Update server table
            if (uaNodeSet.ServerUris != null)
            {
                foreach (string serverUri in uaNodeSet.ServerUris)
                {
                    ServerUris.Add(serverUri);
                    ApplicationNodeManager.SystemContext.ServerUris.GetIndexOrAppend(serverUri);
                }
            }
            uaNodeSet.Import(ApplicationNodeManager.SystemContext, predefinedNodeStateCollection);
            NodeStateCollection = predefinedNodeStateCollection;
        }
Exemplo n.º 9
0
        public static UANodeSet CreateNodeSetModel()
        {
            UANodeSet _ns = new UANodeSet()
            {
                NamespaceUris = new string[] { @"http://cas.eu/UA/Demo/" },
                Aliases       = new NodeIdAlias[] {
                    new NodeIdAlias()
                    {
                        Alias = "Boolean", Value = "i=1"
                    },
                    new NodeIdAlias()
                    {
                        Alias = "HasSubtype", Value = "i=45"
                    }
                },
                Items = new UANode[]
                {
                    new UAReferenceType()
                    {
                        NodeId = "ns=1;i=985", BrowseName = "1:FlowTo", DisplayName = new LocalizedText[] { new LocalizedText()
                                                                                                            {
                                                                                                                Value = "FlowTo"
                                                                                                            } }, Symmetric = true,
                        References = new Reference[] { new Reference()
                                                       {
                                                           ReferenceType = "HasSubtype", IsForward = false, Value = "i=32"
                                                       } }
                    }
                }
            };

            return(_ns);
        }
Exemplo n.º 10
0
        public void OpcUaNodeSet2TestMethod()
        {
            UANodeSet _standard = Extensions.LoadResource <UANodeSet>(Extensions.UADefinedTypesName);

            Assert.IsNotNull(_standard);
            Assert.IsNull(_standard.NamespaceUris);
        }
        public void CreateUAModelContextNodeAliasNull()
        {
            UANodeSet _tm = TestData.CreateNodeSetModel();

            _tm.Aliases = null;
            Mock <IAddressSpaceBuildContext> _asMock = new Mock <IAddressSpaceBuildContext>();
            UAModelContext _mc = new UAModelContext(_tm, _asMock.Object);
        }
Exemplo n.º 12
0
        public void CreateUAModelContextNodeAliasNull()
        {
            UANodeSet _tm = TestData.CreateNodeSetModel();

            _tm.Aliases = null;
            IAddressSpaceBuildContext _as = new AddressSpaceFixture();
            UAModelContext            _mc = new UAModelContext(_tm, _as);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Imports a part of the OPC UA Address Space contained in the <see cref="UANodeSet" /> object model.
 /// </summary>
 /// <param name="model">The model to be imported.</param>
 /// <exception cref="System.ArgumentNullException">model;the model cannot be null</exception>
 void IAddressSpaceContext.ImportUANodeSet(UANodeSet model)
 {
     m_TraceEvent(TraceMessage.DiagnosticTraceMessage("Entering AddressSpaceContextService.ImportUANodeSet - importing from object model."));
     if (model == null)
     {
         throw new ArgumentNullException("model", "the model cannot be null");
     }
     ImportNodeSet(model);
 }
Exemplo n.º 14
0
        public void OpcUaNodeSet2TestMethod()
        {
            FileInfo _testDataFileInfo = new FileInfo(@"XMLModels\CorrectModels\ReferenceTest\ReferenceTest.NodeSet2.xml");

            Assert.IsTrue(_testDataFileInfo.Exists);
            UANodeSet _model = UANodeSet.ReadModelFile(_testDataFileInfo);

            Assert.IsNotNull(_model);
        }
Exemplo n.º 15
0
 public UANodeConverter(string filename, NamespaceTable SessionNamespaceURIs)
 {
     using (Stream stream = new FileStream(filename, FileMode.Open)){
         m_UANodeset       = UANodeSet.Read(stream);
         m_aliases         = m_UANodeset.Aliases;
         m_namespaceURIs   = m_UANodeset.NamespaceUris;
         out_nodeset       = new List <Node>();
         session_namespace = SessionNamespaceURIs;
     }
 }
Exemplo n.º 16
0
        public static List <ImportOPCModel> OrderImportsByDependencies(List <ImportOPCModel> importRequest)
        {
            var importsAndModels = importRequest.Select(importRequest =>
            {
                using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(importRequest.Data.Replace("<Value/>", "<Value xsi:nil='true' />"))))
                {
                    var nodeSet        = UANodeSet.Read(ms);
                    var modelUri       = nodeSet.Models?[0].ModelUri;
                    var requiredModels = nodeSet.Models?.SelectMany(m => m.RequiredModel?.Select(rm => rm.ModelUri) ?? new List <string>())?.ToList();
                    return(importRequest, modelUri, requiredModels);
                }
            }).ToList();

            var orderedImports = new List <(ImportOPCModel, string, List <string>)>();
            var standalone     = importsAndModels.Where(imr => imr.requiredModels.Any() != true).ToList();

            orderedImports.AddRange(standalone);
            foreach (var imr in standalone)
            {
                importsAndModels.Remove(imr);
            }

            bool modelAdded;

            do
            {
                modelAdded = false;
                for (int i = importsAndModels.Count - 1; i >= 0; i--)
                {
                    var  imr = importsAndModels[i];
                    bool bDependenciesSatisfied = true;
                    foreach (var dependency in imr.requiredModels)
                    {
                        if (!orderedImports.Any(imr => imr.Item2 == dependency))
                        {
                            bDependenciesSatisfied = false;
                            continue;
                        }
                    }
                    if (bDependenciesSatisfied)
                    {
                        orderedImports.Add(imr);
                        importsAndModels.RemoveAt(i);
                        modelAdded = true;
                    }
                }
            } while (importsAndModels.Count > 0 && modelAdded);

            //Assert.True(modelAdded, $"{importsAndModels.Count} nodesets require models not in the list.");
            orderedImports.AddRange(importsAndModels);
            var orderedImportRequest = orderedImports.Select(irm => irm.Item1).ToList();

            return(orderedImportRequest);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="AddressSpaceContext" /> class.
        /// </summary>
        /// <param name="traceEvent">Encapsulates an action to trace the progress and validation issues.</param>
        /// <exception cref="System.ArgumentNullException">traceEvent - cannot be null.</exception>
        public AddressSpaceContext(Action <TraceMessage> traceEvent)
        {
            m_TraceEvent     = traceEvent ?? throw new ArgumentNullException("traceEvent");
            m_NamespaceTable = new NamespaceTable();
            m_TraceEvent(TraceMessage.DiagnosticTraceMessage("Entering AddressSpaceContext creator - starting creation the OPC UA Address Space."));
            UANodeSet _standard = UANodeSet.ReadUADefinedTypes();

            m_TraceEvent(TraceMessage.DiagnosticTraceMessage("Address Space - the OPC UA defined has been uploaded."));
            ImportNodeSet(_standard);
            m_TraceEvent(TraceMessage.DiagnosticTraceMessage("Address Space - has bee created successfully."));
        }
Exemplo n.º 18
0
        protected override NodeStateCollection LoadPredefinedNodes(ISystemContext context)
        {
            var nodeStateCollection = new NodeStateCollection();

            using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConverterSystems.Test.PredefinedNodes.xml"))
            {
                var nodeset = UANodeSet.Read(stream);
                nodeset.Import(context, nodeStateCollection);
            }
            return(nodeStateCollection);
        }
Exemplo n.º 19
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UAModelContext" /> class.
 /// </summary>
 /// <param name="model">The imported OPC UA address space model represented by the instance of <see cref="UANodeSet"/>.</param>
 /// <param name="addressSpaceContext">The address space context represented by an instance of <see cref="IAddressSpaceBuildContext"/>.</param>
 /// <exception cref="ArgumentNullException">addressSpaceContext
 /// or
 /// model.Aliases
 /// </exception>
 internal UAModelContext(UANodeSet model, IAddressSpaceBuildContext addressSpaceContext)
 {
     AddressSpaceContext = addressSpaceContext ?? throw new ArgumentNullException(nameof(addressSpaceContext));
     if (model is null)
     {
         throw new ArgumentNullException(nameof(model));
     }
     AddNamespaceUriTable(model.NamespaceUris);
     AddAliases(model.Aliases);
     model.NamespaceUris = model.NamespaceUris ?? new string[] { };
 }
Exemplo n.º 20
0
        public void NamespaceTestMethod1()
        {
            List <TraceMessage> _trace = new List <NodeSet.TraceMessage>();
            UANodeSet           _ns    = TestData.CreateNodeSetModel();
            int _diagnosticCounter     = 0;

            Assert.IsTrue(_ns.NamespaceUris.Length >= 1, "Wrong test data - NamespaceUris must contain more then 2 items");
            OldModel.ModelDesign _md = NodeSet.AddressSpaceContextService.CreateInstance
                                           (_ns.NamespaceUris[0], x => x.ImportNodeSet(_ns, y => TraceDiagnostic(y, _trace, ref _diagnosticCounter), true), z => TraceDiagnostic(z, _trace, ref _diagnosticCounter));
            Assert.AreEqual <int>(2, _md.Namespaces.Length);
            Assert.AreEqual <int>(0, _trace.Where <TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count <TraceMessage>());
        }
Exemplo n.º 21
0
        public void TraceMessageTestMethod()
        {
            List <TraceMessage> _trace   = new List <NodeSet.TraceMessage>();
            int       _diagnosticCounter = 0;
            UANodeSet _ns = TestData.CreateNodeSetModel();

            Assert.IsTrue(_ns.NamespaceUris.Length >= 1, "Wrong test data - NamespaceUris must contain more then 2 items");
            OldModel.ModelDesign _md = NodeSet.AddressSpaceContextService.CreateInstance
                                           (_ns.NamespaceUris[0], x => x.ImportNodeSet(_ns, y => TraceDiagnostic(y, _trace, ref _diagnosticCounter), true), z => TraceDiagnostic(z, _trace, ref _diagnosticCounter));
            Assert.IsTrue(_trace.Count == 0);
            Assert.IsTrue(_diagnosticCounter > 0);
        }
Exemplo n.º 22
0
        //Helpers
        private static void ValidateAndExportModelPreparation(out UANodeSet _ns, out IAddressSpaceContext _as)
        {
            _ns = TestData.CreateNodeSetModel();
            List <TraceMessage> _trace = new List <TraceMessage>();
            int _diagnosticCounter     = 0;

            Assert.AreEqual <int>(0, _trace.Where <TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count <TraceMessage>());
            Assert.IsTrue(_ns.NamespaceUris.Length >= 1, "Wrong test data - NamespaceUris must contain more then 2 items");
            _as = new AddressSpaceContext(x => { Helpers.TraceHelper.TraceDiagnostic(x, _trace, ref _diagnosticCounter); });
            Assert.IsNotNull(_as);
            Assert.AreEqual <int>(0, _trace.Where <TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count <TraceMessage>());
            _as.ImportUANodeSet(_ns);
            Assert.AreEqual <int>(0, _trace.Where <TraceMessage>(x => x.BuildError.Focus != Focus.Diagnostic).Count <TraceMessage>());
        }
Exemplo n.º 23
0
        public UANodeConverter(JObject config, NamespaceTable SessionNamespaceURIs)
        {
            _config = config.ToObject <nodesConfigWrapper>().nodesLoader;

            using (Stream stream = new FileStream(_config.filename, FileMode.Open)){
                m_UANodeset       = UANodeSet.Read(stream);
                m_aliases         = m_UANodeset.Aliases;
                m_namespaceURIs   = m_UANodeset.NamespaceUris;
                out_nodeset       = new List <Node>();
                session_namespace = SessionNamespaceURIs;
            }

            selector = new NodesSelector(_config);
        }
Exemplo n.º 24
0
        private static (NamespaceTable, Dictionary <string, string>) LoadNamespaces(string file)
        {
            var namespaces = new NamespaceTable(new[] { "http://opcfoundation.org/UA/" });

            using (var nodeSetStream = File.OpenRead(file))
            {
                UANodeSet nodeSet = UANodeSet.Read(nodeSetStream);
                var       aliases = nodeSet.Aliases?.ToDictionary(a => a.Alias, a => a.Value) ?? new Dictionary <string, string>();
                foreach (var ns in nodeSet.NamespaceUris)
                {
                    namespaces.GetIndexOrAppend(ns);
                }
                return(namespaces, aliases);
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Imports a part of the OPC UA Address Space contained in the file <see cref="FileInfo" />.
        /// </summary>
        /// <param name="model">The model to be imported.</param>
        /// <exception cref="System.IO.FileNotFoundException">The imported file does not exist</exception>
        void IAddressSpaceContext.ImportUANodeSet(FileInfo model)
        {
            m_TraceEvent(TraceMessage.DiagnosticTraceMessage("Entering AddressSpaceContextService.ImportUANodeSet - importing form file"));
            if (model == null)
            {
                throw new ArgumentNullException("model", "the model cannot be null");
            }
            if (!model.Exists)
            {
                throw new FileNotFoundException("The imported file does not exist", model.FullName);
            }
            UANodeSet _nodeSet = UANodeSet.ReadModellFile(model);

            ImportNodeSet(_nodeSet);
        }
Exemplo n.º 26
0
        private void ImportNodeset2Xml(IDictionary <NodeId, IList <IReference> > externalReferences, string resourcepath)
        {
            using (Stream stream = new FileStream(resourcepath, FileMode.Open))
            {
                UANodeSet nodeSet = UANodeSet.Read(stream);

                NodeStateCollection predefinedNodes = new NodeStateCollection();
                nodeSet.Import(SystemContext, predefinedNodes);

                for (int i = 0; i < predefinedNodes.Count; i++)
                {
                    AddPredefinedNode(SystemContext, predefinedNodes[i]);
                }
            }
        }
Exemplo n.º 27
0
        public void ExportBrowseNameTest()
        {
            UANodeSet _tm = TestData.CreateNodeSetModel();
            IAddressSpaceBuildContext _as           = new AddressSpaceFixture();
            UAModelContext            _mc           = new UAModelContext(_tm, _as);
            XmlQualifiedName          _resolvedName = _mc.ExportBrowseName(null, null);

            Assert.IsNull(_resolvedName);
            _resolvedName = _mc.ExportBrowseName(null, UAInformationModel.DataTypes.BaseDataType);
            Assert.IsNull(_resolvedName);
            _resolvedName = _mc.ExportBrowseName(new NodeId(UAInformationModel.DataTypes.BaseDataType, 0).ToString(), UAInformationModel.DataTypes.BaseDataType);
            Assert.IsNull(_resolvedName);
            _resolvedName = _mc.ExportBrowseName(new NodeId(UAInformationModel.DataTypes.Structure, 0).ToString(), UAInformationModel.DataTypes.BaseDataType);
            Assert.IsNotNull(_resolvedName);
            Assert.AreEqual(@"http://opcfoundation.org/UA/:Structure", _resolvedName.ToString());
        }
Exemplo n.º 28
0
        // MIHO (2021-10-05): added this function in course of bug fixing
        // see: https://github.com/admin-shell-io/aasx-package-explorer/issues/414
        public static UANodeSet getInformationModel(Stream fileStream)
        {
            UANodeSet     InformationModel = new UANodeSet();
            XmlSerializer serializer       = new XmlSerializer(typeof(UANodeSet));

            try
            {
                InformationModel = (UANodeSet)serializer.Deserialize(fileStream);
            }
            catch (Exception ex)
            {
                throw new Exception("Error in accessing or XML formatting\n\n"
                                    + ex.ToString());
            }
            return(InformationModel);
        }
Exemplo n.º 29
0
        public StationNodeManager(IServerInternal server, ApplicationConfiguration configuration)
            : base(server, configuration)
        {
            SystemContext.NodeIdFactory = this;

            using (Stream stream = new FileStream("Station.NodeSet2.xml", FileMode.Open))
            {
                UANodeSet nodeSet = UANodeSet.Read(stream);
                NamespaceUris = nodeSet.NamespaceUris;
            }

            m_namespaceIndex = (ushort)(Server.NamespaceUris.Count - 1);
            m_lastUsedId     = 0;

            m_stationClock = new Timer(Tick, this, Timeout.Infinite, (int)m_actualCycleTime);
        }
Exemplo n.º 30
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AddressSpaceContext" /> class.
        /// </summary>
        /// <param name="traceEvent">Encapsulates an action to trace the progress and validation issues.</param>
        /// <exception cref="System.ArgumentNullException">traceEvent - cannot be null.</exception>
        public AddressSpaceContext(Action <TraceMessage> traceEvent)
        {
            if (traceEvent == null)
            {
                throw new ArgumentNullException("traceEvent");
            }
            m_NamespaceTable = new NamespaceTable(traceEvent);
            m_TraceEvent     = x => { };
            traceEvent(TraceMessage.DiagnosticTraceMessage("Entering AddressSpaceContext creator - starting address space validation."));
            UANodeSet _standard = UANodeSet.ReadUADefinedTypes();

            Debug.Assert(_standard != null);
            traceEvent(TraceMessage.DiagnosticTraceMessage("AddressSpaceContext - uploading the OPC UA defined types."));
            ImportNodeSet(_standard);
            m_TraceEvent = traceEvent;
            m_TraceEvent(TraceMessage.DiagnosticTraceMessage("AddressSpaceContext - has bee created successfully."));
        }