Esempio n. 1
0
 public static ReferenceDescriptionCollection Browse(Session session, BrowseDescription nodeToBrowse, bool throwOnError)
 {
     try
       {
     var descriptionCollection = new ReferenceDescriptionCollection();
     var nodesToBrowse = new BrowseDescriptionCollection { nodeToBrowse };
     BrowseResultCollection results;
     DiagnosticInfoCollection diagnosticInfos;
     session.Browse(null, null, 0U, nodesToBrowse, out results, out diagnosticInfos);
     ClientBase.ValidateResponse(results, nodesToBrowse);
     ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse);
     while (!StatusCode.IsBad(results[0].StatusCode))
     {
       for (var index = 0; index < results[0].References.Count; ++index)
     descriptionCollection.Add(results[0].References[index]);
       if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
     return descriptionCollection;
       var continuationPoints = new ByteStringCollection();
       continuationPoints.Add(results[0].ContinuationPoint);
       session.BrowseNext(null, false, continuationPoints, out results, out diagnosticInfos);
       ClientBase.ValidateResponse(results, continuationPoints);
       ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);
     }
     throw new ServiceResultException(results[0].StatusCode);
       }
       catch (Exception ex)
       {
     if (throwOnError)
       throw new ServiceResultException(ex, 2147549184U);
     return null;
       }
 }
Esempio n. 2
0
        /// <summary>
        /// Finds an element identified by the path from the root.
        /// </summary>
        private AeBrowseElement Find(Session session, string itemId, AeBrowseElement root, Stack <string> names, bool isArea)
        {
            string browseText = null;

            BrowsePath browsePath = new BrowsePath();

            browsePath.StartingNode = root.NodeId;

            while (names.Count > 0)
            {
                RelativePathElement path = new RelativePathElement();

                path.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasNotifier;
                path.IsInverse       = false;
                path.IncludeSubtypes = true;

                // final hop can be HasEventSource for sources.
                if (!isArea && names.Count == 1)
                {
                    path.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasEventSource;
                }

                browseText      = names.Pop();
                path.TargetName = m_mapper.GetRemoteBrowseName(browseText);
                browsePath.RelativePath.Elements.Add(path);
            }

            BrowsePathCollection browsePaths = new BrowsePathCollection();

            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);

            // check if the start node actually exists.
            if (StatusCode.IsBad(results[0].StatusCode))
            {
                return(null);
            }

            // must be exact one target.
            if (results[0].Targets.Count != 1)
            {
                return(null);
            }

            // can't be an external reference.
            BrowsePathTarget target = results[0].Targets[0];

            if (target.RemainingPathIndex != UInt32.MaxValue)
            {
                return(null);
            }

            // need to check if at the end of the tree.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = (NodeId)target.TargetId;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasEventSource;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.IncludeSubtypes = true;

            ReferenceDescriptionCollection children = ComAeUtils.Browse(session, nodeToBrowse, false);

            if (!isArea)
            {
                if (children != null && children.Count > 0)
                {
                    return(null);
                }
            }
            else
            {
                if (children == null || children.Count == 0)
                {
                    return(null);
                }
            }

            // construct the element.
            AeBrowseElement element = new AeBrowseElement();

            element.NodeId     = (NodeId)target.TargetId;
            element.ItemId     = itemId;
            element.BrowseText = browseText;
            element.IsArea     = isArea;

            return(element);
        }
Esempio n. 3
0
        /// <summary>
        /// Adds a target to the tree control.
        /// </summary>
        private void AddReferences(TreeNode parent, ReferenceDescriptionCollection references)
        {
            foreach (ReferenceDescription reference in references)
            {
                if (reference.ReferenceTypeId.IsNullNodeId)
                {
                    Utils.Trace("Reference {0} has null reference type id", reference.DisplayName);
                    continue;
                }

                ReferenceTypeNode typeNode = m_browser.Session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode;
                if (typeNode == null)
                {
                    Utils.Trace("Reference {0} has invalid reference type id.", reference.DisplayName);
                    continue;
                }

                if (m_browser.BrowseDirection == BrowseDirection.Forward && !reference.IsForward ||
                    m_browser.BrowseDirection == BrowseDirection.Inverse && reference.IsForward)
                {
                    Utils.Trace("Reference's IsForward value is: {0}, but the browse direction is: {1}; for reference {2}", reference.IsForward, m_browser.BrowseDirection, reference.DisplayName);
                    continue;
                }

                if (reference.NodeId == null || reference.NodeId.IsNull)
                {
                    Utils.Trace("The node id of the reference {0} is NULL.", reference.DisplayName);
                    continue;
                }

                if (reference.BrowseName == null || reference.BrowseName.Name == null)
                {
                    Utils.Trace("Browse name is empty for reference {0}", reference.DisplayName);
                    continue;
                }

                if (!Enum.IsDefined(typeof(Opc.Ua.NodeClass), reference.NodeClass) || reference.NodeClass == NodeClass.Unspecified)
                {
                    Utils.Trace("Node class is an unknown or unspecified value, for reference {0}", reference.DisplayName);
                    continue;
                }

                if (m_browser.NodeClassMask != 0 && m_browser.NodeClassMask != 255)
                {
                    if (reference.TypeDefinition == null || reference.TypeDefinition.IsNull)
                    {
                        Utils.Trace("Type definition is null for reference {0}", reference.DisplayName);
                        continue;
                    }
                }

                // suppress duplicate references.
                if (!m_showReferences)
                {
                    bool exists = false;

                    foreach (TreeNode existingChild in parent.Nodes)
                    {
                        ReferenceDescription existingReference = existingChild.Tag as ReferenceDescription;

                        if (existingReference != null)
                        {
                            if (existingReference.NodeId == reference.NodeId)
                            {
                                exists = true;
                                break;
                            }
                        }
                    }

                    if (exists)
                    {
                        continue;
                    }
                }

                string text = GetTargetText(reference);
                string icon = GuiUtils2.GetTargetIcon(m_browser.Session, reference);

                TreeNode container = parent;

                if (m_showReferences)
                {
                    container = FindReferenceTypeContainer(parent, reference);
                }

                if (container != null)
                {
                    TreeNode child = AddNode(container, reference, text, icon);
                    child.Nodes.Add(new TreeNode());
                }
            }
        }
Esempio n. 4
0
        /// <see cref="BaseTreeCtrl.EnableMenuItems" />
        protected override void EnableMenuItems(TreeNode clickedNode)
        {
            BrowseOptionsMI.Enabled   = true;
            ShowReferencesMI.Enabled  = true;
            SelectMI.Visible          = m_allowPick;
            SelectSeparatorMI.Visible = m_allowPick;

            if (clickedNode != null)
            {
                // do nothing if an error is detected.
                if (m_browser.Session.KeepAliveStopped)
                {
                    return;
                }

                SelectMI.Enabled         = true;
                SelectItemMI.Enabled     = true;
                SelectChildrenMI.Enabled = clickedNode.Nodes.Count > 0;
                BrowseRefreshMI.Enabled  = true;

                ReferenceDescription reference = clickedNode.Tag as ReferenceDescription;

                if (reference != null)
                {
                    BrowseMI.Enabled         = (reference.NodeId != null && !reference.NodeId.IsAbsolute);
                    ViewAttributesMI.Enabled = true;

                    NodeId nodeId = ExpandedNodeId.ToNodeId(reference.NodeId, m_browser.Session.NamespaceUris);

                    INode node = m_browser.Session.ReadNode(nodeId);

                    byte accessLevel   = 0;
                    byte eventNotifier = 0;
                    bool executable    = false;

                    VariableNode variableNode = node as VariableNode;

                    if (variableNode != null)
                    {
                        accessLevel = variableNode.UserAccessLevel;
                    }

                    ObjectNode objectNode = node as ObjectNode;

                    if (objectNode != null)
                    {
                        eventNotifier = objectNode.EventNotifier;
                    }

                    ViewNode viewNode = node as ViewNode;

                    if (viewNode != null)
                    {
                        eventNotifier = viewNode.EventNotifier;
                    }

                    MethodNode methodNode = node as MethodNode;

                    if (methodNode != null)
                    {
                        executable = methodNode.UserExecutable;
                    }

                    ReadMI.Visible          = false;
                    HistoryReadMI.Visible   = false;
                    WriteMI.Visible         = false;
                    HistoryUpdateMI.Visible = false;
                    EncodingsMI.Visible     = false;
                    SubscribeMI.Visible     = false;
                    CallMI.Visible          = false;

                    if (accessLevel != 0)
                    {
                        ReadMI.Visible          = true;
                        HistoryReadMI.Visible   = true;
                        WriteMI.Visible         = true;
                        HistoryUpdateMI.Visible = true;
                        EncodingsMI.Visible     = true;
                        SubscribeMI.Visible     = m_SessionTreeCtrl != null;

                        if ((accessLevel & (byte)AccessLevels.CurrentRead) != 0)
                        {
                            ReadMI.Enabled         = true;
                            EncodingsMI.Enabled    = true;
                            SubscribeMI.Enabled    = true;
                            SubscribeNewMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.CurrentWrite) != 0)
                        {
                            WriteMI.Enabled     = true;
                            EncodingsMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((accessLevel & (byte)AccessLevels.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }
                    }

                    if (eventNotifier != 0)
                    {
                        HistoryReadMI.Visible   = true;
                        HistoryUpdateMI.Visible = true;
                        SubscribeMI.Visible     = true;

                        if ((eventNotifier & (byte)EventNotifiers.HistoryRead) != 0)
                        {
                            HistoryReadMI.Enabled = true;
                        }

                        if ((eventNotifier & (byte)EventNotifiers.HistoryWrite) != 0)
                        {
                            HistoryUpdateMI.Enabled = true;
                        }

                        SubscribeMI.Enabled    = (eventNotifier & (byte)EventNotifiers.SubscribeToEvents) != 0;
                        SubscribeNewMI.Enabled = SubscribeMI.Enabled;
                    }

                    if (methodNode != null)
                    {
                        CallMI.Visible = true;
                        CallMI.Enabled = executable;
                    }

                    if (variableNode != null && EncodingsMI.Enabled)
                    {
                        ReferenceDescriptionCollection encodings = m_browser.Session.ReadAvailableEncodings(variableNode.NodeId);

                        if (encodings.Count == 0)
                        {
                            EncodingsMI.Visible = false;
                        }
                    }

                    if (SubscribeMI.Enabled)
                    {
                        while (SubscribeMI.DropDown.Items.Count > 1)
                        {
                            SubscribeMI.DropDown.Items.RemoveAt(SubscribeMI.DropDown.Items.Count - 1);
                        }

                        foreach (Subscription subscription in m_browser.Session.Subscriptions)
                        {
                            if (subscription.Created)
                            {
                                ToolStripItem item = SubscribeMI.DropDown.Items.Add(subscription.DisplayName);
                                item.Click += new EventHandler(Subscription_Click);
                                item.Tag    = subscription;
                            }
                        }
                    }
                }
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Collects the fields for the instance node.
        /// </summary>
        private static void CollectInstanceDeclarations(
            Session session,
            NodeId typeId,
            InstanceDeclaration parent,
            List <InstanceDeclaration> instances,
            IDictionary <string, InstanceDeclaration> map)
        {
            // find the children.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            if (parent == null)
            {
                nodeToBrowse.NodeId = typeId;
            }
            else
            {
                nodeToBrowse.NodeId = parent.NodeId;
            }

            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasChild;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask   = (uint)(NodeClass.Object | NodeClass.Variable | NodeClass.Method);
            nodeToBrowse.ResultMask      = (uint)BrowseResultMask.All;

            // ignore any browsing errors.
            ReferenceDescriptionCollection references = ClientUtils.Browse(session, nodeToBrowse, false);

            if (references == null)
            {
                return;
            }

            // process the children.
            List <NodeId> nodeIds = new List <NodeId>();
            List <InstanceDeclaration> children = new List <InstanceDeclaration>();

            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                if (reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                // create a new declaration.
                InstanceDeclaration child = new InstanceDeclaration();

                child.RootTypeId = typeId;
                child.NodeId     = (NodeId)reference.NodeId;
                child.BrowseName = reference.BrowseName;
                child.NodeClass  = reference.NodeClass;

                if (!LocalizedText.IsNullOrEmpty(reference.DisplayName))
                {
                    child.DisplayName = reference.DisplayName.Text;
                }
                else
                {
                    child.DisplayName = reference.BrowseName.Name;
                }

                if (parent != null)
                {
                    child.BrowsePath            = new QualifiedNameCollection(parent.BrowsePath);
                    child.BrowsePathDisplayText = Utils.Format("{0}/{1}", parent.BrowsePathDisplayText, reference.BrowseName);
                    child.DisplayPath           = Utils.Format("{0}/{1}", parent.DisplayPath, reference.DisplayName);
                }
                else
                {
                    child.BrowsePath            = new QualifiedNameCollection();
                    child.BrowsePathDisplayText = Utils.Format("{0}", reference.BrowseName);
                    child.DisplayPath           = Utils.Format("{0}", reference.DisplayName);
                }

                child.BrowsePath.Add(reference.BrowseName);

                // check if reading an overridden declaration.
                InstanceDeclaration overriden = null;

                if (map.TryGetValue(child.BrowsePathDisplayText, out overriden))
                {
                    child.OverriddenDeclaration = overriden;
                }

                map[child.BrowsePathDisplayText] = child;

                // add to list.
                children.Add(child);
                nodeIds.Add(child.NodeId);
            }

            // check if nothing more to do.
            if (children.Count == 0)
            {
                return;
            }

            // find the modelling rules.
            List <NodeId> modellingRules = FindTargetOfReference(session, nodeIds, Opc.Ua.ReferenceTypeIds.HasModellingRule, false);

            if (modellingRules != null)
            {
                for (int ii = 0; ii < nodeIds.Count; ii++)
                {
                    children[ii].ModellingRule = modellingRules[ii];

                    // if the modelling rule is null then the instance is not part of the type declaration.
                    if (NodeId.IsNull(modellingRules[ii]))
                    {
                        map.Remove(children[ii].BrowsePathDisplayText);
                    }
                }
            }

            // update the descriptions.
            UpdateInstanceDescriptions(session, children, false);

            // recusively collect instance declarations for the tree below.
            for (int ii = 0; ii < children.Count; ii++)
            {
                if (!NodeId.IsNull(children[ii].ModellingRule))
                {
                    instances.Add(children[ii]);
                    CollectInstanceDeclarations(session, typeId, children[ii], instances, map);
                }
            }
        }
Esempio n. 6
0
        /// <summary>
        /// Browses the address space and returns the references found.
        /// </summary>
        public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError)
        {
            try
            {
                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();

                // construct browse request.
                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
                nodesToBrowse.Add(nodeToBrowse);

                // start the browse operation.
                BrowseResultCollection   results         = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                session.Browse(
                    null,
                    view,
                    0,
                    nodesToBrowse,
                    out results,
                    out diagnosticInfos);

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

                do
                {
                    // check for error.
                    if (StatusCode.IsBad(results[0].StatusCode))
                    {
                        throw new ServiceResultException(results[0].StatusCode);
                    }

                    // process results.
                    for (int ii = 0; ii < results[0].References.Count; ii++)
                    {
                        references.Add(results[0].References[ii]);
                    }

                    // check if all references have been fetched.
                    if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
                    {
                        break;
                    }

                    // continue browse operation.
                    ByteStringCollection continuationPoints = new ByteStringCollection();
                    continuationPoints.Add(results[0].ContinuationPoint);

                    session.BrowseNext(
                        null,
                        false,
                        continuationPoints,
                        out results,
                        out diagnosticInfos);

                    ClientBase.ValidateResponse(results, continuationPoints);
                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);
                }while (true);

                //return complete list.
                return(references);
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }

                return(null);
            }
        }
        public async Task BrowseAsync()
        {
            // Browse template
            var startingNode   = Objects.RootFolder;
            var browseTemplate = new BrowseDescription {
                NodeId          = startingNode,
                BrowseDirection = BrowseDirection.Forward,
                ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
                IncludeSubtypes = true,
                NodeClassMask   = 0,
                ResultMask      = (uint)BrowseResultMask.All
            };

            var requestHeader         = new RequestHeader();
            var referenceDescriptions = new ReferenceDescriptionCollection();

            var browseDescriptionCollection = ServerFixtureUtils.CreateBrowseDescriptionCollectionFromNodeId(
                new NodeIdCollection(new NodeId[] { Objects.RootFolder }),
                browseTemplate);

            while (browseDescriptionCollection.Any())
            {
                TestContext.Out.WriteLine("Browse {0} Nodes...", browseDescriptionCollection.Count);
                BrowseResultCollection allResults = new BrowseResultCollection();
                var response = await Session.BrowseAsync(
                    requestHeader, null, 5,
                    browseDescriptionCollection,
                    CancellationToken.None).ConfigureAwait(false);

                BrowseResultCollection   results         = response.Results;
                DiagnosticInfoCollection diagnosticInfos = response.DiagnosticInfos;

                allResults.AddRange(results);

                var continuationPoints = ServerFixtureUtils.PrepareBrowseNext(results);
                while (continuationPoints.Any())
                {
                    TestContext.Out.WriteLine("BrowseNext {0} Nodes...", continuationPoints.Count);
                    var nextResponse = await Session.BrowseNextAsync(requestHeader, false, continuationPoints, CancellationToken.None);

                    BrowseResultCollection browseNextResultCollection = nextResponse.Results;
                    diagnosticInfos = nextResponse.DiagnosticInfos;
                    ServerFixtureUtils.ValidateResponse(response.ResponseHeader);
                    ServerFixtureUtils.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);
                    allResults.AddRange(browseNextResultCollection);
                    continuationPoints = ServerFixtureUtils.PrepareBrowseNext(browseNextResultCollection);
                }

                // Build browse request for next level
                var browseTable = new NodeIdCollection();
                foreach (var result in allResults)
                {
                    referenceDescriptions.AddRange(result.References);
                    foreach (var reference in result.References)
                    {
                        browseTable.Add(ExpandedNodeId.ToNodeId(reference.NodeId, Session.NamespaceUris));
                    }
                }
                browseDescriptionCollection = ServerFixtureUtils.CreateBrowseDescriptionCollectionFromNodeId(browseTable, browseTemplate);
            }

            referenceDescriptions.Sort((x, y) => (x.NodeId.CompareTo(y.NodeId)));

            // read values
            var nodesToRead = new ReadValueIdCollection(referenceDescriptions.Select(r =>
                                                                                     new ReadValueId()
            {
                NodeId      = ExpandedNodeId.ToNodeId(r.NodeId, Session.NamespaceUris),
                AttributeId = Attributes.Value
            }));

            // test reads
            TestContext.Out.WriteLine("Test Read Nodes...");
            var readResponse = await Session.ReadAsync(requestHeader, 0, TimestampsToReturn.Neither, nodesToRead, CancellationToken.None).ConfigureAwait(false);

            // test register nodes
            TestContext.Out.WriteLine("Test Register Nodes...");
            var nodesToRegister  = new NodeIdCollection(nodesToRead.Select(n => n.NodeId));
            var registerResponse = await Session.RegisterNodesAsync(requestHeader, nodesToRegister, CancellationToken.None).ConfigureAwait(false);

            var unregisterResponse = await Session.UnregisterNodesAsync(requestHeader, registerResponse.RegisteredNodeIds, CancellationToken.None).ConfigureAwait(false);

            // test writes
            var nodesToWrite = new WriteValueCollection();
            int ii           = 0;

            foreach (var result in readResponse.Results)
            {
                if (StatusCode.IsGood(result.StatusCode))
                {
                    var writeValue = new WriteValue()
                    {
                        AttributeId = Attributes.Value,
                        NodeId      = nodesToRead[ii].NodeId,
                        Value       = new DataValue(result.WrappedValue)
                    };
                    nodesToWrite.Add(writeValue);
                }
                ii++;
            }

            TestContext.Out.WriteLine("Test Writes...");
            var writeResponse = await Session.WriteAsync(requestHeader, nodesToWrite, CancellationToken.None).ConfigureAwait(false);

            TestContext.Out.WriteLine("Found {0} references on server.", referenceDescriptions.Count);
            ii = 0;
            foreach (var reference in referenceDescriptions)
            {
                TestContext.Out.WriteLine("NodeId {0} {1} {2} {3}", reference.NodeId, reference.NodeClass, reference.BrowseName, readResponse.Results[ii++].WrappedValue);
            }
        }
