/// <summary> /// Displays the address space with the specified view /// </summary> public void Show(Session session, NodeId startId) { if (session == null) throw new ArgumentNullException("session"); if (m_session != null) { m_session.SessionClosing -= m_SessionClosing; } m_session = session; m_session.SessionClosing += m_SessionClosing; Browser browser = new Browser(session); browser.BrowseDirection = BrowseDirection.Both; browser.ContinueUntilDone = true; browser.ReferenceTypeId = ReferenceTypeIds.References; BrowseCTRL.Initialize(browser, startId); UpdateNavigationBar(); Show(); BringToFront(); }
public void NodeIdCompareToTestMethod() { NodeId _property = new NodeId(VariableTypes.PropertyType); Assert.AreNotSame(_property, VariableTypeIds.PropertyType); int _res = _property.CompareTo(VariableTypeIds.PropertyType); Assert.AreEqual<int>(0, _res); }
public SessionDiagnosticsDlg(Session session, NodeId sessionNodeId) { InitializeComponent(); List<DiagnosticListViewItem> list = CreateItems(session, sessionNodeId); serverDiagnosticCtrl1.LoadItems(session, list); }
public GetPeersTask(DhtEngine engine, NodeId infohash) { _engine = engine; _infoHash = infohash; _closestNodes = new SortedList<NodeId, NodeId>(Bucket.MaxCapacity); ClosestActiveNodes = new SortedList<NodeId, Node>(Bucket.MaxCapacity*2); }
/// <summary> /// Displays the dialog. /// </summary> public void Show(Session session, NodeId objectId, NodeId methodId) { if (session == null) throw new ArgumentNullException("session"); if (methodId == null) throw new ArgumentNullException("methodId"); if (m_session != null) { m_session.SessionClosing -= m_SessionClosing; } m_session = session; m_session.SessionClosing += m_SessionClosing; m_objectId = objectId; m_methodId = methodId; InputArgumentsCTRL.Update(session, methodId, true); OutputArgumentsCTRL.Update(session, methodId, false); Node target = session.NodeCache.Find(objectId) as Node; Node method = session.NodeCache.Find(methodId) as Node; if (target != null && method != null) { Text = String.Format("Call {0}.{1}", target, method); } Show(); BringToFront(); }
/// <summary cref="IFilterTarget.GetAttributeValue" /> public virtual object GetAttributeValue( FilterContext context, NodeId typeDefinitionId, IList<QualifiedName> relativePath, uint attributeId, NumericRange indexRange) { if (context == null) throw new ArgumentNullException("context"); // read the attribute value. DataValue dataValue = ReadAttributeValue( context, typeDefinitionId, relativePath, attributeId, indexRange); if (StatusCode.IsBad(dataValue.StatusCode)) { return dataValue.StatusCode; } // return the value. return dataValue.Value; }
public DataAddress(BlockId blockId, int dataId) { // TODO: Check for overflow? long[] blockAddr = blockId.ReferenceAddress; blockAddr[1] |= dataId & 0x0FFFF; value = new NodeId(blockAddr); }
/// <summary> /// Sets the nodes in the control. /// </summary> public void Initialize(Session session, ExpandedNodeId nodeId) { if (session == null) throw new ArgumentNullException("session"); Clear(); if (nodeId == null) { return; } m_session = session; m_nodeId = (NodeId)nodeId; INode node = m_session.NodeCache.Find(m_nodeId); if (node != null && (node.NodeClass & (NodeClass.Variable | NodeClass.Object)) != 0) { AddReferences(ReferenceTypeIds.HasTypeDefinition, BrowseDirection.Forward); AddReferences(ReferenceTypeIds.HasModellingRule, BrowseDirection.Forward); } AddAttributes(); AddProperties(); }
public AnnouncePeer(NodeId id, NodeId infoHash, BEncodedNumber port, BEncodedString token) : base(id, QueryName, responseCreator) { Parameters.Add(InfoHashKey, infoHash.BencodedString()); Parameters.Add(PortKey, port); Parameters.Add(TokenKey, token); }
public GetPeersTask(DhtEngine engine, NodeId infohash) { this.engine = engine; this.infoHash = infohash; this.closestNodes = new SortedList<NodeId, NodeId>(Bucket.MaxCapacity); this.queriedNodes = new SortedList<NodeId, Node>(Bucket.MaxCapacity * 2); }
protected ResponseMessage(NodeId id, BEncodedValue transactionId) : base(ResponseType) { Properties.Add(ReturnValuesKey, new BEncodedDictionary()); Parameters.Add(IdKey, id.BencodedString()); TransactionId = transactionId; }
private List<DiagnosticListViewItem> CreateItems(Session session) { List<DiagnosticListViewItem> items = new List<DiagnosticListViewItem>(); NodeId serverNode = new NodeId(Objects.Server); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.EnabledFlag", 0, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary", 0, true, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.CumulatedSessionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.CumulatedSubscriptionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.CurrentSessionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.CurrentSubscriptionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.PublishingRateCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.RejectedRequestsCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.RejectedSessionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.SamplingRateCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.SecurityRejectedRequestsCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.SecurityRejectedSessionCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.ServerViewCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.SessionAbortCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.ServerDiagnosticsSummary.SessionTimeoutCount", 1, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.SamplingRateDiagnosticsArray", 0, true, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.SubscriptionDiagnosticsArray", 0, true, true)); items.Add(new DiagnosticListViewItem(serverNode,"ServerDiagnostics.SessionDiagnosticsSummary", 0, false, false)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.SessionDiagnosticsSummary.SessionDiagnosticsArray", 1, true, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerDiagnostics.SessionDiagnosticsSummary.SessionSecurityDiagnosticsArray", 1, true, true)); return items; }
/// <summary cref="IFilterTarget.IsInView" /> public bool IsInView( FilterContext context, NodeId viewId) { // events instances are not in any view. return false; }
/// <summary> /// Initializes the calculation stream. /// </summary> /// <param name="aggregateId">The aggregate function to apply.</param> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <param name="processingInterval">The processing interval.</param> /// <param name="stepped">Whether to use stepped interpolation.</param> /// <param name="configuration">The aggregate configuration.</param> protected void Initialize( NodeId aggregateId, DateTime startTime, DateTime endTime, double processingInterval, bool stepped, AggregateConfiguration configuration) { AggregateId = aggregateId; StartTime = startTime; EndTime = endTime; ProcessingInterval = processingInterval; Stepped = stepped; Configuration = configuration; TimeFlowsBackward = (endTime < startTime); if (processingInterval == 0) { if (endTime == DateTime.MinValue || startTime == DateTime.MinValue) { throw new ArgumentException("Non-zero processingInterval required.", "processingInterval"); } ProcessingInterval = Math.Abs((endTime - startTime).TotalMilliseconds); } m_values = new LinkedList<DataValue>(); }
/// <summary cref="IFilterTarget.IsTypeOf" /> public bool IsTypeOf( FilterContext context, NodeId typeDefinitionId) { if (context == null) throw new ArgumentNullException("context"); return context.TypeTree.IsTypeOf(TypeDefinitionId, typeDefinitionId); }
protected QueryMessage(NodeId id, BEncodedString queryName, BEncodedDictionary queryArguments, ResponseCreator responseCreator) : base(QueryType) { Properties.Add(QueryNameKey, queryName); Properties.Add(QueryArgumentsKey, queryArguments); Parameters.Add(IdKey, id.BencodedString()); ResponseCreator = responseCreator; }
/// <summary> /// Creates a default aggregator. /// </summary> protected AggregateCalculator(NodeId aggregateId) { AggregateConfiguration configuration = new AggregateConfiguration(); configuration.TreatUncertainAsBad = false; configuration.PercentDataBad = 100; configuration.PercentDataGood = 100; configuration.UseSlopedExtrapolation = false; Initialize(aggregateId, DateTime.UtcNow, DateTime.MaxValue, 1000, false, configuration); }
/// <summary> /// Initializes the control. /// </summary> public void Initialize(Session session, NodeId typeId) { ItemsLV.Items.Clear(); AdjustColumns(); if (session == null) { return; } ILocalNode root = session.NodeCache.Find(typeId) as ILocalNode; if (root == null) { return; } m_session = session; SortedDictionary<string,InstanceDeclaration> instances = new SortedDictionary<string,InstanceDeclaration>(); InstanceDeclaration declaration = new InstanceDeclaration(); declaration.Instance = root; declaration.DisplayPath = Utils.Format("({0})", root.NodeClass); declaration.Description = Utils.Format("{0}", root.Description); declaration.DataType = "NodeId"; IVariableBase variable = root as IVariableBase; if (variable != null) { INode dataType = m_session.NodeCache.Find(variable.DataType); if (dataType != null) { declaration.DataType = Utils.Format("{0}", dataType); } if (variable.ValueRank >= 0) { declaration.DataType += "[]"; } } instances.Add(declaration.DisplayPath, declaration); CollectInstances(root, String.Empty, instances); foreach (InstanceDeclaration instance in instances.Values) { AddItem(instance); } AdjustColumns(); }
/// <summary> /// Creates the session. /// </summary> public void Create( EndpointDescription endpoint, ApplicationDescription client, byte[] clientCertificate, string sessionName, double sessionTimeout, out NodeId sessionId, out NodeId authenticationToken, out byte[] serverNonce, out double revisedSessionTimeout) { lock (m_lock) { // save the secure channel id. m_secureChannelId = null; if (OperationContext.Current != null) { m_secureChannelId = OperationContext.Current.Channel.SessionId; } m_endpoint = endpoint; m_client = client; m_sessionName = sessionName; if (clientCertificate != null) { m_clientCertificate = new X509Certificate2(clientCertificate); } // Create a public and a private identifier for the session. The public identifier is visible in the // address space and audit logs. The private identifier is only used by the client to identify itself // when it sends a request. Clients and servers that do not keep the authentication token will be vulnerable // to session hijacking when using transports such as SSL to implement the secure channel. It is not an // issue for applications that use WS-Secure Conversation. // create a guid for a session id. use it for an authentication token as well. m_sessionId = new NodeId(System.Guid.NewGuid(), 1); m_authenticationToken = authenticationToken = sessionId = m_sessionId; // set a reasonable session timeout. m_sessionTimeout = sessionTimeout; if (m_sessionTimeout < 30000) { m_sessionTimeout = 30000; } revisedSessionTimeout = m_sessionTimeout; // create a server nonce. m_serverNonce = serverNonce = new byte[32]; RNGCryptoServiceProvider random = new RNGCryptoServiceProvider(); random.GetBytes(m_serverNonce); } }
/// <summary cref="IFilterTarget.IsRelatedTo" /> public virtual bool IsRelatedTo( FilterContext context, NodeId source, NodeId targetTypeId, NodeId referenceTypeId, int hops) { // events instances do not have any relationships to other nodes. return false; }
/// <summary> /// Initializes the calculation stream. /// </summary> /// <param name="aggregateId">The aggregate function to apply.</param> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <param name="processingInterval">The processing interval.</param> /// <param name="stepped">Whether to use stepped interpolation.</param> /// <param name="configuration">The aggregate configuration.</param> public AggregateCalculator( NodeId aggregateId, DateTime startTime, DateTime endTime, double processingInterval, bool stepped, AggregateConfiguration configuration) { Initialize(aggregateId, startTime, endTime, processingInterval, stepped, configuration); }
public NodeIdTests() { nodes = new NodeId[20]; for (var i = 0; i < nodes.Length; i++) { var id = new byte[20]; for (var j = 0; j < id.Length; j++) id[j] = (byte) (i*20 + j); nodes[i] = new NodeId(id); } }
//private ILocalNode m_selectedType; #endregion #region Public Interface /// <summary> /// Displays the dialog. /// </summary> public void Show( Session session, NodeId typeId) { if (session == null) throw new ArgumentNullException("session"); m_session = session; //TypeNavigatorCTRL.Initialize(m_session, typeId); //TypeHierarchyCTRL.Initialize(m_session, typeId); }
private List<DiagnosticListViewItem> CreateItems(Session session) { List<DiagnosticListViewItem> items = new List<DiagnosticListViewItem>(); NodeId serverNode = new NodeId(Objects.Server); items.Add(new DiagnosticListViewItem(serverNode, "ServerCapabilities.MaxParallelContinuationPointsPerSession", 0, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerCapabilities.MinSupportedSampleRate", 0, false, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerCapabilities.IdTypeArray", 0, true, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerCapabilities.LocaleIdArray", 0, true, true)); items.Add(new DiagnosticListViewItem(serverNode, "ServerCapabilities.ServerProfileArray", 0, true, true)); return items; }
public void Setup() { nodes = new NodeId[20]; for (int i = 0; i < nodes.Length; i++) { byte[] id = new byte[20]; for (int j = 0; j < id.Length; j++) id[j] = (byte)(i * 20 + j); nodes[i] = new NodeId(id); } }
/// <summary> /// Sets the nodes in the control. /// </summary> public bool Update(Session session, NodeId methodId, bool inputArgs) { if (session == null) throw new ArgumentNullException("session"); if (methodId == null) throw new ArgumentNullException("methodId"); Clear(); m_session = session; // find the method. MethodNode method = session.NodeCache.Find(methodId) as MethodNode; if (method == null) { return false; } // select the property to find. QualifiedName browseName = null; if (inputArgs) { browseName = Opc.Ua.BrowseNames.InputArguments; } else { browseName = Opc.Ua.BrowseNames.OutputArguments; } // fetch the argument list. VariableNode argumentsNode = session.NodeCache.Find(methodId, ReferenceTypeIds.HasProperty, false, true, browseName) as VariableNode; if (argumentsNode == null) { return false; } // read the value from the server. DataValue value = m_session.ReadValue(argumentsNode.NodeId); ExtensionObject[] argumentsList = value.Value as ExtensionObject[]; if (argumentsList != null) { for (int ii = 0; ii < argumentsList.Length; ii++) { AddItem(argumentsList[ii].Body as Argument); } } AdjustColumns(); return ItemsLV.Items.Count > 0; }
/// <summary> /// Initializes the aggregate calculator. /// </summary> /// <param name="aggregateId">The aggregate function to apply.</param> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <param name="processingInterval">The processing interval.</param> /// <param name="stepped">Whether to use stepped interpolation.</param> /// <param name="configuration">The aggregate configuration.</param> public AverageAggregateCalculator( NodeId aggregateId, DateTime startTime, DateTime endTime, double processingInterval, bool stepped, AggregateConfiguration configuration) : base(aggregateId, startTime, endTime, processingInterval, stepped, configuration) { SetPartialBit = aggregateId != Opc.Ua.ObjectIds.AggregateFunction_Average; }
/// <summary> /// Checks if the aggregate is supported by the server. /// </summary> /// <param name="aggregateId">The id of the aggregate function.</param> /// <returns>True if the aggregate is supported.</returns> public bool IsSupported(NodeId aggregateId) { if (NodeId.IsNull(aggregateId)) { return false; } lock (m_lock) { return m_factories.ContainsKey(aggregateId); } }
public void CompareTest() { byte[] i = new byte[20]; byte[] j = new byte[20]; i[19] = 1; j[19] = 2; NodeId one = new NodeId(i); NodeId two = new NodeId(j); Assert.IsTrue(one.CompareTo(two) < 0); Assert.IsTrue(two.CompareTo(one) > 0); Assert.IsTrue(one.CompareTo(one) == 0); }
/// <summary> /// Initializes the aggregate calculator. /// </summary> /// <param name="aggregateId">The aggregate function to apply.</param> /// <param name="startTime">The start time.</param> /// <param name="endTime">The end time.</param> /// <param name="processingInterval">The processing interval.</param> /// <param name="stepped">Whether to use stepped interpolation.</param> /// <param name="configuration">The aggregate configuration.</param> public StartEndAggregateCalculator( NodeId aggregateId, DateTime startTime, DateTime endTime, double processingInterval, bool stepped, AggregateConfiguration configuration) : base(aggregateId, startTime, endTime, processingInterval, stepped, configuration) { SetPartialBit = true; }
/// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return(NodeId.Create(VariableTypes.MemoryTagType, Namespaces.MemoryBuffer, namespaceUris)); }
/// <summary> /// Creates a new instance. /// </summary> public ValidateSessionLessRequestEventArgs(NodeId authenticationToken, RequestType requestType) { AuthenticationToken = authenticationToken; RequestType = requestType; }
/// <summary> /// Creates a new session. /// </summary> public virtual Session CreateSession( OperationContext context, X509Certificate2 serverCertificate, string sessionName, byte[] clientNonce, ApplicationDescription clientDescription, string endpointUrl, X509Certificate2 clientCertificate, double requestedSessionTimeout, uint maxResponseMessageSize, out NodeId sessionId, out NodeId authenticationToken, out byte[] serverNonce, out double revisedSessionTimeout) { sessionId = 0; revisedSessionTimeout = requestedSessionTimeout; Session session = null; lock (m_lock) { // check session count. if (m_maxSessionCount > 0 && m_sessions.Count >= m_maxSessionCount) { throw new ServiceResultException(StatusCodes.BadTooManySessions); } // check for same Nonce in another session if (clientNonce != null) { foreach (Session sessionIterator in m_sessions.Values) { if (Utils.CompareNonce(sessionIterator.ClientNonce, clientNonce)) { throw new ServiceResultException(StatusCodes.BadNonceInvalid); } } } // can assign a simple identifier if secured. authenticationToken = null; if (!String.IsNullOrEmpty(context.ChannelContext.SecureChannelId)) { if (context.ChannelContext.EndpointDescription.SecurityMode != MessageSecurityMode.None) { authenticationToken = Utils.IncrementIdentifier(ref m_lastSessionId); } } // must assign a hard-to-guess id if not secured. if (authenticationToken == null) { byte[] token = Utils.Nonce.CreateNonce(32); authenticationToken = new NodeId(token); } // determine session timeout. if (requestedSessionTimeout > m_maxSessionTimeout) { revisedSessionTimeout = m_maxSessionTimeout; } if (requestedSessionTimeout < m_minSessionTimeout) { revisedSessionTimeout = m_minSessionTimeout; } // create server nonce. serverNonce = Utils.Nonce.CreateNonce((uint)m_minNonceLength); // assign client name. if (String.IsNullOrEmpty(sessionName)) { sessionName = Utils.Format("Session {0}", sessionId); } // create instance of session. session = CreateSession( context, m_server, serverCertificate, authenticationToken, clientNonce, serverNonce, sessionName, clientDescription, endpointUrl, clientCertificate, revisedSessionTimeout, maxResponseMessageSize, m_maxRequestAge, m_maxBrowseContinuationPoints); // get the session id. sessionId = session.Id; // save session. m_sessions.Add(authenticationToken, session); } // raise session related event. RaiseSessionEvent(session, SessionEventReason.Created); // return session. return(session); }
internal UANodeContext GetOrCreateNodeContext(string nodeId, bool lookupAlias, Action <TraceMessage> traceEvent) { NodeId _id = ImportNodeId(nodeId, lookupAlias, traceEvent); return(m_AddressSpaceContext.GetOrCreateNodeContext(_id, this, traceEvent)); }
public override int GetHashCode() => (NodeId.GetHashCode() << 2) ^ Id.GetHashCode();
/// <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); } }
public static T GetOrDefault <T>(this ConcurrentNodeDictionary <T> d, NodeId node) { if (!node.IsValid) { return(default);
/// <summary> /// Collects the fields for the instance node. /// </summary> /// <param name="session">The session.</param> /// <param name="nodeId">The node id.</param> /// <param name="parentPath">The parent path.</param> /// <param name="fields">The event fields.</param> /// <param name="fieldNodeIds">The node id for the declaration of the field.</param> /// <param name="foundNodes">The table of found nodes.</param> private static void CollectFields( Session session, NodeId nodeId, QualifiedNameCollection parentPath, SimpleAttributeOperandCollection fields, List <NodeId> fieldNodeIds, Dictionary <NodeId, QualifiedNameCollection> foundNodes) { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = nodeId; nodeToBrowse.BrowseDirection = BrowseDirection.Forward; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.Aggregates; nodeToBrowse.IncludeSubtypes = true; nodeToBrowse.NodeClassMask = (uint)(NodeClass.Object | NodeClass.Variable); nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; ReferenceDescriptionCollection children = FormUtils.Browse(session, nodeToBrowse, false); if (children == null) { return; } // process the children. for (int ii = 0; ii < children.Count; ii++) { ReferenceDescription child = children[ii]; if (child.NodeId.IsAbsolute) { continue; } // construct browse path. QualifiedNameCollection browsePath = new QualifiedNameCollection(parentPath); browsePath.Add(child.BrowseName); // check if the browse path is already in the list. int index = ContainsPath(fields, browsePath); if (index < 0) { SimpleAttributeOperand field = new SimpleAttributeOperand(); field.TypeDefinitionId = ObjectTypeIds.BaseEventType; field.BrowsePath = browsePath; field.AttributeId = (child.NodeClass == NodeClass.Variable) ? Attributes.Value : Attributes.NodeId; fields.Add(field); fieldNodeIds.Add((NodeId)child.NodeId); } // recusively find all of the children. NodeId targetId = (NodeId)child.NodeId; // need to guard against loops. if (!foundNodes.ContainsKey(targetId)) { foundNodes.Add(targetId, browsePath); CollectFields(session, (NodeId)child.NodeId, browsePath, fields, fieldNodeIds, foundNodes); } } }
/// <summary> /// Returns value of the field name containing the event type. /// </summary> public object GetFieldValue( EventFieldList eventFields, NodeId eventTypeId, IList <QualifiedName> browsePath, uint attributeId) { if (eventFields == null) { return(null); } EventFilter filter = m_filter as EventFilter; if (filter == null) { return(null); } for (int ii = 0; ii < filter.SelectClauses.Count; ii++) { if (ii >= eventFields.EventFields.Count) { return(null); } // check for match. SimpleAttributeOperand clause = filter.SelectClauses[ii]; // attribute id if (clause.AttributeId != attributeId) { continue; } // match null browse path. if (browsePath == null || browsePath.Count == 0) { if (clause.BrowsePath != null && clause.BrowsePath.Count > 0) { continue; } // ignore event type id when matching null browse paths. return(eventFields.EventFields[ii].Value); } // match browse path. // event type id. if (clause.TypeDefinitionId != eventTypeId) { continue; } // match element count. if (clause.BrowsePath.Count != browsePath.Count) { continue; } // check each element. bool match = true; for (int jj = 0; jj < clause.BrowsePath.Count; jj++) { if (clause.BrowsePath[jj] != browsePath[jj]) { match = false; break; } } // check of no match. if (!match) { continue; } // return value. return(eventFields.EventFields[ii].Value); } // no event type in event field list. return(null); }
/// <summary> /// Returns the node ids for a set of relative paths. /// </summary> /// <param name="session">An open session with the server to use.</param> /// <param name="startNodeId">The starting node for the relative paths.</param> /// <param name="namespacesUris">The namespace URIs referenced by the relative paths.</param> /// <param name="relativePaths">The relative paths.</param> /// <returns>A collection of local nodes.</returns> public static List <NodeId> TranslateBrowsePaths( Session session, NodeId startNodeId, NamespaceTable namespacesUris, params string[] relativePaths) { // build the list of browse paths to follow by parsing the relative paths. BrowsePathCollection browsePaths = new BrowsePathCollection(); if (relativePaths != null) { for (int ii = 0; ii < relativePaths.Length; ii++) { BrowsePath browsePath = new BrowsePath(); // The relative paths used indexes in the namespacesUris table. These must be // converted to indexes used by the server. An error occurs if the relative path // refers to a namespaceUri that the server does not recognize. // The relative paths may refer to ReferenceType by their BrowseName. The TypeTree object // allows the parser to look up the server's NodeId for the ReferenceType. browsePath.RelativePath = RelativePath.Parse( relativePaths[ii], session.TypeTree, namespacesUris, session.NamespaceUris); browsePath.StartingNode = startNodeId; browsePaths.Add(browsePath); } } // make the call to the server. ResponseHeader responseHeader = session.TranslateBrowsePathsToNodeIds( null, browsePaths, out BrowsePathResultCollection results, out DiagnosticInfoCollection diagnosticInfos); // ensure that the server returned valid results. Session.ValidateResponse(results, browsePaths); Session.ValidateDiagnosticInfos(diagnosticInfos, browsePaths); // collect the list of node ids found. List <NodeId> nodes = new List <NodeId>(); for (int ii = 0; ii < results.Count; ii++) { // check if the start node actually exists. if (StatusCode.IsBad(results[ii].StatusCode)) { nodes.Add(null); continue; } // an empty list is returned if no node was found. if (results[ii].Targets.Count == 0) { nodes.Add(null); continue; } // Multiple matches are possible, however, the node that matches the type model is the // one we are interested in here. The rest can be ignored. BrowsePathTarget target = results[ii].Targets[0]; if (target.RemainingPathIndex != uint.MaxValue) { nodes.Add(null); continue; } // The targetId is an ExpandedNodeId because it could be node in another server. // The ToNodeId function is used to convert a local NodeId stored in a ExpandedNodeId to a NodeId. nodes.Add(ExpandedNodeId.ToNodeId(target.TargetId, session.NamespaceUris)); } // return whatever was found. return(nodes); }
/// <summary> /// Constructs an event object from a notification. /// </summary> /// <param name="session">The session.</param> /// <param name="monitoredItem">The monitored item that produced the notification.</param> /// <param name="notification">The notification.</param> /// <param name="knownEventTypes">The known event types.</param> /// <param name="eventTypeMappings">Mapping between event types and known event types.</param> /// <returns> /// The event object. Null if the notification is not a valid event type. /// </returns> public static BaseEventState ConstructEvent( Session session, MonitoredItem monitoredItem, EventFieldList notification, Dictionary <NodeId, Type> knownEventTypes, Dictionary <NodeId, NodeId> eventTypeMappings) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); if (eventTypeId == null) { return(null); } // look up the known event type. Type knownType = null; if (eventTypeMappings.TryGetValue(eventTypeId, out NodeId knownTypeId)) { knownType = knownEventTypes[knownTypeId]; } // try again. if (knownType == null) { if (knownEventTypes.TryGetValue(eventTypeId, out knownType)) { knownTypeId = eventTypeId; eventTypeMappings.Add(eventTypeId, eventTypeId); } } // try mapping it to a known type. if (knownType == null) { // browse for the supertypes of the event type. ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); // can't do anything with unknown types. if (supertypes == null) { return(null); } // find the first supertype that matches a known event type. for (int ii = 0; ii < supertypes.Count; ii++) { NodeId superTypeId = (NodeId)supertypes[ii].NodeId; if (knownEventTypes.TryGetValue(superTypeId, out knownType)) { knownTypeId = superTypeId; eventTypeMappings.Add(eventTypeId, superTypeId); } if (knownTypeId != null) { break; } } // can't do anything with unknown types. if (knownTypeId == null) { return(null); } } // construct the event based on the known event type. BaseEventState e = (BaseEventState)Activator.CreateInstance(knownType, new object[] { null }); // get the filter which defines the contents of the notification. EventFilter filter = monitoredItem.Status.Filter as EventFilter; // initialize the event with the values in the notification. e.Update(session.SystemContext, filter.SelectClauses, notification); // save the orginal notification. e.Handle = notification; return(e); }
/// <summary> /// Browses the address space and returns all of the supertypes of the specified type node. /// </summary> /// <param name="session">The session.</param> /// <param name="typeId">The NodeId for a type node in the address space.</param> /// <param name="throwOnError">if set to <c>true</c> a exception will be thrown on an error.</param> /// <returns> /// The references found. Null if an error occurred. /// </returns> public static ReferenceDescriptionCollection BrowseSuperTypes(Session session, NodeId typeId, bool throwOnError) { ReferenceDescriptionCollection supertypes = new ReferenceDescriptionCollection(); try { // find all of the children of the field. BrowseDescription nodeToBrowse = new BrowseDescription(); nodeToBrowse.NodeId = typeId; nodeToBrowse.BrowseDirection = BrowseDirection.Inverse; nodeToBrowse.ReferenceTypeId = ReferenceTypeIds.HasSubtype; nodeToBrowse.IncludeSubtypes = false; // more efficient to use IncludeSubtypes=False when possible. nodeToBrowse.NodeClassMask = 0; // the HasSubtype reference already restricts the targets to Types. nodeToBrowse.ResultMask = (uint)BrowseResultMask.All; ReferenceDescriptionCollection references = Browse(session, nodeToBrowse, throwOnError); while (references != null && references.Count > 0) { // should never be more than one supertype. supertypes.Add(references[0]); // only follow references within this server. if (references[0].NodeId.IsAbsolute) { break; } // get the references for the next level up. nodeToBrowse.NodeId = (NodeId)references[0].NodeId; references = Browse(session, nodeToBrowse, throwOnError); } // return complete list. return(supertypes); } catch (Exception exception) { if (throwOnError) { throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError); } return(null); } }
/// <summary> /// Displays the target of a browse operation in the control. /// </summary> private void Browse(NodeId startId) { if (m_browser == null || NodeId.IsNull(startId)) { Clear(); return; } List <ItemData> variables = new List <ItemData>(); // browse the references from the node and build list of variables. BeginUpdate(); foreach (ReferenceDescription reference in m_browser.Browse(startId)) { Node target = m_session.NodeCache.Find(reference.NodeId) as Node; if (target == null) { continue; } ReferenceTypeNode referenceType = m_session.NodeCache.Find(reference.ReferenceTypeId) as ReferenceTypeNode; Node typeDefinition = null; if ((target.NodeClass & (NodeClass.Variable | NodeClass.Object)) != 0) { typeDefinition = m_session.NodeCache.Find(reference.TypeDefinition) as Node; } else { typeDefinition = m_session.NodeCache.Find(m_session.NodeCache.TypeTree.FindSuperType(target.NodeId)) as Node; } ItemData item = new ItemData(referenceType, !reference.IsForward, target, typeDefinition); AddItem(item, GuiUtils.GetTargetIcon(m_browser.Session, reference), -1); if ((target.NodeClass & (NodeClass.Variable | NodeClass.VariableType)) != 0) { variables.Add(item); } } EndUpdate(); // read the current value for any variables. if (variables.Count > 0) { ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (ItemData item in variables) { ReadValueId valueId = new ReadValueId(); valueId.NodeId = item.Target.NodeId; valueId.AttributeId = Attributes.Value; valueId.IndexRange = null; valueId.DataEncoding = null; nodesToRead.Add(valueId); } DataValueCollection values; DiagnosticInfoCollection diagnosticInfos; m_session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out values, out diagnosticInfos); ClientBase.ValidateResponse(values, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); for (int ii = 0; ii < variables.Count; ii++) { variables[ii].Value = values[ii]; foreach (ListViewItem item in ItemsLV.Items) { if (Object.ReferenceEquals(item.Tag, variables[ii])) { UpdateItem(item, variables[ii]); break; } } } } }
/// <summary> /// Reads the application description from the GDS. /// </summary> private ApplicationDescription Read(NodeId nodeId) { NamespaceTable wellKnownNamespaceUris = new NamespaceTable(); wellKnownNamespaceUris.Append(Namespaces.OpcUaGds); string[] browsePaths = new string[] { "1:ApplicationName", "1:ApplicationType", "1:ApplicationUri", "1:ProductUri", "1:GatewayServerUri", "1:DiscoveryUrls" }; List <NodeId> propertyIds = ClientUtils.TranslateBrowsePaths( ServerCTRL.Session, nodeId, wellKnownNamespaceUris, browsePaths); ReadValueIdCollection nodesToRead = new ReadValueIdCollection(); foreach (NodeId propertyId in propertyIds) { ReadValueId nodeToRead = new ReadValueId(); nodeToRead.NodeId = propertyId; nodeToRead.AttributeId = Attributes.Value; nodesToRead.Add(nodeToRead); } DataValueCollection results = null; DiagnosticInfoCollection diagnosticInfos = null; ServerCTRL.Session.Read( null, 0, TimestampsToReturn.Neither, nodesToRead, out results, out diagnosticInfos); ClientBase.ValidateResponse(results, nodesToRead); ClientBase.ValidateDiagnosticInfos(diagnosticInfos, nodesToRead); ApplicationDescription application = new ApplicationDescription(); application.ApplicationName = results[0].GetValue <LocalizedText>(null); application.ApplicationType = (ApplicationType)results[1].GetValue <int>((int)ApplicationType.Server); application.ApplicationUri = results[2].GetValue <string>(null); application.ProductUri = results[3].GetValue <string>(null); application.GatewayServerUri = results[4].GetValue <string>(null); string[] discoveryUrls = results[5].GetValue <string[]>(null); if (discoveryUrls != null) { application.DiscoveryUrls = new StringCollection(discoveryUrls); } return(application); }
public NodeIdFactory(NodeId firstNodeId) { currentId = firstNodeId.Value; }
public static void CompareExchangeMin <T>(this ConcurrentNodeDictionary <T> map, NodeId node, T comparand) where T : IComparable <T> { if (comparand.IsLessThan(map[node])) { map[node] = comparand; } }
/// <summary> /// Shows a value in control. /// </summary> private void ShowValue(ref int index, ref bool overwrite, object value) { if (value == null) { return; } // show monitored items. MonitoredItem monitoredItem = value as MonitoredItem; if (monitoredItem != null) { m_monitoredItem = monitoredItem; ShowValue(ref index, ref overwrite, monitoredItem.LastValue); return; } // show data changes MonitoredItemNotification datachange = value as MonitoredItemNotification; if (datachange != null) { ShowValue(ref index, ref overwrite, datachange.Value); return; } // show events EventFieldList eventFields = value as EventFieldList; if (eventFields != null) { for (int ii = 0; ii < eventFields.EventFields.Count; ii++) { ShowValue(ref index, ref overwrite, eventFields, ii); } return; } // show extension bodies. ExtensionObject extension = value as ExtensionObject; if (extension != null) { ShowValue(ref index, ref overwrite, extension.Body); return; } // show encodeables. IEncodeable encodeable = value as IEncodeable; if (encodeable != null) { PropertyInfo[] properties = encodeable.GetType().GetProperties(); foreach (PropertyInfo property in properties) { ShowValue(ref index, ref overwrite, encodeable, property); } return; } // show bytes. byte[] bytes = value as byte[]; if (bytes != null) { if (!PromptOnLongList(bytes.Length/16)) { return; } for (int ii = 0; ii < bytes.Length; ii+=16) { ShowValue(ref index, ref overwrite, bytes, ii); } return; } // show arrays Array array = value as Array; if (array != null) { if (!PromptOnLongList(array.Length)) { return; } for (int ii = 0; ii < array.Length; ii++) { ShowValue(ref index, ref overwrite, array, ii); } return; } // show lists IList list = value as IList; if (list != null) { if (!PromptOnLongList(list.Count)) { return; } for (int ii = 0; ii < list.Count; ii++) { ShowValue(ref index, ref overwrite, list, ii); } return; } // show xml elements XmlElement xml = value as XmlElement; if (xml != null) { if (!PromptOnLongList(xml.ChildNodes.Count)) { return; } for (int ii = 0; ii < xml.ChildNodes.Count; ii++) { ShowValue(ref index, ref overwrite, xml, ii); } return; } // show data value. DataValue datavalue = value as DataValue; if (datavalue != null) { ShowValue(ref index, ref overwrite, datavalue, 0); ShowValue(ref index, ref overwrite, datavalue, 1); ShowValue(ref index, ref overwrite, datavalue, 2); ShowValue(ref index, ref overwrite, datavalue, 3); return; } // show node id value. NodeId nodeId = value as NodeId; if (nodeId != null) { ShowValue(ref index, ref overwrite, nodeId, 0); ShowValue(ref index, ref overwrite, nodeId, 1); ShowValue(ref index, ref overwrite, nodeId, 2); return; } // show expanded node id value. ExpandedNodeId expandedNodeId = value as ExpandedNodeId; if (expandedNodeId != null) { ShowValue(ref index, ref overwrite, expandedNodeId, 0); ShowValue(ref index, ref overwrite, expandedNodeId, 1); ShowValue(ref index, ref overwrite, expandedNodeId, 2); ShowValue(ref index, ref overwrite, expandedNodeId, 3); return; } // show qualified name value. QualifiedName qualifiedName = value as QualifiedName; if (qualifiedName != null) { ShowValue(ref index, ref overwrite, qualifiedName, 0); ShowValue(ref index, ref overwrite, qualifiedName, 1); return; } // show qualified name value. LocalizedText localizedText = value as LocalizedText; if (localizedText != null) { ShowValue(ref index, ref overwrite, localizedText, 0); ShowValue(ref index, ref overwrite, localizedText, 1); return; } // show variant. Variant? variant = value as Variant?; if (variant != null) { ShowValue(ref index, ref overwrite, variant.Value.Value); return; } // show unknown types as strings. ShowValue(ref index, ref overwrite, String.Format("{0}", value)); }
/// <inheritdoc/> public IServerSession CreateSession(RequestContextModel context, EndpointDescription endpoint, X509Certificate2 serverCertificate, byte[] clientNonce, X509Certificate2 clientCertificate, double requestedTimeout, out NodeId sessionId, out NodeId authenticationToken, out byte[] serverNonce, out double revisedTimeout) { GatewaySession session = null; lock (_lock) { // check session count. if (_configuration.MaxSessionCount > 0 && _sessions.Count >= _configuration.MaxSessionCount) { throw new ServiceResultException(StatusCodes.BadTooManySessions); } // check for same Nonce in another session if (clientNonce != null) { foreach (var sessionIterator in _sessions.Values) { if (Utils.CompareNonce(sessionIterator.ClientNonce, clientNonce)) { throw new ServiceResultException(StatusCodes.BadNonceInvalid); } } } // Create session sessionId = new NodeId(Guid.NewGuid()); authenticationToken = new NodeId(Utils.Nonce.CreateNonce(kDefaultNonceLength)); var nonceLength = (uint)_configuration.NonceLength; serverNonce = Utils.Nonce.CreateNonce(nonceLength == 0 ? kDefaultNonceLength : nonceLength); var maxSessionTimeout = _configuration.MaxSessionTimeout.TotalMilliseconds; var minSessionTimeout = _configuration.MinSessionTimeout.TotalMilliseconds; if (requestedTimeout > maxSessionTimeout) { revisedTimeout = maxSessionTimeout; } else if (requestedTimeout < minSessionTimeout) { revisedTimeout = minSessionTimeout; } else { revisedTimeout = requestedTimeout; } // Add session to list session = new GatewaySession(this, context, sessionId, endpoint, clientCertificate, clientNonce, serverCertificate, serverNonce, TimeSpan.FromMilliseconds(revisedTimeout), _configuration.MaxRequestAge, _validateUser); if (!_sessions.TryAdd(authenticationToken, session)) { throw new ServiceResultException(StatusCodes.BadInternalError); } } _sessionCreated?.Invoke(session, null); return(session); }
/// <summary> /// Converts a remote NodeId to a local NodeId. /// </summary> public NodeId ToLocalId(NodeId value) { return(ToId(value, m_localNamespaceIndexes)); }
/// <summary> /// Returns the id of the default data type node for the instance. /// </summary> protected override NodeId GetDefaultDataTypeId(NamespaceTable namespaceUris) { return(NodeId.Create(DataTypes.BaseDataType, Opc.Ua.Namespaces.OpcUa, namespaceUris)); }
/// <summary> /// Validate session less request /// </summary> /// <param name="authenticationToken"></param> /// <param name="requestType"></param> /// <returns></returns> protected virtual IUserIdentity ValidateSessionLessRequest(NodeId authenticationToken, RequestType requestType) { // Not supported! throw new ServiceResultException(StatusCodes.BadSessionIdInvalid); }
/// <summary> /// Converts a local NodeId to a remote NodeId. /// </summary> public NodeId ToRemoteId(NodeId value) { return(ToId(value, m_remoteNamespaceIndexes)); }
/// <summary> /// Imports a node from the set. /// </summary> private NodeState Import(ISystemContext context, UANode node) { NodeState importedNode = null; NodeClass nodeClass = NodeClass.Unspecified; if (node is UAObject) { nodeClass = NodeClass.Object; } else if (node is UAVariable) { nodeClass = NodeClass.Variable; } else if (node is UAMethod) { nodeClass = NodeClass.Method; } else if (node is UAObjectType) { nodeClass = NodeClass.ObjectType; } else if (node is UAVariableType) { nodeClass = NodeClass.VariableType; } else if (node is UADataType) { nodeClass = NodeClass.DataType; } else if (node is UAReferenceType) { nodeClass = NodeClass.ReferenceType; } else if (node is UAView) { nodeClass = NodeClass.View; } switch (nodeClass) { case NodeClass.Object: { UAObject o = (UAObject)node; BaseObjectState value = new BaseObjectState(null); value.EventNotifier = o.EventNotifier; importedNode = value; break; } case NodeClass.Variable: { UAVariable o = (UAVariable)node; NodeId typeDefinitionId = null; if (node.References != null) { for (int ii = 0; ii < node.References.Length; ii++) { Opc.Ua.NodeId referenceTypeId = ImportNodeId(node.References[ii].ReferenceType, context.NamespaceUris, true); bool isInverse = !node.References[ii].IsForward; Opc.Ua.ExpandedNodeId targetId = ImportExpandedNodeId(node.References[ii].Value, context.NamespaceUris, context.ServerUris); if (referenceTypeId == ReferenceTypeIds.HasTypeDefinition && !isInverse) { typeDefinitionId = Opc.Ua.ExpandedNodeId.ToNodeId(targetId, context.NamespaceUris); break; } } } BaseVariableState value = null; if (typeDefinitionId == Opc.Ua.VariableTypeIds.PropertyType) { value = new PropertyState(null); } else { value = new BaseDataVariableState(null); } value.DataType = ImportNodeId(o.DataType, context.NamespaceUris, true); value.ValueRank = o.ValueRank; value.ArrayDimensions = ImportArrayDimensions(o.ArrayDimensions); value.AccessLevel = o.AccessLevel; value.UserAccessLevel = o.UserAccessLevel; value.MinimumSamplingInterval = o.MinimumSamplingInterval; value.Historizing = o.Historizing; if (o.Value != null) { XmlDecoder decoder = CreateDecoder(context, o.Value); TypeInfo typeInfo = null; value.Value = decoder.ReadVariantContents(out typeInfo); decoder.Close(); } importedNode = value; break; } case NodeClass.Method: { UAMethod o = (UAMethod)node; MethodState value = new MethodState(null); value.Executable = o.Executable; value.UserExecutable = o.UserExecutable; importedNode = value; break; } case NodeClass.View: { UAView o = (UAView)node; ViewState value = new ViewState(); value.ContainsNoLoops = o.ContainsNoLoops; importedNode = value; break; } case NodeClass.ObjectType: { UAObjectType o = (UAObjectType)node; BaseObjectTypeState value = new BaseObjectTypeState(); value.IsAbstract = o.IsAbstract; importedNode = value; break; } case NodeClass.VariableType: { UAVariableType o = (UAVariableType)node; BaseVariableTypeState value = new BaseDataVariableTypeState(); value.IsAbstract = o.IsAbstract; value.DataType = ImportNodeId(o.DataType, context.NamespaceUris, true); value.ValueRank = o.ValueRank; value.ArrayDimensions = ImportArrayDimensions(o.ArrayDimensions); if (o.Value != null) { XmlDecoder decoder = CreateDecoder(context, o.Value); TypeInfo typeInfo = null; value.Value = decoder.ReadVariantContents(out typeInfo); decoder.Close(); } importedNode = value; break; } case NodeClass.DataType: { UADataType o = (UADataType)node; DataTypeState value = new DataTypeState(); value.IsAbstract = o.IsAbstract; value.Definition = Import(o.Definition, context.NamespaceUris); importedNode = value; break; } case NodeClass.ReferenceType: { UAReferenceType o = (UAReferenceType)node; ReferenceTypeState value = new ReferenceTypeState(); value.IsAbstract = o.IsAbstract; value.InverseName = Import(o.InverseName); value.Symmetric = o.Symmetric; importedNode = value; break; } } importedNode.NodeId = ImportNodeId(node.NodeId, context.NamespaceUris, false); importedNode.BrowseName = ImportQualifiedName(node.BrowseName, context.NamespaceUris); importedNode.DisplayName = Import(node.DisplayName); importedNode.Description = Import(node.Description); importedNode.WriteMask = (AttributeWriteMask)node.WriteMask; importedNode.UserWriteMask = (AttributeWriteMask)node.UserWriteMask; if (!String.IsNullOrEmpty(node.SymbolicName)) { importedNode.SymbolicName = node.SymbolicName; } if (node.References != null) { BaseInstanceState instance = importedNode as BaseInstanceState; BaseTypeState type = importedNode as BaseTypeState; for (int ii = 0; ii < node.References.Length; ii++) { Opc.Ua.NodeId referenceTypeId = ImportNodeId(node.References[ii].ReferenceType, context.NamespaceUris, true); bool isInverse = !node.References[ii].IsForward; Opc.Ua.ExpandedNodeId targetId = ImportExpandedNodeId(node.References[ii].Value, context.NamespaceUris, context.ServerUris); if (instance != null) { if (referenceTypeId == ReferenceTypeIds.HasModellingRule && !isInverse) { instance.ModellingRuleId = Opc.Ua.ExpandedNodeId.ToNodeId(targetId, context.NamespaceUris); continue; } if (referenceTypeId == ReferenceTypeIds.HasTypeDefinition && !isInverse) { instance.TypeDefinitionId = Opc.Ua.ExpandedNodeId.ToNodeId(targetId, context.NamespaceUris); continue; } } if (type != null) { if (referenceTypeId == ReferenceTypeIds.HasSubtype && isInverse) { type.SuperTypeId = Opc.Ua.ExpandedNodeId.ToNodeId(targetId, context.NamespaceUris); continue; } } importedNode.AddReference(referenceTypeId, isInverse, targetId); } } return(importedNode); }
/// <summary> /// Returns the id of the default type definition node for the instance. /// </summary> /// <param name="namespaceUris">The namespace table containing the namespace URIs.</param> /// <returns>The node id.</returns> protected override NodeId GetDefaultTypeDefinitionId(NamespaceTable namespaceUris) { return(NodeId.Create(ITG3200.ObjectTypes.ITG3200Type, ITG3200.Namespaces.ITG3200, namespaceUris)); }
/// <summary> /// Activates an existing session /// </summary> public virtual bool ActivateSession( OperationContext context, NodeId authenticationToken, SignatureData clientSignature, List <SoftwareCertificate> clientSoftwareCertificates, ExtensionObject userIdentityToken, SignatureData userTokenSignature, StringCollection localeIds, out byte[] serverNonce) { serverNonce = null; Session session = null; UserIdentityToken newIdentity = null; UserTokenPolicy userTokenPolicy = null; lock (m_lock) { // find session. if (!m_sessions.TryGetValue(authenticationToken, out session)) { throw new ServiceResultException(StatusCodes.BadSessionIdInvalid); } // check if session timeout has expired. if (session.HasExpired) { m_server.CloseSession(null, session.Id, false); throw new ServiceResultException(StatusCodes.BadSessionClosed); } // create new server nonce. serverNonce = Utils.Nonce.CreateNonce((uint)m_minNonceLength); // validate before activation. session.ValidateBeforeActivate( context, clientSignature, clientSoftwareCertificates, userIdentityToken, userTokenSignature, localeIds, serverNonce, out newIdentity, out userTokenPolicy); } IUserIdentity identity = null; IUserIdentity effectiveIdentity = null; ServiceResult error = null; try { // check if the application has a callback which validates the identity tokens. lock (m_eventLock) { if (m_ImpersonateUser != null) { ImpersonateEventArgs args = new ImpersonateEventArgs(newIdentity, userTokenPolicy); m_ImpersonateUser(session, args); if (ServiceResult.IsBad(args.IdentityValidationError)) { error = args.IdentityValidationError; } else { identity = args.Identity; effectiveIdentity = args.EffectiveIdentity; } } } // parse the token manually if the identity is not provided. if (identity == null) { identity = new UserIdentity(newIdentity); } // use the identity as the effectiveIdentity if not provided. if (effectiveIdentity == null) { effectiveIdentity = identity; } } catch (Exception e) { if (e is ServiceResultException) { throw; } throw ServiceResultException.Create( StatusCodes.BadIdentityTokenInvalid, e, "Could not validate user identity token: {0}", newIdentity); } // check for validation error. if (ServiceResult.IsBad(error)) { throw new ServiceResultException(error); } // activate session. bool contextChanged = session.Activate( context, clientSoftwareCertificates, newIdentity, identity, effectiveIdentity, localeIds, serverNonce); // raise session related event. if (contextChanged) { RaiseSessionEvent(session, SessionEventReason.Activated); } // indicates that the identity context for the session has changed. return(contextChanged); }
/// <summary> /// Returns true if the dictionary contains the data type description; /// </summary> public bool Contains(NodeId descriptionId) { return(DataTypes.ContainsKey(descriptionId)); }
/// <summary> /// Closes the specified session. /// </summary> /// <param name="context">The context.</param> /// <param name="sessionId">The session identifier.</param> /// <param name="deleteSubscriptions">if set to <c>true</c> subscriptions are to be deleted.</param> public void CloseSession(OperationContext context, NodeId sessionId, bool deleteSubscriptions) { m_nodeManager.SessionClosing(context, sessionId, deleteSubscriptions); m_subscriptionManager.SessionClosing(context, sessionId, deleteSubscriptions); m_sessionManager.CloseSession(sessionId); }
public virtual void TestUpdatedNodes() { int runCount = 0; MRApp app = new TestMRApp.MRAppWithHistory(this, 2, 2, false, this.GetType().FullName , true, ++runCount); Configuration conf = new Configuration(); // after half of the map completion, reduce will start conf.SetFloat(MRJobConfig.CompletedMapsForReduceSlowstart, 0.5f); // uberization forces full slowstart (1.0), so disable that conf.SetBoolean(MRJobConfig.JobUbertaskEnable, false); Org.Apache.Hadoop.Mapreduce.V2.App.Job.Job job = app.Submit(conf); app.WaitForState(job, JobState.Running); NUnit.Framework.Assert.AreEqual("Num tasks not correct", 4, job.GetTasks().Count); IEnumerator <Task> it = job.GetTasks().Values.GetEnumerator(); Task mapTask1 = it.Next(); Task mapTask2 = it.Next(); // all maps must be running app.WaitForState(mapTask1, TaskState.Running); app.WaitForState(mapTask2, TaskState.Running); TaskAttempt task1Attempt = mapTask1.GetAttempts().Values.GetEnumerator().Next(); TaskAttempt task2Attempt = mapTask2.GetAttempts().Values.GetEnumerator().Next(); NodeId node1 = task1Attempt.GetNodeId(); NodeId node2 = task2Attempt.GetNodeId(); NUnit.Framework.Assert.AreEqual(node1, node2); // send the done signal to the task app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task1Attempt.GetID (), TaskAttemptEventType.TaDone)); app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task2Attempt.GetID (), TaskAttemptEventType.TaDone)); // all maps must be succeeded app.WaitForState(mapTask1, TaskState.Succeeded); app.WaitForState(mapTask2, TaskState.Succeeded); TaskAttemptCompletionEvent[] events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 2 completion events for success", 2, events .Length); // send updated nodes info AList <NodeReport> updatedNodes = new AList <NodeReport>(); NodeReport nr = RecordFactoryProvider.GetRecordFactory(null).NewRecordInstance <NodeReport >(); nr.SetNodeId(node1); nr.SetNodeState(NodeState.Unhealthy); updatedNodes.AddItem(nr); app.GetContext().GetEventHandler().Handle(new JobUpdatedNodesEvent(job.GetID(), updatedNodes )); app.WaitForState(task1Attempt, TaskAttemptState.Killed); app.WaitForState(task2Attempt, TaskAttemptState.Killed); events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 2 more completion events for killed", 4, events.Length); // all maps must be back to running app.WaitForState(mapTask1, TaskState.Running); app.WaitForState(mapTask2, TaskState.Running); IEnumerator <TaskAttempt> itr = mapTask1.GetAttempts().Values.GetEnumerator(); itr.Next(); task1Attempt = itr.Next(); // send the done signal to the task app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task1Attempt.GetID (), TaskAttemptEventType.TaDone)); // map1 must be succeeded. map2 must be running app.WaitForState(mapTask1, TaskState.Succeeded); app.WaitForState(mapTask2, TaskState.Running); events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 1 more completion events for success", 5, events.Length); // Crash the app again. app.Stop(); // rerun // in rerun the 1st map will be recovered from previous run app = new TestMRApp.MRAppWithHistory(this, 2, 2, false, this.GetType().FullName, false, ++runCount); conf = new Configuration(); conf.SetBoolean(MRJobConfig.MrAmJobRecoveryEnable, true); conf.SetBoolean(MRJobConfig.JobUbertaskEnable, false); job = app.Submit(conf); app.WaitForState(job, JobState.Running); NUnit.Framework.Assert.AreEqual("No of tasks not correct", 4, job.GetTasks().Count ); it = job.GetTasks().Values.GetEnumerator(); mapTask1 = it.Next(); mapTask2 = it.Next(); Task reduceTask1 = it.Next(); Task reduceTask2 = it.Next(); // map 1 will be recovered, no need to send done app.WaitForState(mapTask1, TaskState.Succeeded); app.WaitForState(mapTask2, TaskState.Running); events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 2 completion events for killed & success of map1" , 2, events.Length); task2Attempt = mapTask2.GetAttempts().Values.GetEnumerator().Next(); app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task2Attempt.GetID (), TaskAttemptEventType.TaDone)); app.WaitForState(mapTask2, TaskState.Succeeded); events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 1 more completion events for success", 3, events.Length); app.WaitForState(reduceTask1, TaskState.Running); app.WaitForState(reduceTask2, TaskState.Running); TaskAttempt task3Attempt = reduceTask1.GetAttempts().Values.GetEnumerator().Next( ); app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task3Attempt.GetID (), TaskAttemptEventType.TaDone)); app.WaitForState(reduceTask1, TaskState.Succeeded); app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task3Attempt.GetID (), TaskAttemptEventType.TaKill)); app.WaitForState(reduceTask1, TaskState.Succeeded); TaskAttempt task4Attempt = reduceTask2.GetAttempts().Values.GetEnumerator().Next( ); app.GetContext().GetEventHandler().Handle(new TaskAttemptEvent(task4Attempt.GetID (), TaskAttemptEventType.TaDone)); app.WaitForState(reduceTask2, TaskState.Succeeded); events = job.GetTaskAttemptCompletionEvents(0, 100); NUnit.Framework.Assert.AreEqual("Expecting 2 more completion events for reduce success" , 5, events.Length); // job succeeds app.WaitForState(job, JobState.Succeeded); }
/// <summary> /// Gets the display text for the specified attribute. /// </summary> /// <param name="session">The currently active session.</param> /// <param name="attributeId">The id of the attribute.</param> /// <param name="value">The value of the attribute.</param> /// <returns>The attribute formatted as a string.</returns> public static string GetAttributeDisplayText(Session session, uint attributeId, Variant value) { if (value == Variant.Null) { return(string.Empty); } switch (attributeId) { case Attributes.AccessLevel: case Attributes.UserAccessLevel: { byte?field = value.Value as byte?; if (field != null) { return(GetAccessLevelDisplayText(field.Value)); } break; } case Attributes.EventNotifier: { byte?field = value.Value as byte?; if (field != null) { return(GetEventNotifierDisplayText(field.Value)); } break; } case Attributes.DataType: { return(session.NodeCache.GetDisplayText(value.Value as NodeId)); } case Attributes.ValueRank: { int?field = value.Value as int?; if (field != null) { return(GetValueRankDisplayText(field.Value)); } break; } case Attributes.NodeClass: { int?field = value.Value as int?; if (field != null) { return(((NodeClass)field.Value).ToString()); } break; } case Attributes.NodeId: { NodeId field = value.Value as NodeId; if (!NodeId.IsNull(field)) { return(field.ToString()); } return("Null"); } } // check for byte strings. if (value.Value is byte[]) { return(Utils.ToHexString(value.Value as byte[])); } // use default format. return(value.ToString()); }
public abstract void SetNodeId(NodeId nodeId);