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; } }
/// <summary> /// Reads the arguments for the method. /// </summary> private void ReadArguments(NodeId nodeId) { m_inputArguments = null; m_outputArguments = null; // 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.BrowseName; nodesToBrowse.Add(nodeToBrowse); // find properties. ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, 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; } // ignore other properties. if (reference.BrowseName != Opc.Ua.BrowseNames.InputArguments && reference.BrowseName != Opc.Ua.BrowseNames.OutputArguments) { continue; } ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)reference.NodeId; nodeToRead.AttributeId = Attributes.Value; nodeToRead.Handle = reference; nodesToRead.Add(nodeToRead); } // method has no arguments. if (nodesToRead.Count == 0) { return; } // read the arguments. 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); // save the results. for (int ii = 0; ii < results.Count; ii++) { ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle; if (StatusCode.IsGood(results[ii].StatusCode)) { if (reference.BrowseName == Opc.Ua.BrowseNames.InputArguments) { m_inputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue<ExtensionObject[]>(null), typeof(Argument)); } if (reference.BrowseName == Opc.Ua.BrowseNames.OutputArguments) { m_outputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue<ExtensionObject[]>(null), typeof(Argument)); } } } // set default values for input arguments. if (m_inputArguments != null) { foreach (Argument argument in m_inputArguments) { argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree); } } }
/// <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; }
/// <summary> /// Finds the targets for the specified reference. /// </summary> private static List<NodeId> FindTargetOfReference(Session session, List<NodeId> nodeIds, NodeId referenceTypeId, bool throwOnError) { try { // construct browse request. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); for (int ii = 0; ii < nodeIds.Count; ii++) { BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeIds[ii]; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = referenceTypeId; nodeToBrowse.IncludeSubtypes = false; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.None; nodesToBrowse.Add(nodeToBrowse); } // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, null, 1, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); List<NodeId> targetIds = new List<NodeId>(); ByteStringCollection continuationPoints = new ByteStringCollection(); for (int ii = 0; ii < nodeIds.Count; ii++) { targetIds.Add(null); // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { continue; } // check for continuation point. if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0) { continuationPoints.Add(results[ii].ContinuationPoint); } // get the node id. if (results[ii].References.Count > 0) { if (NodeId.IsNull(results[ii].References[0].NodeId) || results[ii].References[0].NodeId.IsAbsolute) { continue; } targetIds[ii] = (NodeId)results[ii].References[0].NodeId; } } // release continuation points. if (continuationPoints.Count > 0) { session.BrowseNext( null, true, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); } //return complete list. return targetIds; } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return null; } }
private ReferenceDescriptionCollection Browse(StandardServer server, BrowseDescriptionCollection nodesToBrowse, bool throwOnError) { try { ReferenceDescriptionCollection references = new ReferenceDescriptionCollection(); BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection(); while (nodesToBrowse.Count > 0) { // start the browse operation. OperationContext context = new OperationContext(new RequestHeader(), RequestType.Browse); BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; server.CurrentInstance.NodeManager.Browse( context, null, 0, nodesToBrowse, out results, out diagnosticInfos); 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. server.CurrentInstance.NodeManager.BrowseNext( context, false, continuationPoints, out results, out diagnosticInfos); 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); } }
/// <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; } }
/// <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]); }
/// <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; } }
/// <summary> /// Gets the properties. /// </summary> /// <param name="session">The session.</param> /// <param name="requests">The requests.</param> /// <param name="propertyIds">The property ids.</param> /// <returns>The list of properities.</returns> public IList<DaProperty> GetPropertyValues(Session session, ComDaReadPropertiesRequest[] requests, params int[] propertyIds) { TraceState("GetPropertyValues", requests.Length); // select all supported properties if none provided IList<DaProperty> properties = s_SupportedProperties; if (propertyIds == null || propertyIds.Length == 0) { propertyIds = new int[s_SupportedProperties.Length]; for (int ii = 0; ii < propertyIds.Length; ii++) { propertyIds[ii] = s_SupportedProperties[ii].PropertyId; } } // return the descriptions that match the requested properties. else { properties = new DaProperty[propertyIds.Length]; for (int ii = 0; ii < propertyIds.Length; ii++) { for (int jj = 0; jj < s_SupportedProperties.Length; jj++) { if (propertyIds[ii] == s_SupportedProperties[jj].PropertyId) { properties[ii] = s_SupportedProperties[jj]; break; } } } } // build a list of elements to create. BrowseElement[] elements = new BrowseElement[requests.Length]; int[] indexes = new int[requests.Length]; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); for (int ii = 0; ii < requests.Length; ii++) { BrowseElement element = null; // lookup element in cache. lock (m_lock) { string itemId = requests[ii].ItemId; if (String.IsNullOrEmpty(itemId)) { requests[ii].Error = ResultIds.E_INVALIDITEMID; elements[ii] = null; continue; } // if (m_cache.TryGetValue(itemId, out element)) // { // UpdateReadPropertyRequest(requests[ii], element, propertyIds); // continue; // } // create a new element. elements[ii] = element = new BrowseElement(); } element.ItemId = requests[ii].ItemId; element.NodeId = m_mapper.GetRemoteNodeId(element.ItemId); // prepare a request to browse the children. indexes[ii] = PrepareBrowseElementBrowseRequest(element.NodeId, nodesToBrowse); } // check if nothing more to do. if (nodesToBrowse.Count == 0) { return properties; } // browse all elements at once. BrowseResultCollection results = Browse(session, nodesToBrowse); // validate results and prepare read requests. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); for (int ii = 0; ii < elements.Length; ii++) { BrowseElement element = elements[ii]; if (element == null) { continue; } // update the element with the children found. if (!UpdateBrowseElement(element, nodesToBrowse, results, indexes[ii])) { requests[ii].Error = ResultIds.E_UNKNOWNITEMID; elements[ii] = null; continue; } // prepare to read the properties from the server. indexes[ii] = PrepareBrowseElementReadRequest( element.NodeId, element.ReferencesByName, nodesToRead, NodeClass.Unspecified, false); } // check if nothing to do. if (nodesToRead.Count == 0) { return properties; } // read all child properties at once. DataValueCollection values = Read(session, nodesToRead); // process results and build final table. for (int ii = 0; ii < elements.Length; ii++) { BrowseElement element = elements[ii]; if (element == null) { continue; } // update the browse element with the property values. if (!UpdateBrowseElement(session.TypeTree, element, nodesToRead, values, NodeClass.Unspecified, false, indexes[ii])) { requests[ii].Error = ResultIds.E_UNKNOWNITEMID; continue; } UpdateReadPropertyRequest(requests[ii], element, propertyIds); // save element in cache. lock (m_lock) { element.CacheTimestamp = DateTime.UtcNow; m_cache[element.ItemId] = element; } } // return the descriptions. return properties; }
/// <summary> /// Sends the browse request to the server. /// </summary> /// <param name="session">The session.</param> /// <param name="nodesToBrowse">The nodes to browse.</param> /// <returns></returns> private BrowseResultCollection BrowseBlock(Session session, BrowseDescriptionCollection nodesToBrowse) { try { // Utils.Trace("Browsing {0} Nodes", nodesToBrowse.Count); ViewDescription view = new ViewDescription(); Dictionary<int,BrowseResult> combinedResults = new Dictionary<int, BrowseResult>(); // initialize the table of indexes used to correlate results. BrowseDescriptionCollection browseOperations = nodesToBrowse; List<int> browseIndexes = new List<int>(); for (int ii = 0; ii < nodesToBrowse.Count; ii++) { browseIndexes.Add(ii); } BrowseDescriptionCollection unprocessedOperations = new BrowseDescriptionCollection(); List<int> unprocessedBrowseIndexes = new List<int>(); while (browseOperations.Count > 0) { // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, view, 0, browseOperations, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, browseOperations); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, browseOperations); unprocessedOperations.Clear(); unprocessedBrowseIndexes.Clear(); ByteStringCollection continuationPoints = new ByteStringCollection(); List<int> continuationPointIndexes = new List<int>(); for (int ii = 0; ii < browseOperations.Count; ii++) { int index = browseIndexes[ii]; // Utils.Trace("{0}/{1}/{2}", browseOperations[ii].NodeId, browseOperations[ii].ReferenceTypeId, results[ii].References.Count); // look up results. BrowseResult combinedResult = null; if (!combinedResults.TryGetValue(index, out combinedResult)) { combinedResults[index] = combinedResult = new BrowseResult(); } // 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(browseOperations[ii]); unprocessedBrowseIndexes.Add(index); continue; } // save error. if (StatusCode.IsGood(combinedResult.StatusCode)) { combinedResult.StatusCode = results[ii].StatusCode; } continue; } // check if all references have been fetched. if (results[ii].References.Count == 0) { continue; } // save results. combinedResult.References.AddRange(results[ii].References); // check for continuation point. if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0) { continuationPoints.Add(results[ii].ContinuationPoint); continuationPointIndexes.Add(index); } } // process continuation points. ByteStringCollection revisedContinuationPoints = new ByteStringCollection(); List<int> revisedContinuationPointIndexes = new List<int>(); while (continuationPoints.Count > 0) { bool releaseContinuationPoints = false; // continue browse operation. session.BrowseNext( null, releaseContinuationPoints, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); revisedContinuationPoints.Clear(); revisedContinuationPointIndexes.Clear(); for (int ii = 0; ii < continuationPoints.Count; ii++) { int index = continuationPointIndexes[ii]; // look up results. BrowseResult combinedResult = null; if (!combinedResults.TryGetValue(index, out combinedResult)) { combinedResults[index] = new BrowseResult(); } // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { // save error. if (StatusCode.IsGood(combinedResult.StatusCode)) { combinedResult.StatusCode = results[ii].StatusCode; } continue; } // check if all references have been fetched. if (results[ii].References.Count == 0) { continue; } // save results. combinedResult.References.AddRange(results[ii].References); // check for continuation point. if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0) { revisedContinuationPoints.Add(results[ii].ContinuationPoint); revisedContinuationPointIndexes.Add(index); } } // check if browsing must continue; continuationPoints = revisedContinuationPoints; continuationPointIndexes = revisedContinuationPointIndexes; } // check if unprocessed results exist. browseOperations = unprocessedOperations; browseIndexes = unprocessedBrowseIndexes; } // reconstruct list of combined results. BrowseResultCollection finalResults = new BrowseResultCollection(); for (int ii = 0; ii < nodesToBrowse.Count; ii++) { BrowseResult combinedResult = null; if (!combinedResults.TryGetValue(ii, out combinedResult)) { combinedResult = new BrowseResult(); } finalResults.Add(combinedResult); } // return complete list. return finalResults; } catch (Exception e) { throw ComUtils.CreateComException(e, ResultIds.E_FAIL); } }
/// <summary> /// Sends the browse request to the server. /// </summary> /// <param name="session">The session.</param> /// <param name="nodesToBrowse">The nodes to browse.</param> /// <returns></returns> private BrowseResultCollection Browse(Session session, BrowseDescriptionCollection nodesToBrowse) { BrowseResultCollection results = null; // break the request into smaller blocks. if (m_browseBlockSize > 0 && nodesToBrowse.Count > m_browseBlockSize) { results = new BrowseResultCollection(); for (int ii = 0; ii < nodesToBrowse.Count; ii += m_browseBlockSize) { BrowseDescriptionCollection x = new BrowseDescriptionCollection(); for (int jj = ii; jj < ii + m_browseBlockSize && jj < nodesToBrowse.Count; jj++) { x.Add(nodesToBrowse[jj]); } BrowseResultCollection y = BrowseBlock(session, x); results.AddRange(y); } return results; } // small enough to do directly. return BrowseBlock(session, nodesToBrowse); }
/// <summary> /// Updates the browse element with the children returned in the browse results. /// </summary> /// <param name="element">The element.</param> /// <param name="nodesToBrowse">The nodes to browse.</param> /// <param name="results">The results.</param> /// <param name="first">The index of the first browse result associated with the element.</param> /// <returns></returns> private bool UpdateBrowseElement( BrowseElement element, BrowseDescriptionCollection nodesToBrowse, BrowseResultCollection results, int first) { // check for a valid range within the collection. if (first < 0 || first >= nodesToBrowse.Count) { return false; } bool missingReferences = false; // process all references. Dictionary<string,ReferenceDescription> referencesByName = new Dictionary<string, ReferenceDescription>(); Dictionary<string,ReferenceDescription> duplicateNames = new Dictionary<string, ReferenceDescription>(); for (int ii = first; ii < first+2; ii++) { BrowseResult result = results[ii]; // check for errors - rejected node id are fatal; others can be ignored. if (StatusCode.IsBad(result.StatusCode)) { if (result.StatusCode == StatusCodes.BadNodeIdInvalid || result.StatusCode == StatusCodes.BadNodeIdInvalid || result.StatusCode == StatusCodes.BadNodeNotInView) { return false; } missingReferences = true; continue; } // eliminate duplicates and index references by browse name. for (int jj = 0; jj < result.References.Count; jj++) { ReferenceDescription reference = result.References[jj]; // ignore off server references. if (reference.NodeId == null || reference.NodeId.IsAbsolute) { continue; } // construct the browse name. string browseName = m_mapper.GetLocalBrowseName(reference.BrowseName); if (reference.DisplayName != null) { browseName = reference.DisplayName.Text; } // check for duplicates. ReferenceDescription duplicate = null; if (referencesByName.TryGetValue(browseName, out duplicate)) { if (reference.NodeId != duplicate.NodeId) { duplicateNames[browseName] = duplicate; } continue; } // add to table. referencesByName.Add(browseName, reference); } } // remove duplicates. foreach (string duplicateName in duplicateNames.Keys) { referencesByName.Remove(duplicateName); } // save child lookup table. element.ReferencesByName = referencesByName; element.MissingReferences = missingReferences; // update the masks. SetElementMasks(element); return true; }
/// <summary> /// Prepares a browse request for the children of a node. /// </summary> /// <param name="nodeId">The node id.</param> /// <param name="nodesToBrowse">The nodes to browse.</param> private int PrepareBrowseElementBrowseRequest( NodeId nodeId, BrowseDescriptionCollection nodesToBrowse) { int index = nodesToBrowse.Count; BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.Organizes; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)(BrowseResultMask.DisplayName | BrowseResultMask.BrowseName | BrowseResultMask.NodeClass); nodesToBrowse.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HasChild; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)(BrowseResultMask.DisplayName | BrowseResultMask.BrowseName | BrowseResultMask.NodeClass); nodesToBrowse.Add(nodeToBrowse); return index; }
public static void BrowseNode(String currentNode, String browseName) { BrowseResultCollection browseResultCollection = null; DiagnosticInfoCollection diagnosticInfos; BrowseDescriptionCollection browseDescriptionCollection = null; List <NodeClass> nodeClasses = new List <NodeClass>() { NodeClass.Unspecified }; foreach (NodeClass nodeClass in nodeClasses) { browseDescriptionCollection = PrepareBrowseDescriptionCollection(currentNode, (uint)nodeClass); clientSession.Browse( null, null, 100, browseDescriptionCollection, out browseResultCollection, out diagnosticInfos); if (browseResultCollection.Where(br => br.References.Count > 0).FirstOrDefault() == null) { continue; } int browseResultCounter = browseResultCollection.FindIndex(br => br.References.Count > 0); String referenceType = String.Empty; foreach (BrowseResult browseResult in browseResultCollection) { switch (browseResultCounter) { case 0: referenceType = "Organizes"; break; case 1: referenceType = "HasComponent"; break; case 2: referenceType = "HasChild"; break; case 3: referenceType = "HasDescription"; break; case 4: referenceType = "HasProperty"; break; default: referenceType = "HasProperty"; break; } if (browseResult.References.Count > 0) { foreach (ReferenceDescription referenceDescription in browseResult.References) { if (referenceDescription.BrowseName.NamespaceIndex != UaDefaultNamespaceIndex) { BrowseNode(referenceDescription.NodeId.ToString(), referenceDescription.BrowseName.ToString()); } //TBD - If a node id has different relations with its parent node, the additional "relation" should be added //OpcuaNodeList opcuaNodeSubStructure = new OpcuaNodeList(); //opcuaNodeSubStructure.nodeId = referenceDescription.NodeId.ToString(); //opcuaNodeSubStructure.browseName = referenceDescription.BrowseName.ToString(); OpcuaNodeLink opcuaNodeLink = new OpcuaNodeLink(); opcuaNodeLink.nodeID = referenceDescription.NodeId.ToString(); opcuaNodeLink.browseName = referenceDescription.BrowseName.ToString(); opcuaNodeLink.parentNodeId = currentNode; opcuaNodeLink.parentNodebrowseName = browseName; opcuaNodeLink.referenceType = referenceType; if (referenceDescription.IsForward) { opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G"); } opcuaNodeLink.NodeClassMask = nodeClass.ToString("G"); opcuaNodeLink.browseResultMask = BrowseResultMask.All.ToString("G"); //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString())) if (opcuaNodeStructure.ChildrenNodes == null) { opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>(); } addNode(opcuaNodeLink); if (referenceDescription.NodeClass == NodeClass.Method) { Node methodNode = clientSession.ReadNode((NodeId)(referenceDescription.NodeId.ToString())); browseDescriptionCollection = PrepareBrowseDescriptionCollection(referenceDescription.NodeId.ToString(), (uint)nodeClass); clientSession.Browse( null, null, 100, browseDescriptionCollection, out browseResultCollection, out diagnosticInfos); if (browseResultCollection.Where(br => br.References.Count > 0).FirstOrDefault() == null) { continue; } String inputArgumentsNodeId = String.Empty, outputArgumentsNodeId = String.Empty; foreach (BrowseResult br in browseResultCollection) { foreach (ReferenceDescription rd in br.References) { OpcuaNodeLink nodeLink = new OpcuaNodeLink(); nodeLink.nodeID = rd.NodeId.ToString(); nodeLink.browseName = rd.BrowseName.ToString(); if (nodeLink.browseName == "InputArguments") { inputArgumentsNodeId = nodeLink.nodeID; } else if (nodeLink.browseName == "OutputArguments") { outputArgumentsNodeId = nodeLink.nodeID; } nodeLink.parentNodeId = referenceDescription.NodeId.ToString(); nodeLink.parentNodebrowseName = referenceDescription.BrowseName.ToString(); nodeLink.referenceType = referenceType; if (rd.IsForward) { opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G"); } nodeLink.NodeClassMask = nodeClass.ToString("G"); nodeLink.browseResultMask = BrowseResultMask.All.ToString("G"); //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString())) if (opcuaNodeStructure.ChildrenNodes == null) { opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>(); } addNode(nodeLink); } } opcuaNodeLink.isMethod = true; BrowsePathCollection pathsToArgs = new BrowsePathCollection(); BrowsePath pathToInputArgs = new BrowsePath(); pathToInputArgs.StartingNode = methodNode.NodeId; pathToInputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("InputArguments")); pathsToArgs.Add(pathToInputArgs); BrowsePath pathToOutputArgs = new BrowsePath(); pathToOutputArgs.StartingNode = methodNode.NodeId; pathToOutputArgs.RelativePath = new RelativePath(ReferenceTypeIds.HasProperty, false, true, new QualifiedName("OutputArguments")); pathsToArgs.Add(pathToOutputArgs); BrowsePathResultCollection results = null; // Get the nodeId of the input argument ResponseHeader responseHeader = clientSession.TranslateBrowsePathsToNodeIds( null, pathsToArgs, out results, out diagnosticInfos ); ArgumentCollection[] arguments = new ArgumentCollection[2]; for (int i = 0; i < 2; i++) { arguments[i] = new ArgumentCollection(); foreach (BrowsePathTarget bptarget in results[i].Targets) { DataValueCollection readResults = null; ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)bptarget.TargetId; nodeToRead.AttributeId = Attributes.Value; ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); nodesToRead.Add(nodeToRead); DiagnosticInfoCollection readDiagnoistcInfos = null; clientSession.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out readResults, out readDiagnoistcInfos ); ExtensionObject[] exts = (ExtensionObject[])readResults[0].Value; for (int j = 0; j < exts.Length; ++j) { ExtensionObject ext = exts[j]; arguments[i].Add((Argument)ext.Body); OpcuaNodeLink nl = new OpcuaNodeLink(); nl.nodeID = ((Opc.Ua.Argument)ext.Body).BinaryEncodingId.ToString(); nl.browseName = ((Opc.Ua.Argument)ext.Body).Name; if (((Opc.Ua.Argument)ext.Body).Description.Text.Equals("Input argument")) { nl.parentNodeId = inputArgumentsNodeId; } else if (((Opc.Ua.Argument)ext.Body).Description.Text.Equals("Output argument")) { nl.parentNodeId = outputArgumentsNodeId; } nl.parentNodebrowseName = referenceDescription.BrowseName.ToString(); nl.referenceType = referenceType; if (referenceDescription.IsForward) { opcuaNodeLink.BrowseDirection = BrowseDirection.Forward.ToString("G"); } nl.NodeClassMask = NodeClass.Variable.ToString("G"); nl.browseResultMask = BrowseResultMask.All.ToString("G"); nl.isArgument = true; //if (!opcuaNodeStructure.IsChildPresent(referenceDescription.NodeId.ToString())) if (opcuaNodeStructure.ChildrenNodes == null) { opcuaNodeStructure.ChildrenNodes = new List <OpcuaNodeLink>(); } addNode(nl); } } } } } } } } }
/// <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) { return Browse(session, null, nodesToBrowse, throwOnError); }
/// <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; } }
/// <summary> /// Creates the browse element. /// </summary> /// <param name="session">The session.</param> /// <param name="nodeId">The node id.</param> /// <returns>The browse element; null if the node id does not refers to a valid element.</returns> private BrowseElement CreateBrowseElement(Session session, NodeId nodeId) { TraceState("CreateBrowseElement", nodeId); BrowseElement element = new BrowseElement(); element.NodeId = nodeId; element.ItemId = m_mapper.GetLocalItemId(nodeId); // browse the server for the children. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); int index = PrepareBrowseElementBrowseRequest(nodeId, nodesToBrowse); // browse all elements at once. BrowseResultCollection results = Browse(session, nodesToBrowse); // update the element with the children found. if (!UpdateBrowseElement(element, nodesToBrowse, results, index)) { return null; } // read the properties from the server. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); index = PrepareBrowseElementReadRequest(nodeId, element.ReferencesByName, nodesToRead, NodeClass.Unspecified, true); DataValueCollection values = Read(session, nodesToRead); // update the browse element with the property values. if (!UpdateBrowseElement(session.TypeTree, element, nodesToRead, values, NodeClass.Unspecified, true, index)) { return null; } return element; }
/// <summary> /// Invokes the Browse service. /// </summary> /// <param name="requestHeader">The request header.</param> /// <param name="view">The view.</param> /// <param name="requestedMaxReferencesPerNode">The maximum number of references to return for each node.</param> /// <param name="nodesToBrowse">The list of nodes to browse.</param> /// <param name="results">The list of results for the passed starting nodes and filters.</param> /// <param name="diagnosticInfos">The diagnostic information for the results.</param> /// <returns> /// Returns a <see cref="ResponseHeader"/> object /// </returns> public override ResponseHeader Browse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; OperationContext context = ValidateRequest(requestHeader, RequestType.Browse); try { if (nodesToBrowse == null || nodesToBrowse.Count == 0) { throw new ServiceResultException(StatusCodes.BadNothingToDo); } m_serverInternal.NodeManager.Browse( context, view, requestedMaxReferencesPerNode, nodesToBrowse, out results, out diagnosticInfos); return CreateResponse(requestHeader, context.StringTable); } catch (ServiceResultException e) { lock (ServerInternal.DiagnosticsLock) { ServerInternal.ServerDiagnostics.RejectedRequestsCount++; if (IsSecurityError(e.StatusCode)) { ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++; } } throw TranslateException(context, e); } finally { OnRequestComplete(context); } }
/// <summary> /// Creates the children of the browse element. /// </summary> /// <param name="session">The session.</param> /// <param name="parent">The parent.</param> /// <returns> /// The browse element; null if the node id does not refers to a valid element. /// </returns> private List<BrowseElement> LookupChildElements(Session session, BrowseElement parent) { List<BrowseElement> children = new List<BrowseElement>(); List<BrowseElement> childrenToFind = new List<BrowseElement>(); List<int> indexes = new List<int>(); BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); // create an element for each child reference. foreach (ReferenceDescription reference in parent.ReferencesByName.Values) { NodeId nodeId = (NodeId)reference.NodeId; string itemId = m_mapper.GetLocalItemId(nodeId); BrowseElement child = null; lock (m_lock) { // check if child has already been cached. if (m_cache.TryGetValue(itemId, out child)) { child.ParentId = parent.ItemId; children.Add(child); continue; } // create a new element. child = new BrowseElement(); } child.NodeId = nodeId; child.ItemId = itemId; child.NodeClass = reference.NodeClass; child.BrowseName = child.UaBrowseName = m_mapper.GetLocalBrowseName(reference.BrowseName); if (reference.DisplayName != null) { child.BrowseName = reference.DisplayName.Text; } int index = PrepareBrowseElementBrowseRequest(child.NodeId, nodesToBrowse); childrenToFind.Add(child); indexes.Add(index); } // check if nothing to do because everything was in the cache. if (childrenToFind.Count == 0) { return children; } // browse all elements at once. BrowseResultCollection results = Browse(session, nodesToBrowse); // validate results and prepare read requests. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); for (int ii = 0; ii < childrenToFind.Count; ii++) { BrowseElement child = childrenToFind[ii]; // update the element with the children found. if (!UpdateBrowseElement(child, nodesToBrowse, results, indexes[ii])) { children[ii] = null; continue; } // all done with objects. if (child.NodeClass == NodeClass.Object) { child.ParentId = parent.ItemId; children.Add(child); lock (m_lock) { child.CacheTimestamp = DateTime.UtcNow; m_cache[child.ItemId] = child; } } // prepare to read the properties from the server. indexes[ii] = PrepareBrowseElementReadRequest(child.NodeId, child.ReferencesByName, nodesToRead, child.NodeClass, true); } // check if nothing to do because only objects with no properties.. if (nodesToRead.Count == 0) { return children; } // read all child properties at once. DataValueCollection values = Read(session, nodesToRead); // process results and build final table. for (int ii = 0; ii < childrenToFind.Count; ii++) { BrowseElement child = childrenToFind[ii]; if (child == null || child.NodeClass == NodeClass.Object) { continue; } // update the browse element with the property values. if (!UpdateBrowseElement(session.TypeTree, child, nodesToRead, values, child.NodeClass, true, indexes[ii])) { continue; } // add variables to the cache. child.ParentId = parent.ItemId; children.Add(child); lock (m_lock) { child.CacheTimestamp = DateTime.UtcNow; m_cache[child.ItemId] = child; } } return children; }
/// <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); } }
/// <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. 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; } TreeNode child = new TreeNode(reference.ToString()); child.Nodes.Add(new TreeNode()); child.Tag = reference; e.Node.Nodes.Add(child); } } catch (Exception exception) { ClientUtils.HandleException(this.Text, exception); } }
private void PopulateBranch(NodeId sourceId, TreeNodeCollection nodes) { try { nodes.Clear(); // find all of the components of the node. BrowseDescription nodeToBrowse1 = new BrowseDescription(); nodeToBrowse1.NodeId = sourceId; nodeToBrowse1.BrowseDirection = BrowseDirection.Forward; nodeToBrowse1.ReferenceTypeId = ReferenceTypeIds.Aggregates; nodeToBrowse1.IncludeSubtypes = true; nodeToBrowse1.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse1.ResultMask = (uint)BrowseResultMask.All; // find all nodes organized by the node. BrowseDescription nodeToBrowse2 = new BrowseDescription(); nodeToBrowse2.NodeId = sourceId; nodeToBrowse2.BrowseDirection = BrowseDirection.Forward; nodeToBrowse2.ReferenceTypeId = ReferenceTypeIds.Organizes; nodeToBrowse2.IncludeSubtypes = true; nodeToBrowse2.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse2.ResultMask = (uint)BrowseResultMask.All; //find all type orgranized by the node. BrowseDescription nodetoBrowse3 = new BrowseDescription(); nodetoBrowse3.NodeId = sourceId; nodetoBrowse3.BrowseDirection = BrowseDirection.Forward; nodetoBrowse3.ReferenceTypeId = ReferenceTypeIds.References; nodetoBrowse3.IncludeSubtypes = true; nodetoBrowse3.NodeClassMask = (uint)(NodeClass.ReferenceType | NodeClass.ObjectType | NodeClass.DataType | NodeClass.VariableType); nodetoBrowse3.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse1); nodesToBrowse.Add(nodeToBrowse2); nodesToBrowse.Add(nodetoBrowse3); // fetch references from the server. ReferenceDescriptionCollection references = Browse(m_server, nodesToBrowse, false); // process results. for (int ii = 0; ii < references.Count; ii++) { ReferenceDescription target = references[ii]; // add node. TreeNode child = new TreeNode(Utils.Format("{0}", target)); child.Tag = target; child.Nodes.Add(new TreeNode()); nodes.Add(child); } // update the attributes display. DisplayAttributes(sourceId); } catch (Exception exception) { ServerUtils.HandleException(this.Text, exception); } }
private void ReadNode(NodeId nodeid, bool ignoreroot, bool ignorechildren, String DriverName) { INode node = m_session.NodeCache.Find(nodeid); if (node != null) { //TreeNode root = new TreeNode(node.ToString()); //root.ImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, false); //root.SelectedImageIndex = ClientUtils.GetImageIndex(m_session, node.NodeClass, node.TypeDefinitionId, true); ReferenceDescription reference = new ReferenceDescription(); reference.NodeId = node.NodeId; reference.NodeClass = node.NodeClass; reference.BrowseName = node.BrowseName; reference.DisplayName = node.DisplayName; reference.TypeDefinition = node.TypeDefinitionId; // build list of attributes to read. ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (uint attributeId in Attributes.GetIdentifiers()) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)reference.NodeId; nodeToRead.AttributeId = attributeId; nodesToRead.Add(nodeToRead); } // read the attributes. DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); if (ignoreroot == false) { //Log(results[0].ToString() + " \t| " + results[3].ToString() + " \t| "+ results[4].ToString() + " \t| " + results[12].ToString()); Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + s40(results[(int)Attributes.BrowseName - 1].ToString()) + " \tDisplayName: " + s40(results[(int)Attributes.DisplayName - 1].ToString()) + " \tDescription: " + S80(results[(int)Attributes.Description - 1].ToString()) + " \tValue: " + results[(int)Attributes.Value - 1].ToString()); dr = dt.NewRow(); dr["UID"] = results[(int)Attributes.NodeId - 1].ToString(); dr["BrowseName"] = results[(int)Attributes.BrowseName - 1].ToString(); dr["DisplayName"] = results[(int)Attributes.DisplayName - 1].ToString(); dr["Description"] = results[(int)Attributes.Description - 1].ToString(); dr["Value"] = results[(int)Attributes.Value - 1].ToString(); dr["Name"] = DriverName; dt.Rows.Add(dr); if (results[(int)Attributes.AccessLevel - 1].Value != null) { if (((byte)(results[(int)Attributes.AccessLevel - 1].GetValue(typeof(byte))) & AccessLevels.HistoryRead) == AccessLevels.HistoryRead) { //gv.DataSource = dt; ReadHistory(DateTime.Now.AddDays(-1), DateTime.Now, new NodeId(results[0].ToString()), 25, ""); } } } if (ignorechildren == false) { BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeid; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.HierarchicalReferences; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; if (reference != null) { nodeToBrowse.NodeId = (NodeId)reference.NodeId; } nodesToBrowse.Add(nodeToBrowse); ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, nodesToBrowse, false); for (int ii = 0; references != null && ii < references.Count; ii++) { reference = references[ii]; // build list of attributes to read. nodesToRead = new ReadValueIdCollection(); foreach (uint attributeId in Attributes.GetIdentifiers()) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)reference.NodeId; nodeToRead.AttributeId = attributeId; nodesToRead.Add(nodeToRead); } // read the attributes. results = null; diagnosticInfos = null; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); // Log("UID:"+results[0].ToString() + " \tBrowseName: " + results[(int)Attributes.BrowseName].ToString() + " \tDisplayName: " + results[(int)Attributes.DisplayName].ToString() + " \tDescription: " + results[(int)Attributes.Description].ToString() + " \t| " + results[(int)Attributes.Value].ToString()); //Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + results[(int)Attributes.BrowseName - 1].ToString() + " \tDisplayName: " + results[(int)Attributes.DisplayName - 1].ToString() + " \tDescription: " + results[(int)Attributes.Description - 1].ToString() + " \tValue: " + results[(int)Attributes.Value - 1].ToString()); Log("UID:" + S80(results[(int)Attributes.NodeId - 1].ToString()) + " \tBrowseName: " + s40(results[(int)Attributes.BrowseName - 1].ToString()) + " \tDisplayName: " + s40(results[(int)Attributes.DisplayName - 1].ToString()) + " \tDescription: " + S80(results[(int)Attributes.Description - 1].ToString()) + " \tValue: " + results[(int)Attributes.Value - 1].ToString()); dr = dt.NewRow(); dr["UID"] = results[(int)Attributes.NodeId - 1].ToString(); dr["BrowseName"] = results[(int)Attributes.BrowseName - 1].ToString(); dr["DisplayName"] = results[(int)Attributes.DisplayName - 1].ToString(); dr["Description"] = results[(int)Attributes.Description - 1].ToString(); dr["Value"] = results[(int)Attributes.Value - 1].ToString(); dt.Rows.Add(dr); try { if (results[(int)Attributes.AccessLevel - 1].Value != null) { if (((byte)(results[(int)Attributes.AccessLevel - 1].GetValue(typeof(byte))) & AccessLevels.HistoryRead) == AccessLevels.HistoryRead) { //gv.DataSource = dt; ReadHistory(DateTime.Today, DateTime.Now, new NodeId(results[0].ToString()), 25, ""); } } else { if (results[(int)Attributes.Value - 1].Value == null) { // gv.DataSource = dt; ReadNode(new NodeId(results[(int)Attributes.NodeId - 1].ToString()), true, false, ""); } } } catch { Log("V=" + results[17].ToString()); } } } } }
/// <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.Trace(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); } }
/// <summary> /// Browses the children of the node and updates the tree. /// </summary> private bool BrowseChildren(TreeNode parent) { ReferenceDescription reference = parent.Tag as ReferenceDescription; if (reference == null) { return(false); } parent.Nodes.Clear(); if (reference.NodeId.IsAbsolute) { return(false); } BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = (NodeId)reference.NodeId; nodeToBrowse.BrowseDirection = m_browseDirection; nodeToBrowse.ReferenceTypeId = m_referenceTypeId; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)(int)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); ViewDescription view = null; if (NodeId.IsNull(m_viewId)) { view = new ViewDescription(); view.ViewId = m_viewId; view.Timestamp = DateTime.MinValue; view.ViewVersion = 0; } BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Browse( null, view, 0, nodesToBrowse, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return(false); } UpdateNode(parent, results[0].References); while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); m_session.BrowseNext( null, parent == null, continuationPoints, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return(false); } UpdateNode(parent, results[0].References); } return(true); }
/// <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 = new AttributeInfo() { NodeToRead = nodesToRead[ii], Value = results[ii] }; item.ImageIndex = ClientUtils.GetImageIndex(m_session, NodeClass.Variable, Opc.Ua.VariableTypeIds.PropertyType, false); // display in list. AttributesLV.Items.Add(item); } }
/// <summary> /// Invokes the Browse service. /// </summary> public virtual ResponseHeader Browse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { BrowseRequest request = new BrowseRequest(); BrowseResponse response = null; request.RequestHeader = requestHeader; request.View = view; request.RequestedMaxReferencesPerNode = requestedMaxReferencesPerNode; request.NodesToBrowse = nodesToBrowse; UpdateRequestHeader(request, requestHeader == null, "Browse"); try { if (UseTransportChannel) { IServiceResponse genericResponse = TransportChannel.SendRequest(request); if (genericResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } ValidateResponse(genericResponse.ResponseHeader); response = (BrowseResponse)genericResponse; } else { BrowseResponseMessage responseMessage = InnerChannel.Browse(new BrowseMessage(request)); if (responseMessage == null || responseMessage.BrowseResponse == null) { throw new ServiceResultException(StatusCodes.BadUnknownResponse); } response = responseMessage.BrowseResponse; ValidateResponse(response.ResponseHeader); } results = response.Results; diagnosticInfos = response.DiagnosticInfos; } finally { RequestCompleted(request, response, "Browse"); } return response.ResponseHeader; }
/// <summary> /// Begins an asynchronous invocation of 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="callback">The callback.</param> /// <param name="asyncState"></param> /// <returns></returns> public IAsyncResult BeginBrowse( RequestHeader requestHeader, ViewDescription view, NodeId nodeToBrowse, uint maxResultsToReturn, BrowseDirection browseDirection, NodeId referenceTypeId, bool includeSubtypes, uint nodeClassMask, AsyncCallback callback, object asyncState) { 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); return BeginBrowse( requestHeader, view, maxResultsToReturn, nodesToBrowse, callback, asyncState); }
/// <summary> /// Begins an asynchronous invocation of the Browse service. /// </summary> public IAsyncResult BeginBrowse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, AsyncCallback callback, object asyncState) { BrowseRequest request = new BrowseRequest(); request.RequestHeader = requestHeader; request.View = view; request.RequestedMaxReferencesPerNode = requestedMaxReferencesPerNode; request.NodesToBrowse = nodesToBrowse; UpdateRequestHeader(request, requestHeader == null, "Browse"); if (UseTransportChannel) { return TransportChannel.BeginSendRequest(request, callback, asyncState); } return InnerChannel.BeginBrowse(new BrowseMessage(request), callback, asyncState); }
/// <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); references.AddRange(additionalReferences); } // return the results. return references; } finally { m_browseInProgress = false; } }
/// <summary> /// Fetches the references for the node. /// </summary> private List<ReferenceDescription> Browse(Session session, NodeId nodeId) { List<ReferenceDescription> references = new List<ReferenceDescription>(); // specify the references to follow and the fields to return. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.References; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.BrowseDirection = BrowseDirection.Both; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = session.Browse( null, null, 2, nodesToBrowse, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add first batch. references.AddRange(results[0].References); // check if server limited the results. while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); // continue browse operation. responseHeader = session.BrowseNext( null, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add next batch. references.AddRange(results[0].References); } return references; }
/// <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; } }
private static BrowseDescriptionCollection PrepareBrowseDescriptionCollection( NodeId nodeId, uint nodeClassMask) { // We do not inspect all references, but only organize and HasComponent. BrowseDescriptionCollection browseDescriptionCollection = new BrowseDescriptionCollection(); BrowseDescription nodeToBrowse = new BrowseDescription() { NodeId = nodeId, ReferenceTypeId = ReferenceTypeIds.Organizes, IncludeSubtypes = true, BrowseDirection = BrowseDirection.Forward, NodeClassMask = nodeClassMask, ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription() { NodeId = nodeId, ReferenceTypeId = ReferenceTypeIds.HasComponent, IncludeSubtypes = true, BrowseDirection = BrowseDirection.Forward, NodeClassMask = nodeClassMask, ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription() { NodeId = nodeId, ReferenceTypeId = ReferenceTypeIds.HasChild, IncludeSubtypes = true, BrowseDirection = BrowseDirection.Forward, NodeClassMask = nodeClassMask, ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription() { NodeId = nodeId, ReferenceTypeId = ReferenceTypeIds.HasDescription, IncludeSubtypes = true, BrowseDirection = BrowseDirection.Forward, NodeClassMask = nodeClassMask, ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription() { NodeId = nodeId, ReferenceTypeId = ReferenceTypeIds.HasProperty, IncludeSubtypes = true, BrowseDirection = BrowseDirection.Forward, NodeClassMask = nodeClassMask, ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); nodeToBrowse = new BrowseDescription { NodeId = nodeId, BrowseDirection = BrowseDirection.Forward, ReferenceTypeId = ReferenceTypeIds.HasProperty, IncludeSubtypes = true, NodeClassMask = (uint)(NodeClass.Variable | NodeClass.Object), ResultMask = (uint)BrowseResultMask.All }; browseDescriptionCollection.Add(nodeToBrowse); return(browseDescriptionCollection); }
/// <summary> /// Returns the next reference. /// </summary> /// <returns>The next reference that meets the browse criteria.</returns> public override IReference Next() { lock (DataLock) { IReference reference = null; // enumerate pre-defined references. // always call first to ensure any pushed-back references are returned first. reference = base.Next(); if (reference != null) { return(reference); } // don't start browsing huge number of references when only internal references are requested. if (InternalOnly) { return(null); } if (m_stage == Stage.Begin) { // construct request. BrowseDescription nodeToBrowse = new BrowseDescription(); NodeId startId = ObjectIds.ObjectsFolder; if (m_source != null) { startId = m_mapper.ToRemoteId(m_source.NodeId); } nodeToBrowse.NodeId = startId; nodeToBrowse.BrowseDirection = this.BrowseDirection; nodeToBrowse.ReferenceTypeId = this.ReferenceType; nodeToBrowse.IncludeSubtypes = this.IncludeSubtypes; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_client.Browse( null, null, 0, nodesToBrowse, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); m_position = 0; m_references = null; m_continuationPoint = null; m_stage = Stage.References; // check status. if (StatusCode.IsGood(results[0].StatusCode)) { m_references = results[0].References; m_continuationPoint = results[0].ContinuationPoint; reference = NextChild(); if (reference != null) { return(reference); } } } if (m_stage == Stage.References) { reference = NextChild(); if (reference != null) { return(reference); } if (m_source == null && IsRequired(ReferenceTypes.HasNotifier, false)) { // construct request. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = ObjectIds.Server; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = ReferenceTypes.HasNotifier; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = m_client.Browse( null, null, 0, nodesToBrowse, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); m_position = 0; m_references = null; m_continuationPoint = null; m_stage = Stage.Notifiers; // check status. if (StatusCode.IsGood(results[0].StatusCode)) { m_references = results[0].References; m_continuationPoint = results[0].ContinuationPoint; } } m_stage = Stage.Notifiers; } if (m_stage == Stage.Notifiers) { reference = NextChild(); if (reference != null) { return(reference); } m_stage = Stage.Done; } // all done. return(null); } }
/// <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()); }
/// <summary> /// Reads the arguments for the method. /// </summary> private void ReadArguments(NodeId nodeId) { m_inputArguments = null; m_outputArguments = null; // 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.BrowseName; nodesToBrowse.Add(nodeToBrowse); // find properties. ReferenceDescriptionCollection references = ClientUtils.Browse(m_session, null, 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; } // ignore other properties. if (reference.BrowseName != Opc.Ua.BrowseNames.InputArguments && reference.BrowseName != Opc.Ua.BrowseNames.OutputArguments) { continue; } ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = (NodeId)reference.NodeId; nodeToRead.AttributeId = Attributes.Value; nodeToRead.Handle = reference; nodesToRead.Add(nodeToRead); } // method has no arguments. if (nodesToRead.Count == 0) { return; } // read the arguments. 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); // save the results. for (int ii = 0; ii < results.Count; ii++) { ReferenceDescription reference = (ReferenceDescription)nodesToRead[ii].Handle; if (StatusCode.IsGood(results[ii].StatusCode)) { if (reference.BrowseName == Opc.Ua.BrowseNames.InputArguments) { m_inputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue <ExtensionObject[]>(null), typeof(Argument)); } if (reference.BrowseName == Opc.Ua.BrowseNames.OutputArguments) { m_outputArguments = (Argument[])ExtensionObject.ToArray(results[ii].GetValue <ExtensionObject[]>(null), typeof(Argument)); } } } // set default values for input arguments. if (m_inputArguments != null) { foreach (Argument argument in m_inputArguments) { argument.Value = TypeInfo.GetDefaultValue(argument.DataType, argument.ValueRank, m_session.TypeTree); } } }
/// <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()); }
static void Browse(Session session) { DiagnosticInfoCollection diagnosticInfos; BrowseDescriptionCollection bc = new BrowseDescriptionCollection(); BrowseDescription bd = new BrowseDescription(); bd.BrowseDirection = BrowseDirection.Forward; NodeId nodeId = Opc.Ua.Objects.ObjectsFolder; do { Console.WriteLine("\n Enter nodeId to Browse (or q to exit)"); string s = Console.ReadLine(); if (s == "q") break; if (s.Length == 0) { nodeId = Opc.Ua.Objects.ObjectsFolder; } else nodeId = new NodeId(s); bc.Clear(); bd.NodeId = nodeId; bc.Add(bd); BrowseResultCollection results; ResponseHeader rh = session.Browse(null, null, 100, bc, out results, out diagnosticInfos); foreach ( BrowseResult res in results) { foreach (ReferenceDescription rdc in res.References) { Console.WriteLine(String.Format(" Node = {0} (namespace {1}) {2}", rdc.NodeId.ToString(),rdc.NodeId.NamespaceIndex, Environment.NewLine)); } } } while (true); }
/// <summary> /// Gets the list of references to follow. /// </summary> private BrowseDescriptionCollection CreateNodesToBrowse() { BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); if (ReferenceTypeIds != null && ReferenceTypeIds.Length > 0) { for (int ii = 0; ii < ReferenceTypeIds.Length; ii++) { BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = NodeId; nodeToBrowse.BrowseDirection = BrowseDirection; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds[ii]; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; nodesToBrowse.Add(nodeToBrowse); } } else { BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = NodeId; nodeToBrowse.BrowseDirection = BrowseDirection; nodeToBrowse.ReferenceTypeId = Opc.Ua.ReferenceTypeIds.References; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; nodesToBrowse.Add(nodeToBrowse); } return nodesToBrowse; }
/// <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) { return(Browse(session, null, nodesToBrowse, throwOnError)); }
/// <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.Trace(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); } }
/// <summary> /// Finds the targets for the specified reference. /// </summary> private static List <NodeId> FindTargetOfReference(Session session, List <NodeId> nodeIds, NodeId referenceTypeId, bool throwOnError) { try { // construct browse request. BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection( ); for (int ii = 0; ii < nodeIds.Count; ii++) { BrowseDescription nodeToBrowse = new BrowseDescription( ); nodeToBrowse.NodeId = nodeIds[ii]; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = referenceTypeId; nodeToBrowse.IncludeSubtypes = false; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.None; nodesToBrowse.Add(nodeToBrowse); } // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; session.Browse( null, null, 1, nodesToBrowse, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); List <NodeId> targetIds = new List <NodeId>( ); ByteStringCollection continuationPoints = new ByteStringCollection( ); for (int ii = 0; ii < nodeIds.Count; ii++) { targetIds.Add(null); // check for error. if (StatusCode.IsBad(results[ii].StatusCode)) { continue; } // check for continuation point. if (results[ii].ContinuationPoint != null && results[ii].ContinuationPoint.Length > 0) { continuationPoints.Add(results[ii].ContinuationPoint); } // get the node id. if (results[ii].References.Count > 0) { if (NodeId.IsNull(results[ii].References[0].NodeId) || results[ii].References[0].NodeId.IsAbsolute) { continue; } targetIds[ii] = (NodeId)results[ii].References[0].NodeId; } } // release continuation points. if (continuationPoints.Count > 0) { session.BrowseNext( null, true, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); } //return complete list. return(targetIds); } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return(null); } }
/// <summary> /// Fetches the references for the node. /// </summary> private List <ReferenceDescription> Browse(Session session, NodeId nodeId) { List <ReferenceDescription> references = new List <ReferenceDescription>(); // specify the references to follow and the fields to return. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.References; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.BrowseDirection = BrowseDirection.Both; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); // start the browse operation. BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ResponseHeader responseHeader = session.Browse( null, null, 2, nodesToBrowse, out results, out diagnosticInfos); // these do sanity checks on the result - make sure response matched the request. ClientBase.ValidateResponse(results, nodesToBrowse); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToBrowse); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add first batch. references.AddRange(results[0].References); // check if server limited the results. while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); // continue browse operation. responseHeader = session.BrowseNext( null, false, continuationPoints, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, continuationPoints); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, continuationPoints); // check status. if (StatusCode.IsBad(results[0].StatusCode)) { // embed the diagnostic information in a exception. throw ServiceResultException.Create(results[0].StatusCode, 0, diagnosticInfos, responseHeader.StringTable); } // add next batch. references.AddRange(results[0].References); } return(references); }
/// <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; }
/// <summary> /// Returns the set of references that meet the filter criteria. /// </summary> public virtual void Browse( OperationContext context, ViewDescription view, uint maxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { if (context == null) throw new ArgumentNullException("context"); if (nodesToBrowse == null) throw new ArgumentNullException("nodesToBrowse"); if (view != null && !NodeId.IsNull(view.ViewId)) { INodeManager viewManager = null; object viewHandle = GetManagerHandle(view.ViewId, out viewManager); if (viewHandle == null) { throw new ServiceResultException(StatusCodes.BadViewIdUnknown); } NodeMetadata metadata = viewManager.GetNodeMetadata(context, viewHandle, BrowseResultMask.NodeClass); if (metadata == null || metadata.NodeClass != NodeClass.View) { throw new ServiceResultException(StatusCodes.BadViewIdUnknown); } view.Handle = viewHandle; } bool diagnosticsExist = false; results = new BrowseResultCollection(nodesToBrowse.Count); diagnosticInfos = new DiagnosticInfoCollection(nodesToBrowse.Count); uint continuationPointsAssigned = 0; for (int ii = 0; ii < nodesToBrowse.Count; ii++) { // check if request has timed out or been cancelled. if (StatusCode.IsBad(context.OperationStatus)) { // release all allocated continuation points. foreach (BrowseResult current in results) { if (current != null && current.ContinuationPoint != null && current.ContinuationPoint.Length > 0) { ContinuationPoint cp = context.Session.RestoreContinuationPoint(current.ContinuationPoint); cp.Dispose(); } } throw new ServiceResultException(context.OperationStatus); } BrowseDescription nodeToBrowse = nodesToBrowse[ii]; // initialize result. BrowseResult result = new BrowseResult(); result.StatusCode = StatusCodes.Good; results.Add(result); ServiceResult error = null; // need to trap unexpected exceptions to handle bugs in the node managers. try { error = Browse( context, view, maxReferencesPerNode, continuationPointsAssigned < m_maxContinuationPointsPerBrowse, nodeToBrowse, result); } catch (Exception e) { error = ServiceResult.Create(e, StatusCodes.BadUnexpectedError, "Unexpected error browsing node."); } // check for continuation point. if (result.ContinuationPoint != null && result.ContinuationPoint.Length > 0) { continuationPointsAssigned++; } // check for error. result.StatusCode = error.StatusCode; if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0) { DiagnosticInfo diagnosticInfo = null; if (error != null && error.Code != StatusCodes.Good) { diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error); diagnosticsExist = true; } diagnosticInfos.Add(diagnosticInfo); } } // clear the diagnostics array if no diagnostics requested or no errors occurred. UpdateDiagnostics(context, diagnosticsExist, ref diagnosticInfos); }
/// <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 { AttributesView.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 = Browse(m_server, 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. OperationContext context = new OperationContext(new RequestHeader(), RequestType.Browse); DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_server.CurrentInstance.NodeManager.Read( context, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ListViewItem idnode = new ListViewItem("NodeID"); idnode.SubItems.Add(sourceId.ToString()); AttributesView.Items.Add(idnode); // 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(value); item.SubItems.Add(datatype); AttributesView.Items.Add(item); } // adjust width of all columns. for (int ii = 0; ii < AttributesView.Columns.Count; ii++) { AttributesView.Columns[ii].Width = -2; } } catch (Exception exception) { ServerUtils.HandleException(this.Text, exception); } }
/// <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); }
/// <summary> /// Invokes the Browse service. /// </summary> public virtual ResponseHeader Browse( RequestHeader requestHeader, ViewDescription view, uint requestedMaxReferencesPerNode, BrowseDescriptionCollection nodesToBrowse, out BrowseResultCollection results, out DiagnosticInfoCollection diagnosticInfos) { results = null; diagnosticInfos = null; ValidateRequest(requestHeader); // Insert implementation. return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported); }
/// <summary> /// Browses the children of the node and updates the tree. /// </summary> private bool BrowseChildren(TreeNode parent) { ReferenceDescription reference = parent.Tag as ReferenceDescription; if (reference == null) { return false; } parent.Nodes.Clear(); if (reference.NodeId.IsAbsolute) { return false; } BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = (NodeId)reference.NodeId; nodeToBrowse.BrowseDirection = m_browseDirection; nodeToBrowse.ReferenceTypeId = m_referenceTypeId; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = 0; nodeToBrowse.ResultMask = (uint)(int)BrowseResultMask.All; BrowseDescriptionCollection nodesToBrowse = new BrowseDescriptionCollection(); nodesToBrowse.Add(nodeToBrowse); ViewDescription view = null; if (NodeId.IsNull(m_viewId)) { view = new ViewDescription(); view.ViewId = m_viewId; view.Timestamp = DateTime.MinValue; view.ViewVersion = 0; } BrowseResultCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; m_session.Browse( null, view, 0, nodesToBrowse, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return false; } UpdateNode(parent, results[0].References); while (results[0].ContinuationPoint != null && results[0].ContinuationPoint.Length > 0) { ByteStringCollection continuationPoints = new ByteStringCollection(); continuationPoints.Add(results[0].ContinuationPoint); m_session.BrowseNext( null, parent == null, continuationPoints, out results, out diagnosticInfos); if (results.Count != 1 || StatusCode.IsBad(results[0].StatusCode)) { return false; } UpdateNode(parent, results[0].References); } return true; }