Esempio n. 8
0
        /// <summary>
        /// Verifies the references returned for a node.
        /// </summary>
        private bool VerifyReferences(
            Node node, 
            BrowseDescription description, 
            ReferenceDescriptionCollection references)
        {
            bool success = true;
                 
            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                if (reference == null)
                {
                    Log("Returned null ReferenceDescription when Browsing Node '{0}'. NodeId = {1}", node, node.NodeId);
                    success = false;
                    continue;
                }

                if (!VerifyTargetId(node, description, reference))
                {
                    success = false;
                    continue;
                }

                if (!VerifyReferenceTypeId(node, description, reference))
                {
                    success = false;
                    continue;
                }

                if (!VerifyIsForward(node, description, reference))
                {
                    success = false;
                    continue;
                }
            }

            // read the attributes to verify the reference is correct. 
            try
            {
                if (!VerifyTargetAttributes(node, description, references))
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Log(e, "Could not verify target attributes when Browsing Node '{0}'. NodeId = {1}", node, node.NodeId);
                return false;
            }
   
            // verify type definitions.
            try
            {
                if (!VerifyTypeDefinitions(node, description, references))
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Log(e, "Could not verify type definitions when Browsing Node '{0}'. NodeId = {1}", node, node.NodeId);
                return false;
            }
   
            return success;   
        }
Esempio n. 9
0
        public async Task <ActionResult> MethodCallGetParameter(string jstreeNode)
        {
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;
            var      jsonParameter  = new List <object>();
            int      parameterCount = 0;

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }
            bool retry = true;

            while (true)
            {
                try
                {
                    QualifiedName browseName = null;
                    browseName = Opc.Ua.BrowseNames.InputArguments;

                    ReferenceDescriptionCollection references = null;
                    Byte[] continuationPoint;

                    Session session = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                    session.Browse(
                        null,
                        null,
                        node,
                        1u,
                        BrowseDirection.Forward,
                        ReferenceTypeIds.HasProperty,
                        true,
                        0,
                        out continuationPoint,
                        out references);
                    if (references.Count == 1)
                    {
                        var          nodeReference = references[0];
                        VariableNode argumentsNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris)) as VariableNode;
                        DataValue    value         = session.ReadValue(argumentsNode.NodeId);

                        ExtensionObject[] argumentsList = value.Value as ExtensionObject[];
                        for (int ii = 0; ii < argumentsList.Length; ii++)
                        {
                            Argument argument       = (Argument)argumentsList[ii].Body;
                            NodeId   nodeId         = new NodeId(argument.DataType);
                            Node     dataTypeIdNode = session.ReadNode(nodeId);
                            jsonParameter.Add(new { name = argument.Name, value = argument.Value, valuerank = argument.ValueRank, arraydimentions = argument.ArrayDimensions, description = argument.Description.Text, datatype = nodeId.Identifier, typename = dataTypeIdNode.DisplayName.Text });
                        }
                        parameterCount = argumentsList.Length;
                    }
                    else
                    {
                        parameterCount = 0;
                    }

                    return(Json(new { count = parameterCount, parameter = jsonParameter }, JsonRequestBehavior.AllowGet));
                }
                catch (Exception exception)
                {
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
Esempio n. 10
0
        public async Task <ActionResult> GetChildren(string jstreeNode)
        {
            // This delimiter is used to allow the storing of the OPC UA parent node ID together with the OPC UA child node ID in jstree data structures and provide it as parameter to
            // Ajax calls.
            string[] delimiter       = { "__$__" };
            string[] jstreeNodeSplit = jstreeNode.Split(delimiter, 3, StringSplitOptions.None);
            string   node;

            if (jstreeNodeSplit.Length == 1)
            {
                node = jstreeNodeSplit[0];
            }
            else
            {
                node = jstreeNodeSplit[1];
            }

            ReferenceDescriptionCollection references;

            Byte[] continuationPoint;
            var    jsonTree = new List <object>();

            // read the currently published nodes
            Session session = null;

            string[] publishedNodes = null;
            string   endpointUrl    = null;

            try
            {
                session = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                endpointUrl    = session.ConfiguredEndpoint.EndpointUrl.AbsoluteUri;
                publishedNodes = await GetPublishedNodes(endpointUrl);

                Trace.TraceInformation("Currently is/are {0} node(s) published on endpoint '{1}'.", publishedNodes.Length, endpointUrl);
            }
            catch (Exception e)
            {
                // do nothing, since we still want to show the tree
                Trace.TraceWarning("Could not read published nodes for endpoint '{0}'.", endpointUrl);
            }

            bool retry = true;

            while (true)
            {
                try
                {
                    Stopwatch stopwatch = new Stopwatch();
                    stopwatch.Start();
                    session.Browse(
                        null,
                        null,
                        node,
                        0u,
                        BrowseDirection.Forward,
                        ReferenceTypeIds.HierarchicalReferences,
                        true,
                        0,
                        out continuationPoint,
                        out references);

                    Trace.TraceInformation("Browse {0} ms", stopwatch.ElapsedMilliseconds);

                    if (references != null)
                    {
                        var idList = new List <string>();
                        foreach (var nodeReference in references)
                        {
                            bool idFound = false;
                            foreach (var id in idList)
                            {
                                if (id == nodeReference.NodeId.ToString())
                                {
                                    idFound = true;
                                }
                            }
                            if (idFound == true)
                            {
                                continue;
                            }

                            ReferenceDescriptionCollection childReferences = null;
                            Byte[] childContinuationPoint;

                            session.Browse(
                                null,
                                null,
                                ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris),
                                0u,
                                BrowseDirection.Forward,
                                ReferenceTypeIds.HierarchicalReferences,
                                true,
                                0,
                                out childContinuationPoint,
                                out childReferences);

                            INode currentNode = null;
                            try
                            {
                                currentNode = session.ReadNode(ExpandedNodeId.ToNodeId(nodeReference.NodeId, session.NamespaceUris));
                            }
                            catch (Exception)
                            {
                                // skip this node
                                continue;
                            }

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;
                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;
                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;
                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;
                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            var isPublished = false;
                            var isRelevant  = false;
                            if (publishedNodes != null)
                            {
                                Session stationSession = await OpcSessionHelper.Instance.GetSessionAsync(Session.SessionID, (string)Session["EndpointUrl"]);

                                string urn = stationSession.ServerUris.GetString(0);
                                foreach (var nodeId in publishedNodes)
                                {
                                    if (nodeId == nodeReference.NodeId.ToString())
                                    {
                                        isPublished = true;
                                        ContosoOpcUaNode contosoOpcUaNode = Startup.Topology.GetOpcUaNode(urn, nodeId);
                                        if (contosoOpcUaNode?.Relevance != null)
                                        {
                                            isRelevant = true;
                                        }
                                    }
                                }
                            }

                            jsonTree.Add(new
                            {
                                id            = ("__" + node + delimiter[0] + nodeReference.NodeId.ToString()),
                                text          = nodeReference.DisplayName.ToString(),
                                nodeClass     = nodeReference.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = (childReferences.Count == 0) ? false : true,
                                publishedNode = isPublished,
                                relevantNode  = isRelevant
                            });
                            idList.Add(nodeReference.NodeId.ToString());
                        }

                        // If there are no children, then this is a call to read the properties of the node itself.
                        if (jsonTree.Count == 0)
                        {
                            INode currentNode = session.ReadNode(new NodeId(node));

                            byte currentNodeAccessLevel   = 0;
                            byte currentNodeEventNotifier = 0;
                            bool currentNodeExecutable    = false;

                            VariableNode variableNode = currentNode as VariableNode;

                            if (variableNode != null)
                            {
                                currentNodeAccessLevel = variableNode.UserAccessLevel;
                                if (!PermsChecker.HasPermission(Permission.ControlOpcServer))
                                {
                                    currentNodeAccessLevel = (byte)((uint)currentNodeAccessLevel & ~0x2);
                                }
                            }

                            ObjectNode objectNode = currentNode as ObjectNode;

                            if (objectNode != null)
                            {
                                currentNodeEventNotifier = objectNode.EventNotifier;
                            }

                            ViewNode viewNode = currentNode as ViewNode;

                            if (viewNode != null)
                            {
                                currentNodeEventNotifier = viewNode.EventNotifier;
                            }

                            MethodNode methodNode = currentNode as MethodNode;

                            if (methodNode != null && PermsChecker.HasPermission(Permission.ControlOpcServer))
                            {
                                currentNodeExecutable = methodNode.UserExecutable;
                            }

                            jsonTree.Add(new
                            {
                                id            = jstreeNode,
                                text          = currentNode.DisplayName.ToString(),
                                nodeClass     = currentNode.NodeClass.ToString(),
                                accessLevel   = currentNodeAccessLevel.ToString(),
                                eventNotifier = currentNodeEventNotifier.ToString(),
                                executable    = currentNodeExecutable.ToString(),
                                children      = false
                            });
                        }
                    }

                    stopwatch.Stop();
                    Trace.TraceInformation("GetChildren took {0} ms", stopwatch.ElapsedMilliseconds);

                    return(Json(jsonTree, JsonRequestBehavior.AllowGet));
                }
                catch (Exception exception)
                {
                    OpcSessionHelper.Instance.Disconnect(Session.SessionID);
                    if (!retry)
                    {
                        return(Content(CreateOpcExceptionActionString(exception)));
                    }
                    retry = false;
                }
            }
        }
Esempio n. 11
0
        /// <summary>
        ///
        /// </summary>
        private void AddSessions()
        {
            Browser browser = new Browser(m_Session);

            browser.MaxReferencesReturned = 0;
            browser.BrowseDirection       = BrowseDirection.Forward;
            browser.IncludeSubtypes       = true;
            browser.NodeClassMask         = (int)NodeClass.Object;
            browser.ContinueUntilDone     = true;
            NodeId browseid = new NodeId(Objects.Server_ServerDiagnostics_SessionsDiagnosticsSummary);

            browser.ReferenceTypeId = null;
            ReferenceDescriptionCollection refs = browser.Browse(browseid);

            foreach (ReferenceDescription rf in refs)
            {
                if (m_Session.TypeTree.IsTypeOf(new ExpandedNodeId(rf.TypeDefinition), new ExpandedNodeId(ObjectTypes.SessionDiagnosticsObjectType)))
                {
                    if (listView1.Items.IndexOfKey(rf.NodeId.ToString()) == -1)
                    {
                        ListViewItem lvi = listView1.Items.Add(rf.NodeId.ToString(), rf.DisplayName.Text.ToString(), -1);
                        lvi.Tag         = rf.NodeId;
                        lvi.IndentCount = 0;

                        string SessionID            = "SessionDiagnostics.SessionId";
                        string ClientName           = "SessionDiagnostics.ClientName";
                        string ClientConnectionTime = "SessionDiagnostics.ClientConnectionTime";

                        ListViewItem.ListViewSubItem SessionIDSubItem = lvi.SubItems.Add("");
                        SessionIDSubItem.Name = rf.NodeId.Identifier.ToString() + "." + SessionID;
                        ListViewItem.ListViewSubItem ClientNameSubItem = lvi.SubItems.Add("");
                        ClientNameSubItem.Name = rf.NodeId.Identifier.ToString() + "." + ClientName;
                        ListViewItem.ListViewSubItem ClientConnectionTimeSubItem = lvi.SubItems.Add("");
                        ClientConnectionTimeSubItem.Name = rf.NodeId.Identifier.ToString() + "." + ClientConnectionTime;

                        MonitoredItem sessionItem = new MonitoredItem(m_Subscription.DefaultItem);
                        sessionItem.StartNodeId  = (NodeId)rf.NodeId;
                        sessionItem.RelativePath = SessionID;
                        sessionItem.NodeClass    = NodeClass.Object;
                        sessionItem.AttributeId  = Attributes.Value;
                        m_Subscription.AddItem(sessionItem);
                        sessionItem.Notification += m_ItemNotification;


                        INode node = m_Session.NodeCache.Find(rf.NodeId);

                        TypedMonitoredItem SessionIDItem = new TypedMonitoredItem(m_Subscription.DefaultItem);
                        SessionIDItem.StartNodeId  = (NodeId)rf.NodeId;
                        SessionIDItem.RelativePath = SessionID;
                        SessionIDItem.NodeClass    = NodeClass.Variable;
                        SessionIDItem.AttributeId  = Attributes.Value;
                        m_Subscription.AddItem(SessionIDItem);
                        SessionIDItem.Notification += m_ItemNotification;
                        SessionIDSubItem.Tag        = SessionIDItem;
                        Utils.Trace("Adding: {0}, {1} as subitem in AddSessions()", SessionIDItem.StartNodeId.ToString(), SessionIDItem.RelativePath.ToString());


                        TypedMonitoredItem ClientNameItem = new TypedMonitoredItem(m_Subscription.DefaultItem);
                        ClientNameItem.StartNodeId  = (NodeId)rf.NodeId;
                        ClientNameItem.RelativePath = ClientName;
                        ClientNameItem.NodeClass    = NodeClass.Variable;
                        ClientNameItem.AttributeId  = Attributes.Value;
                        m_Subscription.AddItem(ClientNameItem);
                        ClientNameItem.Notification += m_ItemNotification;
                        ClientNameSubItem.Tag        = ClientNameItem;
                        Utils.Trace("Adding: {0}, {1} as subitem in AddSessions()", ClientNameItem.StartNodeId.ToString(), ClientNameItem.RelativePath.ToString());

                        DateTimeMonitoredItem ClientConnectionTimeItem = new DateTimeMonitoredItem(m_Subscription.DefaultItem);
                        ClientConnectionTimeItem.StartNodeId  = (NodeId)rf.NodeId;
                        ClientConnectionTimeItem.RelativePath = ClientConnectionTime;
                        ClientConnectionTimeItem.NodeClass    = NodeClass.Variable;
                        ClientConnectionTimeItem.AttributeId  = Attributes.Value;
                        m_Subscription.AddItem(ClientConnectionTimeItem);
                        ClientConnectionTimeItem.Notification += m_ItemNotification;
                        ClientConnectionTimeSubItem.Tag        = ClientConnectionTimeItem;
                        Utils.Trace("Adding: {0}, {1} as subitem in AddSessions()", ClientConnectionTimeItem.StartNodeId.ToString(), ClientConnectionTimeItem.RelativePath.ToString());
                    }
                    else
                    {
                        Utils.Trace("Key already exists in listview. rf.BrowseName: {0},rf.NodeId: {1}, rf.TypeDefinition: {2}", rf.BrowseName.ToString(), rf.NodeId.ToString(), rf.TypeDefinition.ToString());
                    }
                }
                else
                {
                    Utils.Trace("Unknown Object rf.BrowseName: {0},rf.NodeId: {1}, rf.TypeDefinition: {2}", rf.BrowseName.ToString(), rf.NodeId.ToString(), rf.TypeDefinition.ToString());
                }
            }
        }
        /// <summary>
        /// Adds the properties to the control.
        /// </summary>
        private void AddProperties()
        {
            // build list of properties to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            Browser browser = new Browser(m_session);

            browser.BrowseDirection   = BrowseDirection.Forward;
            browser.ReferenceTypeId   = ReferenceTypeIds.HasProperty;
            browser.IncludeSubtypes   = true;
            browser.NodeClassMask     = (int)NodeClass.Variable;
            browser.ContinueUntilDone = true;

            ReferenceDescriptionCollection references = browser.Browse(m_nodeId);

            foreach (ReferenceDescription reference in references)
            {
                ReadValueId valueId = new ReadValueId();

                valueId.NodeId       = (NodeId)reference.NodeId;
                valueId.AttributeId  = Attributes.Value;
                valueId.IndexRange   = null;
                valueId.DataEncoding = null;

                nodesToRead.Add(valueId);
            }

            // check for empty list.
            if (nodesToRead.Count == 0)
            {
                return;
            }

            // read values.
            DataValueCollection      values;
            DiagnosticInfoCollection diagnosticInfos;

            m_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                nodesToRead,
                out values,
                out diagnosticInfos);

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

            // update control.
            for (int ii = 0; ii < nodesToRead.Count; ii++)
            {
                NodeField field = new NodeField();

                field.ValueId    = nodesToRead[ii];
                field.Name       = references[ii].ToString();
                field.Value      = values[ii].Value;
                field.StatusCode = values[ii].StatusCode;

                if (diagnosticInfos != null && diagnosticInfos.Count > ii)
                {
                    field.DiagnosticInfo = diagnosticInfos[ii];
                }

                AddItem(field, "Property", -1);
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Recursively finds the targets of the specified path.
        /// </summary>
        private void GetTargets(Node start, IList <RelativePathElement> path, int index, BrowsePathResult result)
        {
            // check for invalid parameters.
            if (index >= path.Count)
            {
                return;
            }

            // look for list of references for node.
            ReferenceDescriptionCollection references = start.Handle as ReferenceDescriptionCollection;

            if (references == null || references.Count == 0)
            {
                return;
            }

            RelativePathElement element = path[index];

            // each list of references.
            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // check for a reference match.
                if (element.IsInverse == reference.IsForward)
                {
                    continue;
                }

                if (element.ReferenceTypeId != reference.ReferenceTypeId)
                {
                    if (!element.IncludeSubtypes)
                    {
                        continue;
                    }

                    if (!Session.TypeTree.IsTypeOf(reference.ReferenceTypeId, element.ReferenceTypeId))
                    {
                        continue;
                    }
                }

                // check for a browse name match.
                if (element.TargetName != reference.BrowseName)
                {
                    continue;
                }

                // check for end of list.
                if (index == path.Count - 1)
                {
                    BrowsePathTarget item = new BrowsePathTarget();
                    item.TargetId           = reference.NodeId;
                    item.RemainingPathIndex = UInt32.MaxValue;
                    result.Targets.Add(item);
                    continue;
                }

                // check for external reference.
                if (reference.NodeId.IsAbsolute)
                {
                    BrowsePathTarget item = new BrowsePathTarget();
                    item.TargetId           = reference.NodeId;
                    item.RemainingPathIndex = (uint)index + 1;
                    result.Targets.Add(item);
                    continue;
                }

                // check for targets.
                Node target = null;

                if (!AvailableNodes.TryGetValue((NodeId)reference.NodeId, out target))
                {
                    BrowsePathTarget item = new BrowsePathTarget();
                    item.TargetId           = reference.NodeId;
                    item.RemainingPathIndex = (uint)index + 1;
                    result.Targets.Add(item);
                    continue;
                }

                // recursively follow targets.
                GetTargets(target, path, index + 1, result);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// Adds a single hop path for all references for the node.
        /// </summary>
        private void AddMultiHopPaths(
            Node node,
            Node baseNode,
            IList <RelativePathElement> basePath,
            BrowsePathCollection pathsToTranslate,
            int hops)
        {
            ReferenceDescriptionCollection references = node.Handle as ReferenceDescriptionCollection;

            if (references == null)
            {
                return;
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                BrowsePath browsePath = new BrowsePath();

                browsePath.StartingNode = baseNode.NodeId;
                browsePath.Handle       = baseNode;

                if (basePath != null)
                {
                    browsePath.RelativePath.Elements.AddRange(basePath);
                }

                RelativePathElement element = new RelativePathElement();

                element.ReferenceTypeId = ReferenceTypeIds.NonHierarchicalReferences;
                element.IsInverse       = !reference.IsForward;
                element.IncludeSubtypes = true;
                element.TargetName      = reference.BrowseName;

                browsePath.RelativePath.Elements.Add(element);
                pathsToTranslate.Add(browsePath);

                // only follow forward heiarchical
                if (!Session.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HierarchicalReferences))
                {
                    continue;
                }

                element.ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences;

                // can't do anything with absolute or inverse references.
                if (!reference.IsForward || reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                // look up target
                if (browsePath.RelativePath.Elements.Count < hops)
                {
                    Node target = null;

                    if (!AvailableNodes.TryGetValue((NodeId)reference.NodeId, out target))
                    {
                        continue;
                    }

                    AddMultiHopPaths(target, baseNode, browsePath.RelativePath.Elements, pathsToTranslate, hops);
                }
            }
        }
Esempio n. 15
0
        /// <summary>
        /// Verifies that the server does no ignore the BrowseResultMask.
        /// </summary>
        private bool DoBrowseResultMaskTest()
        {
            // follow tree from each starting node.
            bool success = true;
                     
            double increment = MaxProgress/AvailableNodes.Count;
            double position  = 0;
            
            Log("Starting BrowseResultMaskTest for {0} Nodes ({1}% Coverage)", AvailableNodes.Values.Count, Configuration.Coverage);
            
            int counter = 0;

            foreach (Node node in AvailableNodes.Values)
            {          
                if (!CheckCoverage(ref counter))
                {
                    continue;
                }
                
                try
                {
                    BrowseDescription nodeToBrowse = new BrowseDescription();
                    
                    nodeToBrowse.NodeId = node.NodeId;
                    nodeToBrowse.BrowseDirection = BrowseDirection.Both;
                    nodeToBrowse.IncludeSubtypes = true;
                    nodeToBrowse.NodeClassMask = 0;
                    nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.References;
                    nodeToBrowse.ResultMask = (uint)BrowseResultMask.None;
                    
                    ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();
                    
                    if (!Browse(node, nodeToBrowse, references))
                    {
                        success = false;
                        break;
                    }
                }
                catch (Exception e)
                {
                    success = false;
                    Log(e, "BrowseResultMaskTest Failed for Node '{0}'. NodeId = {1}", node, node.NodeId);
                }

                position += increment;
                ReportProgress(position);
            }   
         
            return success;
        }
Esempio n. 16
0
        /// <summary>
        /// Browses the node and verifies the results.
        /// </summary>
        protected override bool Browse(
            Node node,
            BrowseDescription nodeToBrowse, 
            ReferenceDescriptionCollection references)
        {            
            List<Node> nodes = new List<Node>();
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
            List<ReferenceDescriptionCollection> referenceLists = new List<ReferenceDescriptionCollection>();
            
            nodes.Add(node);
            nodesToBrowse.Add(nodeToBrowse);
            referenceLists.Add(references);

            return Browse(nodes, nodesToBrowse, referenceLists);
        }
Esempio n. 17
0
        /// <summary>
        /// Browses the server node.
        /// </summary>
        private void BrowseServerNode(TreeNode treeNode)
        {
            try
            {
                tvServer.BeginUpdate();
                bool fillNodeRequired             = false;
                TreeNodeCollection nodeCollection = null;
                ServerNodeTag      serverNodeTag  = null;
                NodeId             nodeId         = null;

                if (treeNode == null)
                {
                    fillNodeRequired = true;
                    nodeCollection   = tvServer.Nodes;
                    serverNodeTag    = null;
                    nodeId           = ObjectIds.ObjectsFolder;
                }
                else if (treeNode.Tag is ServerNodeTag nodeTag)
                {
                    fillNodeRequired = !nodeTag.IsFilled;
                    nodeCollection   = treeNode.Nodes;
                    serverNodeTag    = nodeTag;
                    nodeId           = nodeTag.OpcNodeId;
                }

                if (fillNodeRequired && nodeId != null && opcSession != null)
                {
                    Browser browser = new Browser(opcSession)
                    {
                        BrowseDirection = BrowseDirection.Forward,
                        NodeClassMask   = (int)NodeClass.Variable | (int)NodeClass.Object | (int)NodeClass.Method,
                        ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences
                    };

                    ReferenceDescriptionCollection browseResults = browser.Browse(nodeId);
                    nodeCollection.Clear();

                    foreach (ReferenceDescription rd in browseResults)
                    {
                        TreeNode childNode = TreeViewUtils.CreateNode(rd.DisplayName, SelectImageKey(rd.NodeClass));
                        childNode.Tag = new ServerNodeTag(rd, opcSession.NamespaceUris);

                        // allow to expand any node
                        TreeNode emptyNode = TreeViewUtils.CreateNode(KpPhrases.EmptyNode, "empty.png");
                        childNode.Nodes.Add(emptyNode);

                        nodeCollection.Add(childNode);
                    }

                    if (serverNodeTag != null)
                    {
                        serverNodeTag.IsFilled = true;
                    }
                }
            }
            catch (Exception ex)
            {
                ScadaUiUtils.ShowError(KpPhrases.BrowseServerError + ":" + Environment.NewLine + ex.Message);
            }
            finally
            {
                tvServer.EndUpdate();
            }
        }
Esempio n. 18
0
        private void SelectMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_nodesSelected != null)
                {
                    if (NodesTV.SelectedNode == null)
                    {
                        return;
                    }

                    ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;

                    if (reference != null)
                    {
                        ReferenceDescriptionCollection collection = new ReferenceDescriptionCollection();
                        collection.Add(reference);
                        m_nodesSelected(this, new NodesSelectedEventArgs(collection));
                    }
                }        
			}
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Gets all elements for the specified references
        /// </summary>
        /// <param name="session">The session to use</param>
        /// <param name="browser">The browser to use</param>
        /// <param name="level">The level</param>
        /// <param name="references">The references to browse</param>
        /// <param name="verbose">If true the address space will be printed out to the console; otherwise not</param>
        private static void GetElements(Session session, Browser browser, uint level, ReferenceDescriptionCollection references, bool verbose)
        {
            var spaces = new StringBuilder();

            for (var i = 0; i <= level; i++)
            {
                spaces.Append(i);
                spaces.Append("   ");
            }

            // Iterate through the references and print the variables
            foreach (var reference in references)
            {
                // make sure the type definition is in the cache.
                session.NodeCache.Find(reference.ReferenceTypeId);

                switch (reference.NodeClass)
                {
                case NodeClass.Object:
                    if (verbose)
                    {
                        Console.WriteLine(spaces + "+ " + reference.DisplayName);
                    }
                    break;

                default:
                    if (verbose)
                    {
                        Console.WriteLine(spaces + "- " + reference.DisplayName);
                    }
                    break;
                }
                var subReferences = browser.Browse((NodeId)reference.NodeId);
                level += 1;
                GetElements(session, browser, level, subReferences, verbose);
                level -= 1;
            }
        }
Esempio n. 20
0
        /// <summary>
        /// Collects the fields for the instance node.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="nodeId">The node id.</param>
        /// <param name="parentPath">The parent path.</param>
        /// <param name="fields">The event fields.</param>
        /// <param name="fieldNodeIds">The node id for the declaration of the field.</param>
        /// <param name="foundNodes">The table of found nodes.</param>
        private static void CollectFields(
            Session session,
            NodeId nodeId,
            QualifiedNameCollection parentPath,
            SimpleAttributeOperandCollection fields,
            List <NodeId> fieldNodeIds,
            Dictionary <NodeId, QualifiedNameCollection> foundNodes)
        {
            // find all of the children of the field.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = nodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.Aggregates;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask   = (uint)(NodeClass.Object | NodeClass.Variable);
            nodeToBrowse.ResultMask      = (uint)BrowseResultMask.All;

            ReferenceDescriptionCollection children = ClientUtils.Browse(session, nodeToBrowse, false);

            if (children == null)
            {
                return;
            }

            // process the children.
            for (int ii = 0; ii < children.Count; ii++)
            {
                ReferenceDescription child = children[ii];

                if (child.NodeId.IsAbsolute)
                {
                    continue;
                }

                // construct browse path.
                QualifiedNameCollection browsePath = new QualifiedNameCollection(parentPath);
                browsePath.Add(child.BrowseName);

                // check if the browse path is already in the list.
                int index = ContainsPath(fields, browsePath);

                if (index < 0)
                {
                    SimpleAttributeOperand field = new SimpleAttributeOperand();

                    field.TypeDefinitionId = ObjectTypeIds.BaseEventType;
                    field.BrowsePath       = browsePath;
                    field.AttributeId      = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId;

                    fields.Add(field);
                    fieldNodeIds.Add((NodeId)child.NodeId);
                }

                // recusively find all of the children.
                NodeId targetId = (NodeId)child.NodeId;

                // need to guard against loops.
                if (!foundNodes.ContainsKey(targetId))
                {
                    foundNodes.Add(targetId, browsePath);
                    CollectFields(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes);
                }
            }
        }
Esempio n. 21
0
        /// <summary>
        /// Constructs an event object from a notification.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="monitoredItem">The monitored item that produced the notification.</param>
        /// <param name="notification">The notification.</param>
        /// <param name="eventTypeMappings">Mapping between event types and known event types.</param>
        /// <returns>
        /// The event object. Null if the notification is not a valid event type.
        /// </returns>
        public static BaseEventState ConstructEvent(
            Session session,
            MonitoredItem monitoredItem,
            EventFieldList notification,
            Dictionary <NodeId, NodeId> eventTypeMappings)
        {
            // find the event type.
            NodeId eventTypeId = FindEventType(monitoredItem, notification);

            if (eventTypeId == null)
            {
                return(null);
            }

            // look up the known event type.
            NodeId knownTypeId = null;

            if (!eventTypeMappings.TryGetValue(eventTypeId, out knownTypeId))
            {
                // check for a known type
                for (int jj = 0; jj < KnownEventTypes.Length; jj++)
                {
                    if (KnownEventTypes[jj] == eventTypeId)
                    {
                        knownTypeId = eventTypeId;
                        eventTypeMappings.Add(eventTypeId, eventTypeId);
                        break;
                    }
                }

                // browse for the supertypes of the event type.
                if (knownTypeId == null)
                {
                    ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false);

                    // can't do anything with unknown types.
                    if (supertypes == null)
                    {
                        return(null);
                    }

                    // find the first supertype that matches a known event type.
                    for (int ii = 0; ii < supertypes.Count; ii++)
                    {
                        for (int jj = 0; jj < KnownEventTypes.Length; jj++)
                        {
                            if (KnownEventTypes[jj] == supertypes[ii].NodeId)
                            {
                                knownTypeId = KnownEventTypes[jj];
                                eventTypeMappings.Add(eventTypeId, knownTypeId);
                                break;
                            }
                        }

                        if (knownTypeId != null)
                        {
                            break;
                        }
                    }
                }
            }

            if (knownTypeId == null)
            {
                return(null);
            }

            // all of the known event types have a UInt32 as identifier.
            uint?id = knownTypeId.Identifier as uint?;

            if (id == null)
            {
                return(null);
            }

            // construct the event based on the known event type.
            BaseEventState e = null;

            switch (id.Value)
            {
            case ObjectTypes.ConditionType: { e = new ConditionState(null); break; }

            case ObjectTypes.DialogConditionType: { e = new DialogConditionState(null); break; }

            case ObjectTypes.AlarmConditionType: { e = new AlarmConditionState(null); break; }

            case ObjectTypes.ExclusiveLimitAlarmType: { e = new ExclusiveLimitAlarmState(null); break; }

            case ObjectTypes.NonExclusiveLimitAlarmType: { e = new NonExclusiveLimitAlarmState(null); break; }

            case ObjectTypes.AuditEventType: { e = new AuditEventState(null); break; }

            case ObjectTypes.AuditUpdateMethodEventType: { e = new AuditUpdateMethodEventState(null); break; }

            default:
            {
                e = new BaseEventState(null);
                break;
            }
            }

            // get the filter which defines the contents of the notification.
            EventFilter filter = monitoredItem.Status.Filter as EventFilter;

            // initialize the event with the values in the notification.
            e.Update(session.SystemContext, filter.SelectClauses, notification);

            // save the orginal notification.
            e.Handle = notification;

            return(e);
        }
Esempio n. 22
0
        /// <summary>
        /// Constructs an event object from a notification.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="monitoredItem">The monitored item that produced the notification.</param>
        /// <param name="notification">The notification.</param>
        /// <param name="knownEventTypes">The known event types.</param>
        /// <param name="eventTypeMappings">Mapping between event types and known event types.</param>
        /// <returns>
        /// The event object. Null if the notification is not a valid event type.
        /// </returns>
        public static BaseEventState ConstructEvent(
            Session session,
            MonitoredItem monitoredItem,
            EventFieldList notification,
            Dictionary <NodeId, Type> knownEventTypes,
            Dictionary <NodeId, NodeId> eventTypeMappings)
        {
            // find the event type.
            NodeId eventTypeId = FindEventType(monitoredItem, notification);

            if (eventTypeId == null)
            {
                return(null);
            }

            // look up the known event type.
            Type   knownType   = null;
            NodeId knownTypeId = null;

            if (eventTypeMappings.TryGetValue(eventTypeId, out knownTypeId))
            {
                knownType = knownEventTypes[knownTypeId];
            }

            // try again.
            if (knownType == null)
            {
                if (knownEventTypes.TryGetValue(eventTypeId, out knownType))
                {
                    knownTypeId = eventTypeId;
                    eventTypeMappings.Add(eventTypeId, eventTypeId);
                }
            }

            // try mapping it to a known type.
            if (knownType == null)
            {
                // browse for the supertypes of the event type.
                ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes(session, eventTypeId, false);

                // can't do anything with unknown types.
                if (supertypes == null)
                {
                    return(null);
                }

                // find the first supertype that matches a known event type.
                for (int ii = 0; ii < supertypes.Count; ii++)
                {
                    NodeId superTypeId = (NodeId)supertypes[ii].NodeId;

                    if (knownEventTypes.TryGetValue(superTypeId, out knownType))
                    {
                        knownTypeId = superTypeId;
                        eventTypeMappings.Add(eventTypeId, superTypeId);
                    }

                    if (knownTypeId != null)
                    {
                        break;
                    }
                }

                // can't do anything with unknown types.
                if (knownTypeId == null)
                {
                    return(null);
                }
            }

            // construct the event based on the known event type.
            BaseEventState e = (BaseEventState)Activator.CreateInstance(knownType, new object[] { (NodeState)null });

            // get the filter which defines the contents of the notification.
            EventFilter filter = monitoredItem.Status.Filter as EventFilter;

            // initialize the event with the values in the notification.
            e.Update(session.SystemContext, filter.SelectClauses, notification);

            // save the orginal notification.
            e.Handle = notification;

            return(e);
        }
Esempio n. 23
0
        /// <summary>
        /// Handles the BeforeExpand event of the BrowseTV control.
        /// </summary>
        private void BrowseTV_BeforeExpand(object sender, TreeViewCancelEventArgs e)
        {
            try
            {
                ReferenceDescription reference = (ReferenceDescription)e.Node.Tag;
                e.Node.Nodes.Clear();

                // build list of references to browse.
                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

                for (int ii = 0; ii < m_referenceTypeIds.Length; ii++)
                {
                    BrowseDescription nodeToBrowse = new BrowseDescription();

                    nodeToBrowse.NodeId          = m_rootId;
                    nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
                    nodeToBrowse.ReferenceTypeId = m_referenceTypeIds[ii];
                    nodeToBrowse.IncludeSubtypes = true;
                    nodeToBrowse.NodeClassMask   = 0;
                    nodeToBrowse.ResultMask      = (uint)BrowseResultMask.All;

                    if (reference != null)
                    {
                        nodeToBrowse.NodeId = (NodeId)reference.NodeId;
                    }

                    nodesToBrowse.Add(nodeToBrowse);
                }

                // add the childen to the control.
                SortedDictionary <ExpandedNodeId, TreeNode> dictionary = new SortedDictionary <ExpandedNodeId, TreeNode>();

                ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, nodesToBrowse, false);

                for (int ii = 0; references != null && ii < references.Count; ii++)
                {
                    reference = references[ii];

                    // ignore out of server references.
                    if (reference.NodeId.IsAbsolute)
                    {
                        continue;
                    }

                    if (dictionary.ContainsKey(reference.NodeId))
                    {
                        continue;
                    }

                    TreeNode child = new TreeNode(reference.ToString());

                    child.Nodes.Add(new TreeNode());
                    child.Tag = reference;

                    if (!reference.TypeDefinition.IsAbsolute)
                    {
                        try
                        {
                            if (!m_typeImageMapping.ContainsKey((NodeId)reference.TypeDefinition))
                            {
                                List <NodeId> nodeIds = ClientUtils.TranslateBrowsePaths(m_session, (NodeId)reference.TypeDefinition, m_session.NamespaceUris, Opc.Ua.BrowseNames.Icon);

                                if (nodeIds.Count > 0 && nodeIds[0] != null)
                                {
                                    DataValue value = m_session.ReadValue(nodeIds[0]);
                                    byte[]    bytes = value.Value as byte[];

                                    if (bytes != null)
                                    {
                                        System.IO.MemoryStream istrm = new System.IO.MemoryStream(bytes);
                                        Image icon = Image.FromStream(istrm);
                                        BrowseTV.ImageList.Images.Add(icon);
                                        m_typeImageMapping[(NodeId)reference.TypeDefinition] = BrowseTV.ImageList.Images.Count - 1;
                                    }
                                }
                            }
                        }
                        catch (Exception exception)
                        {
                            Utils.LogError(exception, "Error loading image.");
                        }
                    }

                    int index = 0;

                    if (!m_typeImageMapping.TryGetValue((NodeId)reference.TypeDefinition, out index))
                    {
                        child.ImageIndex         = ClientUtils.GetImageIndex(m_session, reference.NodeClass, reference.TypeDefinition, false);
                        child.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, reference.NodeClass, reference.TypeDefinition, true);
                    }
                    else
                    {
                        child.ImageIndex         = index;
                        child.SelectedImageIndex = index;
                    }

                    dictionary[reference.NodeId] = child;
                }

                // add nodes to tree.
                foreach (TreeNode node in dictionary.Values.OrderBy(i => i.Text))
                {
                    e.Node.Nodes.Add(node);
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Esempio n. 24
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal NodesSelectedEventArgs(ExpandedNodeId sourceId, ReferenceDescriptionCollection references)
 {
     m_sourceId   = sourceId;
     m_references = references;
 }
Esempio n. 25
0
        /// <summary>
        /// Displays the attributes and properties in the attributes view.
        /// </summary>
        /// <param name="sourceId">The NodeId of the Node to browse.</param>
        private void DisplayAttributes(NodeId sourceId)
        {
            try
            {
                AttributesLV.Items.Clear();

                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

                // attempt to read all possible attributes.
                for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId      = sourceId;
                    nodeToRead.AttributeId = ii;
                    nodesToRead.Add(nodeToRead);
                }

                int startOfProperties = nodesToRead.Count;

                // find all of the pror of the node.
                BrowseDescription nodeToBrowse1 = new BrowseDescription();

                nodeToBrowse1.NodeId          = sourceId;
                nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
                nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                nodeToBrowse1.IncludeSubtypes = true;
                nodeToBrowse1.NodeClassMask   = 0;
                nodeToBrowse1.ResultMask      = (uint)BrowseResultMask.All;

                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
                nodesToBrowse.Add(nodeToBrowse1);

                // fetch property references from the server.
                ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false);

                if (references == null)
                {
                    return;
                }

                for (int ii = 0; ii < references.Count; ii++)
                {
                    // ignore external references.
                    if (references[ii].NodeId.IsAbsolute)
                    {
                        continue;
                    }

                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId      = (NodeId)references[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.Value;
                    nodesToRead.Add(nodeToRead);
                }

                // read all values.
                DataValueCollection      results         = null;
                DiagnosticInfoCollection diagnosticInfos = null;

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

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

                // process results.
                for (int ii = 0; ii < results.Count; ii++)
                {
                    string name     = null;
                    string datatype = null;
                    string value    = null;

                    // process attribute value.
                    if (ii < startOfProperties)
                    {
                        // ignore attributes which are invalid for the node.
                        if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                        {
                            continue;
                        }

                        // get the name of the attribute.
                        name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId);

                        // display any unexpected error.
                        if (StatusCode.IsBad(results[ii].StatusCode))
                        {
                            datatype = Utils.Format("{0}", Attributes.GetDataTypeId(nodesToRead[ii].AttributeId));
                            value    = Utils.Format("{0}", results[ii].StatusCode);
                        }

                        // display the value.
                        else
                        {
                            TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                            datatype = typeInfo.BuiltInType.ToString();

                            if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                            {
                                datatype += "[]";
                            }

                            value = Utils.Format("{0}", results[ii].Value);
                        }
                    }

                    // process property value.
                    else
                    {
                        // ignore properties which are invalid for the node.
                        if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown)
                        {
                            continue;
                        }

                        // get the name of the property.
                        name = Utils.Format("{0}", references[ii - startOfProperties]);

                        // display any unexpected error.
                        if (StatusCode.IsBad(results[ii].StatusCode))
                        {
                            datatype = String.Empty;
                            value    = Utils.Format("{0}", results[ii].StatusCode);
                        }

                        // display the value.
                        else
                        {
                            TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                            datatype = typeInfo.BuiltInType.ToString();

                            if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                            {
                                datatype += "[]";
                            }

                            value = Utils.Format("{0}", results[ii].Value);
                        }
                    }

                    // add the attribute name/value to the list view.
                    ListViewItem item = new ListViewItem(name);
                    item.SubItems.Add(datatype);
                    item.SubItems.Add(value);
                    AttributesLV.Items.Add(item);
                }

                // adjust width of all columns.
                for (int ii = 0; ii < AttributesLV.Columns.Count; ii++)
                {
                    AttributesLV.Columns[ii].Width = -2;
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Esempio n. 26
0
 public BrowseTreeCtrl()
 {
     InitializeComponent();
     m_references            = new ReferenceDescriptionCollection();
     m_BrowserMoreReferences = new BrowserEventHandler(Browser_MoreReferences);
 }
Esempio n. 27
0
        /// <summary>
        /// 读取一个节点的指定属性
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="attribute"></param>
        /// <returns></returns>
        private DataValue ReadNoteDataValueAttributes(NodeId nodeId, uint attribute)
        {
            NodeId sourceId = nodeId;
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();


            ReadValueId nodeToRead = new ReadValueId();

            nodeToRead.NodeId      = sourceId;
            nodeToRead.AttributeId = attribute;
            nodesToRead.Add(nodeToRead);

            int startOfProperties = nodesToRead.Count;

            // find all of the pror of the node.
            BrowseDescription nodeToBrowse1 = new BrowseDescription();

            nodeToBrowse1.NodeId          = sourceId;
            nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
            nodeToBrowse1.IncludeSubtypes = true;
            nodeToBrowse1.NodeClassMask   = 0;
            nodeToBrowse1.ResultMask      = (uint)BrowseResultMask.All;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            nodesToBrowse.Add(nodeToBrowse1);

            // fetch property references from the server.
            ReferenceDescriptionCollection references = FormUtils.Browse(m_OpcUaClient.Session, nodesToBrowse, false);

            if (references == null)
            {
                return(null);
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId nodeToRead2 = new ReadValueId();
                nodeToRead2.NodeId      = (NodeId)references[ii].NodeId;
                nodeToRead2.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead2);
            }

            // read all values.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            return(results[0]);
        }
Esempio n. 28
0
        /// <summary>
        /// Recursively populates the event types table.
        /// </summary>
        private void IndexTypesFromServer(NodeId baseTypeId, int eventType)
        {
            // check if event type needs to be revised.
            if (baseTypeId == Opc.Ua.ObjectTypeIds.ConditionType)
            {
                eventType = OpcRcw.Ae.Constants.CONDITION_EVENT;
            }

            else if (baseTypeId == Opc.Ua.ObjectTypeIds.AuditEventType)
            {
                eventType = OpcRcw.Ae.Constants.TRACKING_EVENT;
            }

            else if (baseTypeId == Opc.Ua.ObjectTypeIds.BaseEventType)
            {
                eventType = OpcRcw.Ae.Constants.SIMPLE_EVENT;
            }

            // browse for subtypes.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = baseTypeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasSubtype;
            nodeToBrowse.IncludeSubtypes = false;
            nodeToBrowse.NodeClassMask   = (uint)NodeClass.ObjectType;
            nodeToBrowse.ResultMask      = (uint)(BrowseResultMask.BrowseName | BrowseResultMask.DisplayName | BrowseResultMask.NodeClass);

            ReferenceDescriptionCollection references = ComAeUtils.Browse(
                m_session,
                nodeToBrowse,
                false);

            for (int ii = 0; ii < references.Count; ii++)
            {
                // these types have t
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

                NodeId typeId = (NodeId)references[ii].NodeId;

                if (!m_eventTypes.ContainsKey(typeId))
                {
                    // collection the instances declared by the type.
                    List <AeEventAttribute> declarations      = new List <AeEventAttribute>();
                    Dictionary <string, AeEventAttribute> map = new Dictionary <string, AeEventAttribute>();

                    ComAeUtils.CollectInstanceDeclarations(
                        m_session,
                        this,
                        (NodeId)references[ii].NodeId,
                        null,
                        declarations,
                        map);

                    AeEventCategory declaration = new AeEventCategory();
                    declaration.TypeId               = (NodeId)references[ii].NodeId;
                    declaration.SuperTypeId          = baseTypeId;
                    declaration.EventType            = eventType;
                    declaration.Description          = (LocalizedText.IsNullOrEmpty(references[ii].DisplayName)) ? references[ii].BrowseName.Name : references[ii].DisplayName.Text;
                    declaration.Attributes           = declarations;
                    m_eventTypes[declaration.TypeId] = declaration;
                }

                // recursively look for subtypes.
                IndexTypesFromServer(typeId, eventType);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// Browses the specified node.
        /// </summary>
        public ReferenceDescriptionCollection Browse(NodeId nodeId)
        {
            if (m_session == null)
            {
                throw new ServiceResultException(StatusCodes.BadServerNotConnected, "Cannot browse if not connected to a server.");
            }

            try
            {
                m_browseInProgress = true;

                // construct request.
                BrowseDescription nodeToBrowse = new BrowseDescription();

                nodeToBrowse.NodeId          = nodeId;
                nodeToBrowse.BrowseDirection = m_browseDirection;
                nodeToBrowse.ReferenceTypeId = m_referenceTypeId;
                nodeToBrowse.IncludeSubtypes = m_includeSubtypes;
                nodeToBrowse.NodeClassMask   = m_nodeClassMask;
                nodeToBrowse.ResultMask      = m_resultMask;

                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
                nodesToBrowse.Add(nodeToBrowse);

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

                ResponseHeader responseHeader = m_session.Browse(
                    null,
                    m_view,
                    m_maxReferencesReturned,
                    nodesToBrowse,
                    out results,
                    out diagnosticInfos);

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

                // check if valid.
                if (StatusCode.IsBad(results[0].StatusCode))
                {
                    throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable);
                }

                // fetch initial set of references.
                byte[] continuationPoint = results[0].ContinuationPoint;
                ReferenceDescriptionCollection references = results[0].References;

                // process any continuation point.
                while (continuationPoint != null)
                {
                    ReferenceDescriptionCollection additionalReferences;

                    if (!m_continueUntilDone && m_MoreReferences != null)
                    {
                        BrowserEventArgs args = new BrowserEventArgs(references);
                        m_MoreReferences(this, args);

                        // cancel browser and return the references fetched so far.
                        if (args.Cancel)
                        {
                            BrowseNext(ref continuationPoint, true);
                            return(references);
                        }

                        m_continueUntilDone = args.ContinueUntilDone;
                    }

                    additionalReferences = BrowseNext(ref continuationPoint, false);
                    if (additionalReferences != null && additionalReferences.Count > 0)
                    {
                        references.AddRange(additionalReferences);
                    }
                    else
                    {
                        Utils.Trace("Continuation point exists, but the browse results are null/empty.");
                        break;
                    }
                }

                // return the results.
                return(references);
            }
            finally
            {
                m_browseInProgress = false;
            }
        }
Esempio n. 30
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal BrowserEventArgs(ReferenceDescriptionCollection references)
 {
     m_references = references;
 }
        /// <summary>
        /// Reads the properties for the node.
        /// </summary>
        private void ReadProperties(NodeId nodeId)
        {
            // build list of references to browse.
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();

            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = nodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasProperty;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask   = (uint)NodeClass.Variable;
            nodeToBrowse.ResultMask      = (uint)BrowseResultMask.All;

            nodesToBrowse.Add(nodeToBrowse);

            // find properties.
            ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, View, nodesToBrowse, false);

            // build list of properties to read.
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

            for (int ii = 0; references != null && ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // ignore out of server references.
                if (reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId();
                nodeToRead.NodeId      = (NodeId)reference.NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                nodeToRead.Handle      = reference;
                nodesToRead.Add(nodeToRead);
            }

            if (nodesToRead.Count == 0)
            {
                return;
            }

            // read the properties.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            // add the results to the display.
            for (int ii = 0; ii < results.Count; ii++)
            {
                ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle;

                TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                // add the metadata for the attribute.
                ListViewItem item = new ListViewItem(reference.ToString());
                item.SubItems.Add(typeInfo.BuiltInType.ToString());

                if (typeInfo.ValueRank >= 0)
                {
                    item.SubItems[1].Text += "[]";
                }

                // add the value.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    item.SubItems.Add(results[ii].StatusCode.ToString());
                }
                else
                {
                    item.SubItems.Add(results[ii].WrappedValue.ToString());
                }

                item.Tag = results[ii];

                // display in list.
                AttributesLV.Items.Add(item);
            }

            // set the column widths.
            for (int ii = 0; ii < AttributesLV.Columns.Count; ii++)
            {
                AttributesLV.Columns[ii].Width = -2;
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Reads the attribute values in order to compare them to the returned results.
        /// </summary>
        private bool VerifyTypeDefinitions(
            Node node, 
            BrowseDescription description, 
            ReferenceDescriptionCollection references)
        {
            // check if nothing to do.
            if (references.Count == 0)
            {
                return true;
            }

            bool success = true;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
            
            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                if ((description.ResultMask & (uint)BrowseResultMask.TypeDefinition) == 0)
                {
                    if (!NodeId.IsNull(reference.TypeDefinition))
                    {
                        success = false;

                        Log(
                            "Unexpected TypeDefinition returned for Node '{0}'. NodeId = {1}, TargetId = {2}, TypeDefinition = {3}",
                            node, 
                            node.NodeId, 
                            reference.NodeId,
                            reference.TypeDefinition);
                    }

                    continue;
                }

                // ignore invalid or external references.
                if (reference == null || reference.NodeId == null || reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                BrowseDescription nodeToBrowse = new BrowseDescription();
                
                nodeToBrowse.NodeId = (NodeId)reference.NodeId;
                nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
                nodeToBrowse.IncludeSubtypes = false;
                nodeToBrowse.NodeClassMask = 0;
                nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasTypeDefinition;
                nodeToBrowse.ResultMask = (uint)BrowseResultMask.None;
                nodeToBrowse.Handle = references[ii];
                
                nodesToBrowse.Add(nodeToBrowse);
            }

            // nothing more to do if no type definitions requested.
            if ((description.ResultMask & (uint)BrowseResultMask.TypeDefinition) == 0)
            {
                return success;
            }

            // browse.
            BrowseResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;
            
            RequestHeader requestHeader = new RequestHeader();
            requestHeader.ReturnDiagnostics = 0;

            Session.Browse(
                null,
                m_view,
                0,
                nodesToBrowse,
                out results,
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(results, nodesToBrowse);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse);
            
            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array when Browsing TypeDefinition while Browsing Node '{0}'. NodeId = {1}", node, node.NodeId);
                return false;
            }

            bool error = false;

            for (int ii = 0; ii < nodesToBrowse.Count; ii++)
            {
                BrowseResult result = results[ii];
                
                if (StatusCode.IsBad(result.StatusCode))
                {
                    error = true;

                    Log(
                        "Browse TypeDefinition Failed for Node '{0}'. NodeId = {1}, TargetId = {2}, Status = {3}",
                        node, 
                        node.NodeId, 
                        nodesToBrowse[ii].NodeId,
                        results[0].StatusCode);
                    
                    continue;
                }

                ReferenceDescription reference = (ReferenceDescription)nodesToBrowse[ii].Handle;

                if (result.References.Count == 0)
                {
                    if (!NodeId.IsNull(reference.TypeDefinition))
                    {
                        error = true;

                        Log(
                            "Unexpected TypeDefinition returned for Node '{0}'. NodeId = {1}, TargetId = {2}, TypeDefinition = {3}",
                            node, 
                            node.NodeId, 
                            nodesToBrowse[ii].NodeId,
                            reference.TypeDefinition);
                    
                        continue;
                    }
                }
                else
                {
                    if (result.References.Count != 1)
                    {
                        error = true;

                        Log(
                            "Too many TypeDefinitions returned for Node '{0}'. NodeId = {1}, TargetId = {2}, Count = {3}",
                            node, 
                            node.NodeId, 
                            nodesToBrowse[ii].NodeId,
                            result.References.Count);
                    
                        continue;
                    }

                    if (result.References[0].NodeId != reference.TypeDefinition)
                    {
                        error = true;

                        Log(
                            "Incorrect TypeDefinition returned for Node '{0}'. NodeId = {1}, TargetId = {2}, Expected = {3}, Actual = {4}",
                            node, 
                            node.NodeId, 
                            nodesToBrowse[ii].NodeId,
                            result.References[0].NodeId,
                            reference.TypeDefinition);
                    
                        continue;
                    }
                }
            }

            return !error;
        }
Esempio n. 33
0
        /// <summary>
        /// 读取一个节点的所有属性
        /// </summary>
        /// <param name="tag">节点信息</param>
        /// <returns>节点的特性值</returns>
        public OpcNodeAttribute[] ReadNoteAttributes(string tag)
        {
            NodeId sourceId = new NodeId(tag);
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            // attempt to read all possible attributes.
            // 尝试着去读取所有可能的特性
            for (uint ii = Attributes.NodeClass; ii <= Attributes.UserExecutable; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = sourceId;
                nodeToRead.AttributeId = ii;
                nodesToRead.Add(nodeToRead);
            }

            int startOfProperties = nodesToRead.Count;

            // find all of the pror of the node.
            BrowseDescription nodeToBrowse1 = new BrowseDescription( );

            nodeToBrowse1.NodeId          = sourceId;
            nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
            nodeToBrowse1.IncludeSubtypes = true;
            nodeToBrowse1.NodeClassMask   = 0;
            nodeToBrowse1.ResultMask      = (uint)BrowseResultMask.All;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );

            nodesToBrowse.Add(nodeToBrowse1);

            // fetch property references from the server.
            ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false);

            if (references == null)
            {
                return(new OpcNodeAttribute[0]);
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = (NodeId)references[ii].NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            // read all values.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            // process results.


            List <OpcNodeAttribute> nodeAttribute = new List <OpcNodeAttribute>( );

            for (int ii = 0; ii < results.Count; ii++)
            {
                OpcNodeAttribute item = new OpcNodeAttribute( );

                // process attribute value.
                if (ii < startOfProperties)
                {
                    // ignore attributes which are invalid for the node.
                    if (results[ii].StatusCode == StatusCodes.BadAttributeIdInvalid)
                    {
                        continue;
                    }

                    // get the name of the attribute.
                    item.Name = Attributes.GetBrowseName(nodesToRead[ii].AttributeId);

                    // display any unexpected error.
                    if (StatusCode.IsBad(results[ii].StatusCode))
                    {
                        item.Type  = Utils.Format("{0}", Attributes.GetDataTypeId(nodesToRead[ii].AttributeId));
                        item.Value = Utils.Format("{0}", results[ii].StatusCode);
                    }

                    // display the value.
                    else
                    {
                        TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                        item.Type = typeInfo.BuiltInType.ToString( );

                        if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                        {
                            item.Type += "[]";
                        }

                        item.Value = results[ii].Value;//Utils.Format("{0}", results[ii].Value);
                    }
                }

                // process property value.
                else
                {
                    // ignore properties which are invalid for the node.
                    if (results[ii].StatusCode == StatusCodes.BadNodeIdUnknown)
                    {
                        continue;
                    }

                    // get the name of the property.
                    item.Name = Utils.Format("{0}", references[ii - startOfProperties]);

                    // display any unexpected error.
                    if (StatusCode.IsBad(results[ii].StatusCode))
                    {
                        item.Type  = String.Empty;
                        item.Value = Utils.Format("{0}", results[ii].StatusCode);
                    }

                    // display the value.
                    else
                    {
                        TypeInfo typeInfo = TypeInfo.Construct(results[ii].Value);

                        item.Type = typeInfo.BuiltInType.ToString( );

                        if (typeInfo.ValueRank >= ValueRanks.OneOrMoreDimensions)
                        {
                            item.Type += "[]";
                        }

                        item.Value = results[ii].Value; //Utils.Format("{0}", results[ii].Value);
                    }
                }

                nodeAttribute.Add(item);
            }

            return(nodeAttribute.ToArray( ));
        }
Esempio n. 34
0
        /// <summary>
        /// Verifies the results of a browse filter.
        /// </summary>
        private bool VerifyFilterResults(
            Node node, 
            BrowseDescription description,
            ReferenceDescriptionCollection actualList)
        {
            NodeId referenceTypeId = description.ReferenceTypeId; 
            BrowseDirection browseDirection = description.BrowseDirection;
            bool includeSubtypes = description.IncludeSubtypes;
            NodeClass nodeClassMask = (NodeClass)description.NodeClassMask;

            // nothing to verify if no master list.
            ReferenceDescriptionCollection masterList = node.Handle as ReferenceDescriptionCollection;

            if (masterList == null)
            {
                return true;
            }

            // cannot verify filter if filter criteria not returned.
            BrowseResultMask requiredMask = (BrowseResultMask.ReferenceTypeId | BrowseResultMask.IsForward | BrowseResultMask.NodeClass);

            if ((description.ResultMask & (uint)requiredMask) != (uint)requiredMask)
            {
                return true;
            }
            
            bool success = true;

            // look for missing references.
            for (int ii = 0; ii < masterList.Count; ii++)
            {
                ReferenceDescription reference = masterList[ii];
                
                if (nodeClassMask != NodeClass.Unspecified && (reference.NodeClass & nodeClassMask) == 0)
                {
                    continue;
                }

                if ((browseDirection == BrowseDirection.Inverse && reference.IsForward) || (browseDirection == BrowseDirection.Forward && !reference.IsForward))
                {
                    continue;
                }

                if (reference.ReferenceTypeId != referenceTypeId)
                {
                    if (!includeSubtypes)
                    {
                        continue;
                    }

                    if (!Session.TypeTree.IsTypeOf(reference.ReferenceTypeId, referenceTypeId))
                    {
                        continue;
                    }
                }
                
                bool found = false;

                for (int jj = 0; jj < actualList.Count; jj++)
                {
                    if (actualList[jj].NodeId == reference.NodeId && actualList[jj].IsForward == reference.IsForward && actualList[jj].ReferenceTypeId == reference.ReferenceTypeId)
                    {
                        found = true;
                        break;
                    }
                }

                if (!found)
                {
                    Log(
                        "Did not return expected target when browsing  Node '{0}'. NodeId = {1}, NodeClassMask = {2}, ReferenceFilter = {3}, TargetName = {4}, NodeClass = {5}, ReferenceType = {6}, TargetId = {7}.",
                        node, 
                        node.NodeId,
                        nodeClassMask,
                        Session.TypeTree.FindReferenceTypeName(referenceTypeId),
                        reference.DisplayName,
                        reference.NodeClass,
                        Session.TypeTree.FindReferenceTypeName(reference.ReferenceTypeId),
                        reference.NodeId);

                    success = false;
                }
            }
            
            // look for extra references.
            for (int ii = 0; ii < actualList.Count; ii++)
            {                
                bool found = false;

                for (int jj = 0; jj < masterList.Count; jj++)
                {
                    ReferenceDescription reference = masterList[jj];
                    
                    if (nodeClassMask != NodeClass.Unspecified && (reference.NodeClass & nodeClassMask) == 0)
                    {
                        continue;
                    }

                    if (actualList[ii].NodeId != reference.NodeId || actualList[ii].IsForward != reference.IsForward || actualList[ii].ReferenceTypeId != reference.ReferenceTypeId)
                    {
                        continue;
                    }
                                    
                    if ((browseDirection != BrowseDirection.Inverse && reference.IsForward) || (browseDirection != BrowseDirection.Forward && !reference.IsForward))
                    {
                        if (!includeSubtypes)
                        {
                            if (reference.ReferenceTypeId == referenceTypeId)
                            {
                                found = true;
                                break;
                            }
                        }
                        else
                        {
                            if (Session.TypeTree.IsTypeOf(reference.ReferenceTypeId, referenceTypeId))
                            {
                                found = true;
                                break;
                            }
                        }
                    }

                    Log(
                        "Returned invalid target when browsing Node '{0}'. NodeId = {1}, NodeClassMask = {2}, ReferenceFilter = {3}, TargetName = {4}, NodeClass = {5}, ReferenceType = {6}, TargetId = {7}.",
                        node, 
                        node.NodeId,
                        nodeClassMask,
                        Session.TypeTree.FindReferenceTypeName(referenceTypeId),
                        reference.DisplayName,
                        reference.NodeClass,
                        Session.TypeTree.FindReferenceTypeName(reference.ReferenceTypeId),
                        reference.NodeId);

                    success = false;
                    break;
                }

                if (!found)
                {
                    Log(
                        "Returned unexpected target when browsing Node '{0}'. NodeId = {1}, NodeClassMask = {2}, ReferenceFilter = {3}, TargetName = {4}, NodeClass = {5}, ReferenceType = {6}, TargetId = {7}.",
                        node, 
                        node.NodeId,
                        nodeClassMask,
                        Session.TypeTree.FindReferenceTypeName(referenceTypeId),
                        actualList[ii].DisplayName,
                        actualList[ii].NodeClass,
                        Session.TypeTree.FindReferenceTypeName(actualList[ii].ReferenceTypeId),
                        actualList[ii].NodeId);

                    success = false;
                    continue;
                }
            }

            return success;
        }         
Esempio n. 35
0
        /// <summary>
        /// 读取一个节点的所有属性
        /// </summary>
        /// <param name="tag">节点值</param>
        /// <returns>所有的数据</returns>
        public DataValue[] ReadNoteDataValueAttributes(string tag)
        {
            NodeId sourceId = new NodeId(tag);
            ReadValueIdCollection nodesToRead = new ReadValueIdCollection( );

            // attempt to read all possible attributes.
            // 尝试着去读取所有可能的特性
            for (uint ii = Attributes.NodeId; ii <= Attributes.UserExecutable; ii++)
            {
                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = sourceId;
                nodeToRead.AttributeId = ii;
                nodesToRead.Add(nodeToRead);
            }

            int startOfProperties = nodesToRead.Count;

            // find all of the pror of the node.
            BrowseDescription nodeToBrowse1 = new BrowseDescription( );

            nodeToBrowse1.NodeId          = sourceId;
            nodeToBrowse1.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.HasProperty;
            nodeToBrowse1.IncludeSubtypes = true;
            nodeToBrowse1.NodeClassMask   = 0;
            nodeToBrowse1.ResultMask      = (uint)BrowseResultMask.All;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( );

            nodesToBrowse.Add(nodeToBrowse1);

            // fetch property references from the server.
            ReferenceDescriptionCollection references = FormUtils.Browse(m_session, nodesToBrowse, false);

            if (references == null)
            {
                return(new DataValue[0]);
            }

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore external references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId nodeToRead = new ReadValueId( );
                nodeToRead.NodeId      = (NodeId)references[ii].NodeId;
                nodeToRead.AttributeId = Attributes.Value;
                nodesToRead.Add(nodeToRead);
            }

            // read all values.
            DataValueCollection      results         = null;
            DiagnosticInfoCollection diagnosticInfos = null;

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

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

            return(results.ToArray( ));
        }
Esempio n. 36
0
        /// <summary>
        /// Adds the browse results to the node (if not null). 
        /// </summary>
        private void UpdateNode(TreeNode parent, ReferenceDescriptionCollection references)
        { 
            try
            {
                for (int ii = 0; ii < references.Count; ii++)
                {
                    ReferenceDescription reference = references[ii];

                    TreeNode childNode = new TreeNode(reference.ToString());

                    childNode.ImageKey = childNode.SelectedImageKey = GuiUtils.GetTargetIcon(m_session, reference);
                    childNode.Tag = reference;
                                        
                    childNode.Nodes.Add(new TreeNode());
                    
                    parent.Nodes.Add(childNode);
                }
			}
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
Esempio n. 37
0
        /// <summary>
        /// Browses the address space and returns the references found.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="nodesToBrowse">The set of browse operations to perform.</param>
        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
        /// <returns>
        /// The references found. Null if an error occurred.
        /// </returns>
        public static ReferenceDescriptionCollection Browse(Session session, BrowseDescriptionCollection nodesToBrowse, bool throwOnError)
        {
            try
            {
                ReferenceDescriptionCollection references            = new ReferenceDescriptionCollection( );
                BrowseDescriptionCollection    unprocessedOperations = new BrowseDescriptionCollection( );

                while (nodesToBrowse.Count > 0)
                {
                    // start the browse operation.
                    BrowseResultCollection   results         = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    session.Browse(
                        null,
                        null,
                        0,
                        nodesToBrowse,
                        out results,
                        out diagnosticInfos);

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

                    ByteStringCollection continuationPoints = new ByteStringCollection( );

                    for (int ii = 0; ii < nodesToBrowse.Count; ii++)
                    {
                        // check for error.
                        if (StatusCode.IsBad(results[ii].StatusCode))
                        {
                            // this error indicates that the server does not have enough simultaneously active
                            // continuation points. This request will need to be resent after the other operations
                            // have been completed and their continuation points released.
                            if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints)
                            {
                                unprocessedOperations.Add(nodesToBrowse[ii]);
                            }

                            continue;
                        }

                        // check if all references have been fetched.
                        if (results[ii].References.Count == 0)
                        {
                            continue;
                        }

                        // save results.
                        references.AddRange(results[ii].References);

                        // check for continuation point.
                        if (results[ii].ContinuationPoint != null)
                        {
                            continuationPoints.Add(results[ii].ContinuationPoint);
                        }
                    }

                    // process continuation points.
                    ByteStringCollection revisedContiuationPoints = new ByteStringCollection( );

                    while (continuationPoints.Count > 0)
                    {
                        // continue browse operation.
                        session.BrowseNext(
                            null,
                            false,
                            continuationPoints,
                            out results,
                            out diagnosticInfos);

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

                        for (int ii = 0; ii < continuationPoints.Count; ii++)
                        {
                            // check for error.
                            if (StatusCode.IsBad(results[ii].StatusCode))
                            {
                                continue;
                            }

                            // check if all references have been fetched.
                            if (results[ii].References.Count == 0)
                            {
                                continue;
                            }

                            // save results.
                            references.AddRange(results[ii].References);

                            // check for continuation point.
                            if (results[ii].ContinuationPoint != null)
                            {
                                revisedContiuationPoints.Add(results[ii].ContinuationPoint);
                            }
                        }

                        // check if browsing must continue;
                        revisedContiuationPoints = continuationPoints;
                    }

                    // check if unprocessed results exist.
                    nodesToBrowse = unprocessedOperations;
                }

                // return complete list.
                return(references);
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }

                return(null);
            }
        }
Esempio n. 38
0
        /// <summary>
        /// Browses the node and verifies the results.
        /// </summary>
        private bool Browse(Node node, double start, double range)
        {
            // watch for circular references.
            if (m_availableNodes.ContainsKey(node.NodeId))
            {
                return true;
            }

            // get the master list of references.
            BrowseDescription nodeToBrowse = new BrowseDescription();
            
            nodeToBrowse.NodeId = node.NodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Both;
            nodeToBrowse.IncludeSubtypes = true;
            nodeToBrowse.NodeClassMask = 0;
            nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.References;
            nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;
            
            ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();
            
            if (!Browse(node, nodeToBrowse, references))
            {
                return false;
            }

            // save references.
            node.Handle = references;
            
            // add to dictionary.
            m_availableNodes.Add(node.NodeId, node);

            // build list of hierachial targets.
            List<Node> targets = new List<Node>();

            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                if (!reference.IsForward)
                {
                    continue;
                }

                if (!Session.TypeTree.IsTypeOf(reference.ReferenceTypeId, ReferenceTypeIds.HierarchicalReferences))
                {
                    continue;
                }

                Node target = Node.Copy(new Node(reference));
                targets.Add(target);
            }
                        
            // recursively follow sub-tree.
            if (targets.Count > 0)
            {
                double increment = range/targets.Count;
                double position  = start;

                for (int ii = 0; ii < targets.Count; ii++)
                {
                    if (range == MaxProgress)
                    {
                        Log("Browsing children of '{0}'. NodeId = {1}", targets[ii], targets[ii].NodeId);
                    }

                    Browse(targets[ii], position, increment);

                    position += increment;
                    ReportProgress(position);
                }
            }

            return true;
        }
        /// <summary>
        /// Browses the address space and returns the references found.
        /// </summary>
        public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescriptionCollection nodesToBrowse, bool throwOnError)
        {
            try
            {
                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();
                BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection();

                while (nodesToBrowse.Count > 0)
                {
                    // start the browse operation.
                    BrowseResultCollection results = null;
                    DiagnosticInfoCollection diagnosticInfos = null;

                    session.Browse(
                        null,
                        view,
                        0,
                        nodesToBrowse,
                        out results,
                        out diagnosticInfos);

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

                    ByteStringCollection continuationPoints = new ByteStringCollection();

                    for (int ii = 0; ii < nodesToBrowse.Count; ii++)
                    {
                        // check for error.
                        if (StatusCode.IsBad(results[ii].StatusCode))
                        {
                            // this error indicates that the server does not have enough simultaneously active 
                            // continuation points. This request will need to be resent after the other operations
                            // have been completed and their continuation points released.
                            if (results[ii].StatusCode == StatusCodes.BadNoContinuationPoints)
                            {
                                unprocessedOperations.Add(nodesToBrowse[ii]);
                            }

                            continue;
                        }
                        
                        // check if all references have been fetched.
                        if (results[ii].References.Count == 0)
                        {
                            continue;
                        }

                        // save results.
                        references.AddRange(results[ii].References);

                        // check for continuation point.
                        if (results[ii].ContinuationPoint != null)
                        {
                            continuationPoints.Add(results[ii].ContinuationPoint);
                        }
                    }

                    // process continuation points.
                    ByteStringCollection revisedContiuationPoints = new ByteStringCollection();

                    while (continuationPoints.Count > 0)
                    {
                        // continue browse operation.
                        session.BrowseNext(
                            null,
                            false,
                            continuationPoints,
                            out results,
                            out diagnosticInfos);

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

                        for (int ii = 0; ii < continuationPoints.Count; ii++)
                        {
                            // check for error.
                            if (StatusCode.IsBad(results[ii].StatusCode))
                            {
                                continue;
                            }

                            // check if all references have been fetched.
                            if (results[ii].References.Count == 0)
                            {
                                continue;
                            }

                            // save results.
                            references.AddRange(results[ii].References);

                            // check for continuation point.
                            if (results[ii].ContinuationPoint != null)
                            {
                                revisedContiuationPoints.Add(results[ii].ContinuationPoint);
                            }
                        }

                        // check if browsing must continue;
                        revisedContiuationPoints = continuationPoints;
                    }

                    // check if unprocessed results exist.
                    nodesToBrowse = unprocessedOperations;
                }

                // return complete list.
                return references;
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }

                return null;
            }
        }
Esempio n. 40
0
        /// <summary>
        /// Finishes an asynchronous invocation of the BrowseNext service.
        /// </summary>
        public ResponseHeader EndBrowseNext(
            IAsyncResult result,
            out byte[] revisedContinuationPoint,
            out ReferenceDescriptionCollection references)
        {
            BrowseResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = EndBrowseNext(
                result,
                out results,
                out diagnosticInfos);

            if (results == null || results.Count != 1)
            {
                throw new ServiceResultException(StatusCodes.BadUnknownResponse);
            }

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable));
            }

            revisedContinuationPoint = results[0].ContinuationPoint;
            references = results[0].References;

            return responseHeader;
        }
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal BrowserEventArgs(ReferenceDescriptionCollection references)
 {
     m_references = references;
 }
Esempio n. 42
0
        /// <summary>
        /// Invokes the Browse service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="view">The view to browse.</param>
        /// <param name="nodeToBrowse">The node to browse.</param>
        /// <param name="maxResultsToReturn">The maximum number of returned values.</param>
        /// <param name="browseDirection">The browse direction.</param>
        /// <param name="referenceTypeId">The reference type id.</param>
        /// <param name="includeSubtypes">If set to <c>true</c> the subtypes of the ReferenceType will be included in the browse.</param>
        /// <param name="nodeClassMask">The node class mask.</param>
        /// <param name="continuationPoint">The continuation point.</param>
        /// <param name="references">The list of node references.</param>
        /// <returns></returns>
        public virtual ResponseHeader Browse(
            RequestHeader requestHeader,
            ViewDescription view,
            NodeId nodeToBrowse,
            uint maxResultsToReturn,
            BrowseDirection browseDirection,
            NodeId referenceTypeId,
            bool includeSubtypes,
            uint nodeClassMask,
            out byte[] continuationPoint,
            out ReferenceDescriptionCollection references)
        {
            BrowseDescription description = new BrowseDescription();

            description.NodeId = nodeToBrowse;
            description.BrowseDirection = browseDirection;
            description.ReferenceTypeId = referenceTypeId;
            description.IncludeSubtypes = includeSubtypes;
            description.NodeClassMask = nodeClassMask;
            description.ResultMask = (uint)BrowseResultMask.All;

            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
            nodesToBrowse.Add(description);

            BrowseResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = Browse(
                requestHeader,
                view,
                maxResultsToReturn,
                nodesToBrowse,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable));
            }

            continuationPoint = results[0].ContinuationPoint;
            references = results[0].References;

            return responseHeader;
        }
Esempio n. 43
0
        /// <summary>
        /// Invokes the BrowseNext service.
        /// </summary>
        public virtual ResponseHeader BrowseNext(
            RequestHeader requestHeader,
            bool releaseContinuationPoint,
            byte[] continuationPoint,
            out byte[] revisedContinuationPoint,
            out ReferenceDescriptionCollection references)
        {
            ByteStringCollection continuationPoints = new ByteStringCollection();
            continuationPoints.Add(continuationPoint);

            BrowseResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            ResponseHeader responseHeader = BrowseNext(
                requestHeader,
                releaseContinuationPoint,
                continuationPoints,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(new ServiceResult(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable));
            }

            revisedContinuationPoint = results[0].ContinuationPoint;
            references = results[0].References;

            return responseHeader;
        }
Esempio n. 44
0
        /// <summary>
        /// Browses the node and returns the references found.
        /// </summary>
        protected virtual bool Browse(
            Node node,
            BrowseDescription nodeToBrowse, 
            ReferenceDescriptionCollection references)
        {            
            BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
            nodesToBrowse.Add(nodeToBrowse);

            BrowseResultCollection results;
            DiagnosticInfoCollection diagnosticInfos;
            
            RequestHeader requestHeader = new RequestHeader();
            requestHeader.ReturnDiagnostics = 0;

            Session.Browse(
                requestHeader,
                new ViewDescription(),
                0,
                nodesToBrowse,
                out results,
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(results, nodesToBrowse);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse);
            
            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array during Browse.");
                return false;
            }
            
            // process results.
            ByteStringCollection continuationPoints = new ByteStringCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                // check status code.
                if (StatusCode.IsBad(results[ii].StatusCode))
                {
                    Log(
                        "Browse Failed for Node '{0}'. Status = {2}, NodeId = {1}", 
                        node, 
                        node.NodeId, 
                        results[ii].StatusCode);

                    return false;
                }
                
                // save references.
                references.AddRange(results[ii].References);

                if (results[ii].ContinuationPoint != null)
                {
                    continuationPoints.Add(results[ii].ContinuationPoint);
                }
            }
            
            // process continuation points.
            while (continuationPoints.Count > 0)
            {                       
                requestHeader = new RequestHeader();
                requestHeader.ReturnDiagnostics = 0;

                Session.BrowseNext(
                    requestHeader,
                    false,
                    continuationPoints,
                    out results,
                    out diagnosticInfos);
                
                ClientBase.ValidateResponse(results, continuationPoints);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);

                // check diagnostics.
                if (diagnosticInfos != null && diagnosticInfos.Count > 0)
                {
                    Log("Returned non-empty DiagnosticInfos array during BrowseNext.");
                    return false;
                }
                
                continuationPoints.Clear();

                // process results.
                for (int ii = 0; ii < results.Count; ii++)
                {
                    // check status code.
                    if (StatusCode.IsBad(results[ii].StatusCode))
                    {
                        Log(
                            "BrowseNext Failed for Node '{0}'. Status = {2}, NodeId = {1}", 
                            node, 
                            node.NodeId, 
                            results[ii].StatusCode);

                        return false;
                    }

                    // save references.
                    references.AddRange(results[ii].References);

                    if (results[ii].ContinuationPoint != null)
                    {
                        // check max references.
                        if (results[ii].References.Count == 0)
                        {
                            Log(
                                "No references returned with a continuation point for Node '{0}'. NodeId = {1}",
                                node, 
                                node.NodeId);
                           
                            return false;
                        }

                        continuationPoints.Add(results[ii].ContinuationPoint);
                    }
                }
            }
            
            return true;
        }
Esempio n. 45
0
        /// <summary>
        /// Prompts the user to specify the browse options.
        /// </summary>
        public bool ShowDialog(Session session, NodeId variableId)
        {
            if (session == null)    throw new ArgumentNullException("session");
            if (variableId == null) throw new ArgumentNullException("variableId");
            
            m_session   = session;
            m_encodings = session.ReadAvailableEncodings(variableId);

            foreach (ReferenceDescription encoding in m_encodings)
            {
                EncodingCB.Items.Add(encoding.ToString());
            }

            if (EncodingCB.Items.Count > 0)
            {
                EncodingCB.SelectedIndex = 0;
            }

            if (ShowDialog() != DialogResult.OK)
            {
                return false;
            }

            return true;
        }
Esempio n. 46
0
        /// <see cref="BaseTreeCtrl.SelectNode" />
        protected override void SelectNode()
        {
            base.SelectNode();
            
            // check if node is selected.
            if (NodesTV.SelectedNode == null)
            {
                return;
            }
            
            m_parent = GetParentOfSelected();

            ReferenceDescription reference = NodesTV.SelectedNode.Tag as ReferenceDescription;

            // update the attributes control.
            if (m_AttributesCtrl != null)
            {              
                if (reference != null)
                {
                    m_AttributesCtrl.Initialize(m_browser.Session, reference.NodeId);
                }
                else
                {
                    m_AttributesCtrl.Clear();
                }
            }
                        
            // check for single reference.
            if (reference != null)
            {
                m_references = new ReferenceDescription[] { reference };
                return;
            }
            
            // check if reference type folder is selected.
            NodeId referenceTypeId = NodesTV.SelectedNode.Tag as NodeId;

            if (referenceTypeId != null)
            {
                m_references = new ReferenceDescriptionCollection();

                foreach (TreeNode child in NodesTV.SelectedNode.Nodes)
                {                        
                    reference = child.Tag as ReferenceDescription;

                    if (reference != null)
                    {
                        m_references.Add(reference);
                    }
                }
            }      
        }
Esempio n. 47
0
        /// <summary>
        /// Adds a target to the tree control.
        /// </summary>
        private void AddReferences(TreeNode parent, ReferenceDescriptionCollection references)
        {
            foreach (ReferenceDescription reference in references)
            {
                if (reference.ReferenceTypeId.IsNullNodeId)
                {
                    Utils.Trace("Reference {0} has null reference type id", reference.DisplayName);
                    continue;
                }

                ReferenceTypeNode typeNode = m_browser.Session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode;
                if (typeNode == null)
                {
                    Utils.Trace("Reference {0} has invalid reference type id.", reference.DisplayName);
                    continue;
                }

                if (m_browser.BrowseDirection == BrowseDirection.Forward && !reference.IsForward
                    || m_browser.BrowseDirection == BrowseDirection.Inverse && reference.IsForward)
                {
                    Utils.Trace("Reference's IsForward value is: {0}, but the browse direction is: {1}; for reference {2}", reference.IsForward, m_browser.BrowseDirection, reference.DisplayName);
                    continue;
                }

                if (reference.NodeId == null || reference.NodeId.IsNull)
                {
                    Utils.Trace("The node id of the reference {0} is NULL.", reference.DisplayName);
                    continue;
                }

                if (reference.BrowseName == null || reference.BrowseName.Name == null)
                {
                    Utils.Trace("Browse name is empty for reference {0}", reference.DisplayName);
                    continue;
                }

                if (!Enum.IsDefined(typeof(Opc.Ua.NodeClass), reference.NodeClass) || reference.NodeClass == NodeClass.Unspecified)
                {
                    Utils.Trace("Node class is an unknown or unspecified value, for reference {0}", reference.DisplayName);
                    continue;
                }
                
                if (m_browser.NodeClassMask != 0 && m_browser.NodeClassMask != 255)
                {
                    if (reference.TypeDefinition == null || reference.TypeDefinition.IsNull)
                    {
                        Utils.Trace("Type definition is null for reference {0}", reference.DisplayName);
                        continue;
                    }
                }

                // suppress duplicate references.
                if (!m_showReferences)
                {
                    bool exists = false;

                    foreach (TreeNode existingChild in parent.Nodes)
                    {
                        ReferenceDescription existingReference = existingChild.Tag as ReferenceDescription;

                        if (existingReference != null)
                        {
                            if (existingReference.NodeId == reference.NodeId)
                            {
                                exists = true;
                                break;
                            }
                        }
                    }

                    if (exists)
                    {
                        continue;
                    }
                }

                string text = GetTargetText(reference);
                string icon = GuiUtils2.GetTargetIcon(m_browser.Session, reference);

                TreeNode container = parent;

                if (m_showReferences)
                {
                    container = FindReferenceTypeContainer(parent, reference);
                }

                if (container != null)
                {
                    TreeNode child = AddNode(container, reference, text, icon);
                    child.Nodes.Add(new TreeNode());
                }
            }
        }
Esempio n. 48
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal NodesSelectedEventArgs(ExpandedNodeId sourceId, ReferenceDescriptionCollection references)
 {
     m_sourceId   = sourceId;
     m_references = references;
 }
Esempio n. 49
0
 public BrowseTreeCtrl()
 {
     InitializeComponent();
     m_references = new ReferenceDescriptionCollection();
     m_BrowserMoreReferences = new BrowserEventHandler(Browser_MoreReferences);
 }
Esempio n. 50
0
        /// <summary>
        /// Loops until browse is complete for max results reached.
        /// </summary>
        protected ServiceResult FetchReferences(
            OperationContext                   context,
            bool                               assignContinuationPoint,
            ref ContinuationPoint              cp, 
            ref ReferenceDescriptionCollection references)
        {
            Debug.Assert(context != null);
            Debug.Assert(cp != null);
            Debug.Assert(references != null);

            INodeManager nodeManager = cp.Manager;
            NodeClass nodeClassMask = (NodeClass)cp.NodeClassMask;
            BrowseResultMask resultMask = cp.ResultMask;

            // loop until browse is complete or max results.
            while (cp != null)
            {
                // fetch next batch.
                nodeManager.Browse(context, ref cp, references);
                
                ReferenceDescriptionCollection referencesToKeep = new ReferenceDescriptionCollection(references.Count);

                // check for incomplete reference descriptions.
                for (int ii = 0; ii < references.Count; ii++)
                {
                    ReferenceDescription reference = references[ii];
                    
                    // check if filtering must be applied.
                    if (reference.Unfiltered)
                    {                   
                        // ignore unknown external references.
                        if (reference.NodeId.IsAbsolute)
                        {
                            continue;
                        }

                        // update the description.
                        bool include = UpdateReferenceDescription(
                            context,
                            (NodeId)reference.NodeId,
                            nodeClassMask,
                            resultMask,
                            reference);

                        if (!include)
                        {
                            continue;
                        }
                    }

                    // add to list.
                    referencesToKeep.Add(reference);
                }

                // replace list.
                references = referencesToKeep;

                // check if browse limit reached.
                if (cp != null && references.Count >= cp.MaxResultsToReturn)
                {
                    if (!assignContinuationPoint)
                    {
                        return StatusCodes.BadNoContinuationPoints;
                    }

                    cp.Id = Guid.NewGuid();
                    context.Session.SaveContinuationPoint(cp);
                    break;
                }
            }

            // all is good.
            return ServiceResult.Good;
        }
Esempio n. 51
0
        /// <see cref="BaseListCtrl.GetDataToDrag" />
        protected override object GetDataToDrag()
        {
            ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();

            foreach (ListViewItem listItem in ItemsLV.SelectedItems)
            {
                PropertyItem property = listItem.Tag as PropertyItem;

                if (property != null)
                {
                    references.Add(property.Reference);
                }
            }

            return references;
        }
Esempio n. 52
0
        /// <summary>
        /// Applies the browse filters to a set of references.
        /// </summary>
        private void ApplyFilters(
            ReferenceDescriptionCollection currentBatch, 
			OPCBROWSEFILTER                dwBrowseFilter,
			string                         szElementNameFilter, 
            int                            maxReferencesReturned,
            IList<BrowseElement>           filteredResults,
            IList<BrowseElement>           unprocessedResults)
        {
            // apply the filters to each item in the batch.
            foreach (ReferenceDescription reference in currentBatch)
            {
                // check for a valid node.
                INode target = m_session.NodeCache.FetchNode(reference.NodeId);

                if (target == null)
                {
                    continue;
                }
                
                // create the browse element.
                BrowseElement element = new BrowseElement();
                
                element.Node   = target;
                element.Name   = target.BrowseName.Name;
                element.ItemId = NodeIdToItemId(target.NodeId);
    
                // apply the element name filter.
                if (!String.IsNullOrEmpty(szElementNameFilter))
                {
                    if (!ComUtils.Match(element.Name, szElementNameFilter, true))
                    {
                        continue;
                    }
                }

                element.IsItem = IsItem(target);
                element.HasChildren = HasChildren(target);

                // apply the browse filter.
                if (dwBrowseFilter != OPCBROWSEFILTER.OPC_BROWSE_FILTER_ALL)
                {
                    if (dwBrowseFilter == OPCBROWSEFILTER.OPC_BROWSE_FILTER_ITEMS)
                    {
                        if (!element.IsItem)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (!element.HasChildren)
                        {
                            continue;
                        }
                    }
                }               

                // must save the results to return in a subsequent browse.
                if (maxReferencesReturned != 0 && filteredResults.Count >= maxReferencesReturned)
                {
                    unprocessedResults.Add(element);
                }

                // can return the results in this browse.
                else
                {
                    filteredResults.Add(element);
                }
            }
        }
        /// <summary>
        /// Browses the address space and returns the references found.
        /// </summary>
        public static ReferenceDescriptionCollection Browse(Session session, ViewDescription view, BrowseDescription nodeToBrowse, bool throwOnError)
        {
            try
            {
                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();

                // construct browse request.
                BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection();
                nodesToBrowse.Add(nodeToBrowse);

                // start the browse operation.
                BrowseResultCollection results = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                session.Browse(
                    null,
                    view,
                    0,
                    nodesToBrowse,
                    out results,
                    out diagnosticInfos);

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

                do
                {
                    // check for error.
                    if (StatusCode.IsBad(results[0].StatusCode))
                    {
                        throw new ServiceResultException(results[0].StatusCode);
                    }

                    // process results.
                    for (int ii = 0; ii < results[0].References.Count; ii++)
                    {
                        references.Add(results[0].References[ii]);
                    }

                    // check if all references have been fetched.
                    if (results[0].References.Count == 0 || results[0].ContinuationPoint == null)
                    {
                        break;
                    }

                    // continue browse operation.
                    ByteStringCollection continuationPoints = new ByteStringCollection();
                    continuationPoints.Add(results[0].ContinuationPoint);

                    session.BrowseNext(
                        null,
                        false,
                        continuationPoints,
                        out results,
                        out diagnosticInfos);

                    ClientBase.ValidateResponse(results, continuationPoints);
                    ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints);
                }
                while (true);

                //return complete list.
                return references;
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }

                return null;
            }
        }
Esempio n. 54
0
        private void SelectChildrenMI_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_ItemsSelected == null || NodesTV.SelectedNode == null)
                {
                    return;
                }

                m_parent = GetParentOfSelected();
                m_references = new ReferenceDescriptionCollection();

                foreach (TreeNode child in NodesTV.SelectedNode.Nodes)
                {
                    ReferenceDescription reference = child.Tag as ReferenceDescription;

                    if (reference != null)
                    {
                        m_references.Add(reference);
                    }                    
                }

                if (m_references.Count > 0)
                {
                    m_ItemsSelected(this, new NodesSelectedEventArgs(m_parent.NodeId, m_references));
                }
            }
            catch (Exception exception)
            {
				GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception);
            }
        }
        /// <summary>
        /// Browses the address space and returns all of the supertypes of the specified type node.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="typeId">The NodeId for a type node in the address space.</param>
        /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param>
        /// <returns>
        /// The references found. Null if an error occurred.
        /// </returns>
        public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, NodeId typeId, bool throwOnError)
        {
            ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection();

            try
            {
                // find all of the children of the field.
                BrowseDescription nodeToBrowse = new BrowseDescription();

                nodeToBrowse.NodeId = typeId;
                nodeToBrowse.BrowseDirection = BrowseDirection.Inverse;
                nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype;
                nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible.
                nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. 
                nodeToBrowse.ResultMask = (uint)BrowseResultMask.All;

                ReferenceDescriptionCollection references = Browse(session, nodeToBrowse, throwOnError);

                while (references != null && references.Count > 0)
                {
                    // should never be more than one supertype.
                    supertypes.Add(references[0]);

                    // only follow references within this server.
                    if (references[0].NodeId.IsAbsolute)
                    {
                        break;
                    }

                    // get the references for the next level up.
                    nodeToBrowse.NodeId = (NodeId)references[0].NodeId;
                    references = Browse(session, nodeToBrowse, throwOnError);
                }

                // return complete list.
                return supertypes;
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }

                return null;
            }
        }
Esempio n. 56
0
        /// <summary>
        /// Returns the available encodings for a node
        /// </summary>
        /// <param name="variableId">The variable node.</param>
        /// <returns></returns>
        public ReferenceDescriptionCollection ReadAvailableEncodings(NodeId variableId)
        {
            VariableNode variable = NodeCache.Find(variableId) as VariableNode;

            if (variable == null)
            {
                throw ServiceResultException.Create(StatusCodes.BadNodeIdInvalid, "NodeId does not refer to a valid variable node.");
            }

            // no encodings available if there was a problem reading the data type for the node.
            if (NodeId.IsNull(variable.DataType))
            {
                return new ReferenceDescriptionCollection();
            }

            // no encodings for non-structures.
            if (!TypeTree.IsTypeOf(variable.DataType, DataTypes.Structure))
            {
                return new ReferenceDescriptionCollection();
            }

            // look for cached values.
            IList<INode> encodings = NodeCache.Find(variableId, ReferenceTypeIds.HasEncoding, false, true);

            if (encodings.Count > 0)
            {
                ReferenceDescriptionCollection references = new ReferenceDescriptionCollection();

                foreach (INode encoding in encodings)
                {
                    ReferenceDescription reference = new ReferenceDescription();

                    reference.ReferenceTypeId = ReferenceTypeIds.HasEncoding;
                    reference.IsForward       = true;
                    reference.NodeId          = encoding.NodeId;
                    reference.NodeClass       = encoding.NodeClass;
                    reference.BrowseName      = encoding.BrowseName;
                    reference.DisplayName     = encoding.DisplayName;
                    reference.TypeDefinition  = encoding.TypeDefinitionId;
                
                    references.Add(reference);
                }

                return references;
            }

            Browser browser = new Browser(this);
                        
            browser.BrowseDirection = BrowseDirection.Forward;
            browser.ReferenceTypeId = ReferenceTypeIds.HasEncoding;
            browser.IncludeSubtypes = false;
            browser.NodeClassMask   = 0;
                        
            return browser.Browse(variable.DataType);
        }
Esempio n. 57
0
        /// <summary>
        /// Fetches the children from the server.
        /// </summary>
        private List <AeBrowseElement> Browse(Session session, AeBrowseElement start, bool isArea)
        {
            // browse for notifiers and sources.
            BrowseDescription nodeToBrowse = new BrowseDescription();

            nodeToBrowse.NodeId          = start.NodeId;
            nodeToBrowse.BrowseDirection = BrowseDirection.Forward;
            nodeToBrowse.ResultMask      = (uint)(BrowseResultMask.BrowseName);
            nodeToBrowse.NodeClassMask   = (uint)0;

            if (isArea)
            {
                nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasNotifier;
                nodeToBrowse.IncludeSubtypes = true;
            }
            else
            {
                nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasEventSource;
                nodeToBrowse.IncludeSubtypes = true;
            }

            ReferenceDescriptionCollection references = ComAeUtils.Browse(
                session,
                nodeToBrowse,
                false);

            if (references == null)
            {
                throw ComUtils.CreateComException(ResultIds.E_FAIL);
            }

            List <AeBrowseElement> hits = new List <AeBrowseElement>();

            for (int ii = 0; ii < references.Count; ii++)
            {
                // ignore remote references.
                if (references[ii].NodeId.IsAbsolute)
                {
                    continue;
                }

                // need to check if at the end of the tree.
                if (references[ii].ReferenceTypeId != ReferenceTypeIds.HasEventSource)
                {
                    nodeToBrowse.NodeId = (NodeId)references[ii].NodeId;

                    ReferenceDescriptionCollection children = ComAeUtils.Browse(session, nodeToBrowse, false);

                    if (!isArea)
                    {
                        if (children != null && children.Count > 0)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        if (children == null || children.Count == 0)
                        {
                            continue;
                        }
                    }
                }

                string browseText = m_mapper.GetLocalBrowseName(references[ii].BrowseName);

                // check for duplicate browse names.
                for (int jj = 0; jj < hits.Count; jj++)
                {
                    if (hits[jj].BrowseText == browseText)
                    {
                        hits[jj].Duplicated = true;
                        browseText          = null;
                        break;
                    }
                }

                // add new element.
                if (browseText != null)
                {
                    AeBrowseElement element = new AeBrowseElement();
                    element.Parent     = start;
                    element.NodeId     = (NodeId)references[ii].NodeId;
                    element.BrowseText = m_mapper.GetLocalBrowseName(references[ii].BrowseName);
                    element.IsArea     = isArea;
                    hits.Add(element);

                    StringBuilder itemId = new StringBuilder();
                    itemId.Append(start.ItemId);
                    itemId.Append('/');
                    itemId.Append(element.BrowseText);
                    element.ItemId = itemId.ToString();
                }
            }

            // remove any duplicates.
            for (int ii = 0; ii < hits.Count;)
            {
                if (hits[ii].Duplicated)
                {
                    hits.RemoveAt(ii);
                    continue;
                }

                ii++;
            }

            return(hits);
        }
Esempio n. 58
-1
        /// <summary>
        /// Reads the attribute values in order to compare them to the returned results.
        /// </summary>
        private bool VerifyTargetAttributes(
            Node node, 
            BrowseDescription description, 
            ReferenceDescriptionCollection references)
        {
            // check if nothing to do.
            if (references.Count == 0)
            {
                return true;
            }
            
            bool error = false;

            // build list of values to read.
            ReadValueIdCollection valuesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < references.Count; ii++)
            {
                ReferenceDescription reference = references[ii];

                // ignore invalid or external references.
                if (reference == null || reference.NodeId == null || reference.NodeId.IsAbsolute)
                {
                    continue;
                }

                ReadValueId valueToRead = new ReadValueId();

                valueToRead.NodeId = (NodeId)reference.NodeId;
                valueToRead.AttributeId = Attributes.NodeId;
                valueToRead.Handle = reference;

                valuesToRead.Add(valueToRead);
                                
                if ((description.ResultMask & (uint)BrowseResultMask.NodeClass) != 0)
                {
                    valueToRead = new ReadValueId();

                    valueToRead.NodeId = (NodeId)reference.NodeId;
                    valueToRead.AttributeId = Attributes.NodeClass;
                    valueToRead.Handle = reference;

                    valuesToRead.Add(valueToRead);
                }
                else
                {
                    if (reference.NodeClass != 0)
                    {
                        error = true;
                        
                        Log(
                            "Unexpected NodeClass when Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, NodeClass = {3}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId, 
                            reference.NodeClass);

                        continue;
                    }
                }
                                
                if ((description.ResultMask & (uint)BrowseResultMask.BrowseName) != 0)
                {
                    valueToRead = new ReadValueId();

                    valueToRead.NodeId = (NodeId)reference.NodeId;
                    valueToRead.AttributeId = Attributes.BrowseName;
                    valueToRead.Handle = reference;

                    valuesToRead.Add(valueToRead);
                }
                else
                {
                    if (!QualifiedName.IsNull(reference.BrowseName))
                    {
                        error = true;
                        
                        Log(
                            "Unexpected BrowseName when Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, BrowseName = {3}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId, 
                            reference.BrowseName);

                        continue;
                    }
                }
                                
                if ((description.ResultMask & (uint)BrowseResultMask.DisplayName) != 0)
                {
                    valueToRead = new ReadValueId();

                    valueToRead.NodeId = (NodeId)reference.NodeId;
                    valueToRead.AttributeId = Attributes.DisplayName;
                    valueToRead.Handle = reference;

                    valuesToRead.Add(valueToRead);
                }
                else
                {
                    if (!LocalizedText.IsNullOrEmpty(reference.DisplayName))
                    {
                        error = true;
                        
                        Log(
                            "Unexpected DisplayName when Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, DisplayName = {3}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId, 
                            reference.DisplayName);

                        continue;
                    }
                }
            }
            
            // halt if errors occured.
            if (error)
            {
                return false;
            }

            // read values from server.
            DataValueCollection results;
            DiagnosticInfoCollection diagnosticInfos;

            RequestHeader requestHeader = new RequestHeader();
            requestHeader.ReturnDiagnostics = 0;

            Session.Read(
                requestHeader,
                0,
                TimestampsToReturn.Neither,
                valuesToRead,
                out results,
                out diagnosticInfos);
            
            ClientBase.ValidateResponse(results, valuesToRead);
            ClientBase.ValidateDiagnosticInfos(diagnosticInfos, valuesToRead);
            
            // check diagnostics.
            if (diagnosticInfos != null && diagnosticInfos.Count > 0)
            {
                Log("Returned non-empty DiagnosticInfos array when Reading Attributes while Browsing Node '{0}'. NodeId = {1}", node, node.NodeId);
                return false;
            }

            for (int ii = 0; ii < valuesToRead.Count; ii++)
            {
                if (results[ii].StatusCode != StatusCodes.Good)
                {
                    error = true;
                    
                    Log(
                        "Could not read {2} when Browsing Node '{0}'. NodeId = {1}, TargetId = {3}, Status = {4}", 
                        node, 
                        node.NodeId, 
                        Attributes.GetBrowseName(valuesToRead[ii].AttributeId), 
                        valuesToRead[ii].NodeId,
                        results[ii].StatusCode);

                    continue;
                }
                
                ReferenceDescription reference = (ReferenceDescription)valuesToRead[ii].Handle;

                if (valuesToRead[ii].AttributeId == Attributes.NodeId)
                {
                    NodeId expectedId = results[ii].Value as NodeId;

                    if (expectedId != reference.NodeId)
                    {
                        error = true;
                        
                        Log(
                            "Incorrect NodeId Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, Expected = {3}, Actual = {4}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId,
                            expectedId,
                            reference.NodeId);
                    }

                    continue;
                }
                
                if (valuesToRead[ii].AttributeId == Attributes.NodeClass)
                {
                    int? expectedClass = results[ii].Value as int?;

                    if (expectedClass == null || expectedClass.Value != (int)reference.NodeClass)
                    {
                        error = true;
                        
                        Log(
                            "Incorrect NodeClass Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, Expected = {3}, Actual = {4}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId,
                            expectedClass,
                            reference.NodeClass);
                    }

                    continue;
                }

                if (valuesToRead[ii].AttributeId == Attributes.BrowseName)
                {
                    QualifiedName expectedName = results[ii].Value as QualifiedName;

                    if (expectedName != reference.BrowseName)
                    {
                        error = true;
                        
                        Log(
                            "Incorrect BrowseName Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, Expected = {3}, Actual = {4}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId,
                            expectedName,
                            reference.BrowseName);
                    }

                    continue;
                }

                if (valuesToRead[ii].AttributeId == Attributes.DisplayName)
                {
                    LocalizedText expectedName = results[ii].Value as LocalizedText;

                    if (expectedName != reference.DisplayName)
                    {
                        error = true;
                        
                        Log(
                            "Incorrect DisplayName Browsing Node '{0}'. NodeId = {1}, TargetId = {2}, Expected = {3}, Actual = {4}", 
                            node, 
                            node.NodeId, 
                            reference.NodeId,
                            expectedName,
                            reference.DisplayName);
                    }

                    continue;
                }
            }

            return !error;
        }