Ejemplo n.º 1
0
        /// <summary cref="GetRandom(Type)" />
        public ExtensionObject GetRandomExtensionObject()
        {
            NodeId typeId = GetRandomNodeId();

            if (NodeId.IsNull(typeId))
            {
                return(new ExtensionObject());
            }
            object body = null;

            if (m_random.NextInt32(1) != 0)
            {
                body = GetRandomByteString();
            }
            else
            {
                body = GetRandomXmlElement();
            }

            return(new ExtensionObject(typeId, body));
        }
Ejemplo n.º 2
0
 /// <summary>
 /// Get browsable references
 /// </summary>
 /// <returns></returns>
 private IEnumerable <IReference> GetReferences()
 {
     if (!NodeId.IsNull(TypeDefinitionId))
     {
         yield return(new NodeStateReference(
                          ReferenceTypeIds.HasTypeDefinition, false, TypeDefinitionId));
     }
     if (!NodeId.IsNull(ModellingRuleId))
     {
         yield return(new NodeStateReference(
                          ReferenceTypeIds.HasModellingRule, false, ModellingRuleId));
     }
     if (Parent != null)
     {
         if (!NodeId.IsNull(ReferenceTypeId))
         {
             yield return(new NodeStateReference(
                              ReferenceTypeId, true, Parent.NodeId));
         }
     }
 }
Ejemplo n.º 3
0
        protected string GetNodeIdString(
            NodeId nodeId
            )
        {
            if (NodeId.IsNull(nodeId))
            {
                return(null);
            }

            if (nodeId.IdType != IdType.String || NamespaceIndex != nodeId.NamespaceIndex)
            {
                throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
            }

            string id = nodeId.Identifier as string;

            if (id == null)
            {
                throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
            }
            return(id);
        }
Ejemplo n.º 4
0
        protected Guid GetNodeIdGuid(
            NodeId nodeId
            )
        {
            if (NodeId.IsNull(nodeId))
            {
                throw new ArgumentNullException(nameof(nodeId));
            }

            if (nodeId.IdType != IdType.Guid || NamespaceIndex != nodeId.NamespaceIndex)
            {
                throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
            }

            Guid?id = nodeId.Identifier as Guid?;

            if (id == null)
            {
                throw new ServiceResultException(StatusCodes.BadNodeIdUnknown);
            }
            return((Guid)id);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Creates a new aggregate calculator.
        /// </summary>
        /// <param name="aggregateId">The id of the aggregate function.</param>
        /// <param name="startTime">When to start processing.</param>
        /// <param name="endTime">When to stop processing.</param>
        /// <param name="processingInterval">The processing interval.</param>
        /// <param name="stepped">Whether stepped interpolation should be used.</param>
        /// <param name="configuration">The configuaration to use.</param>
        /// <returns></returns>
        public IAggregateCalculator CreateCalculator(
            NodeId aggregateId,
            DateTime startTime,
            DateTime endTime,
            double processingInterval,
            bool stepped,
            AggregateConfiguration configuration)
        {
            if (NodeId.IsNull(aggregateId))
            {
                return(null);
            }

            AggregatorFactory factory = null;

            lock (m_lock)
            {
                if (!m_factories.TryGetValue(aggregateId, out factory))
                {
                    return(null);
                }
            }

            if (configuration.UseServerCapabilitiesDefaults)
            {
                // ensure the configuration is initialized
                configuration = GetDefaultConfiguration(null);
            }

            IAggregateCalculator calculator = factory(aggregateId, startTime, endTime, processingInterval, stepped, configuration);

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

            return(calculator);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Initializes the control with a root and a set of hierarchial reference types to follow.
        /// </summary>
        /// <param name="session">The session.</param>
        /// <param name="rootId">The root of the hierarchy to browse.</param>
        /// <param name="referenceTypeIds">The reference types to follow.</param>
        public void Initialize(
            Session session,
            NodeId rootId,
            params NodeId[] referenceTypeIds)
        {
            // set default root.
            if (NodeId.IsNull(rootId))
            {
                rootId = Opc.Ua.ObjectIds.ObjectsFolder;
            }

            // set default reference type.
            if (referenceTypeIds == null)
            {
                referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.HierarchicalReferences };
            }

            m_rootId           = rootId;
            m_referenceTypeIds = referenceTypeIds;

            // save session.
            ChangeSession(session, true);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Convert an expanded node id to a node id.
        /// </summary>
        /// <param name="nodeId"></param>
        /// <param name="namespaces"></param>
        /// <returns></returns>
        public static NodeId ToNodeId(this ExpandedNodeId nodeId,
                                      NamespaceTable namespaces)
        {
            if (NodeId.IsNull(nodeId))
            {
                return(NodeId.Null);
            }
            if (nodeId.NamespaceIndex > 0 && namespaces == null)
            {
                throw new ArgumentNullException(nameof(namespaces));
            }
            int index = nodeId.NamespaceIndex;

            if (!string.IsNullOrEmpty(nodeId.NamespaceUri))
            {
                index = namespaces.GetIndex(nodeId.NamespaceUri);
                if (index < 0)
                {
                    throw new IndexOutOfRangeException($"Namespace '{nodeId.NamespaceUri}' was not found in NamespaceTable.");
                }
            }
            return(new NodeId(nodeId.Identifier, (ushort)index));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Creates a new aggregate calculator.
        /// </summary>
        /// <param name="aggregateId">The id of the aggregate function.</param>
        /// <param name="startTime">When to start processing.</param>
        /// <param name="endTime">When to stop processing.</param>
        /// <param name="processingInterval">The processing interval.</param>
        /// <param name="configuration">The configuaration to use.</param>
        /// <returns></returns>
        public IAggregateCalculator CreateCalculator(
            NodeId aggregateId,
            DateTime startTime,
            DateTime endTime,
            double processingInterval,
            AggregateConfiguration configuration)
        {
            if (NodeId.IsNull(aggregateId))
            {
                return(null);
            }

            AggregatorFactory factory = null;

            lock (m_lock)
            {
                if (!m_factories.TryGetValue(aggregateId, out factory))
                {
                    return(null);
                }
            }

            AggregateCalculatorImpl calculator = factory();

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

            calculator.StartTime          = startTime;
            calculator.EndTime            = endTime;
            calculator.ProcessingInterval = processingInterval;
            calculator.Configuration      = configuration;
            calculator.SteppedVariable    = configuration.UseSlopedExtrapolation;

            return(calculator);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Prompts the user to select a node.
        /// </summary>
        public ReferenceDescription ShowDialog(
            Session session,
            NodeId rootId,
            ViewDescription view,
            string caption,
            params NodeId[] referenceTypeIds)
        {
            // set the caption.
            if (!String.IsNullOrEmpty(caption))
            {
                this.Text = caption;
            }

            // set default root.
            if (NodeId.IsNull(rootId))
            {
                rootId = Opc.Ua.ObjectIds.ObjectsFolder;
            }

            // set default reference type.
            if (referenceTypeIds == null)
            {
                referenceTypeIds = new NodeId[] { Opc.Ua.ReferenceTypeIds.HierarchicalReferences };
            }

            // initialize the control.
            BrowseCTRL.Initialize(session, rootId, referenceTypeIds);
            BrowseCTRL.View = view;

            // display the dialog.
            if (ShowDialog() != DialogResult.OK)
            {
                return(null);
            }

            return(BrowseCTRL.SelectedNode);
        }
        /// <summary>
        /// This method compares two NodeId values.
        /// </summary>
        /// <param name="value1">First Value.</param>
        /// <param name="value2">Second Value.</param>
        /// <returns>True in case of equal values.
        /// False or ServiceResultException in case of unequal values.</returns>
        public bool CompareNodeId(NodeId value1, NodeId value2)
        {
            if (NodeId.IsNull(value1) && NodeId.IsNull(value2))
            {
                return(true);
            }

            if (value1 == null || value2 == null)
            {
                if (value1 != value2)
                {
                    return(ReportError(value1, value2));
                }

                return(true);
            }

            if (value1 != value2)
            {
                return(ReportError(value1, value2));
            }

            return(true);
        }
Ejemplo n.º 11
0
        private void ChangeViewBTN_Click(object sender, EventArgs e)
        {
            try
            {
                ViewDescription view = null;

                ReferenceDescription reference = ViewCB.SelectedItem as ReferenceDescription;

                if (reference != null && !NodeId.IsNull(reference.NodeId))
                {
                    view             = new ViewDescription();
                    view.ViewId      = ExpandedNodeId.ToNodeId(reference.NodeId, m_session.NamespaceUris);
                    view.ViewVersion = 0;
                    view.Timestamp   = DateTime.MinValue;
                }

                BrowseCTRL.View = view;
                BrowseCTRL.RefreshSelection();
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
        public override NodeId RegisterApplication(
            ApplicationRecordDataType application
            )
        {
            NodeId appNodeId = base.RegisterApplication(application);

            if (NodeId.IsNull(appNodeId))
            {
                appNodeId = new NodeId(Guid.NewGuid(), NamespaceIndex);
            }
            Guid   applicationId = GetNodeIdGuid(appNodeId);
            string capabilities  = base.ServerCapabilities(application);

            lock (Lock)
            {
                Application record = null;

                if (applicationId != Guid.Empty)
                {
                    var results = from ii in Applications
                                  where ii.ApplicationId == applicationId
                                  select ii;

                    record = results.SingleOrDefault();

                    if (record != null)
                    {
                        var endpoints = (from ii in ServerEndpoints
                                         where ii.ApplicationId == record.ApplicationId
                                         select ii).ToList <ServerEndpoint>();

                        foreach (var endpoint in endpoints)
                        {
                            ServerEndpoints.Remove(endpoint);
                        }

                        var names = (from ii in ApplicationNames
                                     where ii.ApplicationId == record.ApplicationId
                                     select ii).ToList <ApplicationName>();

                        foreach (var name in names)
                        {
                            ApplicationNames.Remove(name);
                        }

                        SaveChanges();
                    }
                }

                bool isNew = false;

                if (record == null)
                {
                    applicationId = Guid.NewGuid();
                    record        = new Application()
                    {
                        ApplicationId = applicationId,
                        ID            = 0
                    };
                    isNew = true;
                }

                record.ApplicationUri     = application.ApplicationUri;
                record.ApplicationName    = application.ApplicationNames[0].Text;
                record.ApplicationType    = (int)application.ApplicationType;
                record.ProductUri         = application.ProductUri;
                record.ServerCapabilities = capabilities;

                if (isNew)
                {
                    Applications.Add(record);
                }

                SaveChanges();

                if (application.DiscoveryUrls != null)
                {
                    foreach (var discoveryUrl in application.DiscoveryUrls)
                    {
                        ServerEndpoints.Add(
                            new ServerEndpoint()
                        {
                            ApplicationId = record.ApplicationId,
                            DiscoveryUrl  = discoveryUrl
                        });
                    }
                }

                if (application.ApplicationNames != null && application.ApplicationNames.Count > 0)
                {
                    foreach (var applicationName in application.ApplicationNames)
                    {
                        ApplicationNames.Add(new ApplicationName()
                        {
                            ApplicationId = record.ApplicationId,
                            Locale        = applicationName.Locale,
                            Text          = applicationName.Text
                        });
                    }
                }

                SaveChanges();

                return(new NodeId(applicationId, NamespaceIndex));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Exports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.Export.DataTypeDefinition Export(
            DataTypeState dataType,
            ExtensionObject source,
            NamespaceTable namespaceUris,
            bool outputRedundantNames)
        {
            if (source == null || source.Body == null)
            {
                return(null);
            }

            DataTypeDefinition definition = new DataTypeDefinition();

            if (outputRedundantNames || dataType.BrowseName != null)
            {
                definition.Name = Export(dataType.BrowseName, namespaceUris);
            }

            if (dataType.BrowseName.Name != dataType.SymbolicName)
            {
                definition.SymbolicName = dataType.SymbolicName;
            }

            switch (dataType.DataTypeModifier)
            {
            case DataTypeModifier.Union: { definition.IsUnion = true; break; }

            case DataTypeModifier.OptionSet: { definition.IsOptionSet = true; break; }
            }

            StructureDefinition structureDefinition = source.Body as StructureDefinition;

            if (structureDefinition != null)
            {
                if (structureDefinition.StructureType == StructureType.Union)
                {
                    definition.IsUnion = true;
                }

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

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

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

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

                        output.ValueRank = field.ValueRank;

                        fields.Add(output);
                    }

                    definition.Field = fields.ToArray();
                }
            }

            EnumDefinition enumDefinition = source.Body as EnumDefinition;

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

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

                        output.Name        = field.Name;
                        output.DisplayName = Export(new Opc.Ua.LocalizedText[] { field.Name });
                        output.Description = Export(new Opc.Ua.LocalizedText[] { field.Description });
                        output.ValueRank   = ValueRanks.Scalar;
                        output.Value       = (int)field.Value;

                        fields.Add(output);
                    }

                    definition.Field = fields.ToArray();
                }
            }

            return(definition);
        }
Ejemplo n.º 14
0
        /// <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);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Collects the fields for the instance node.
        /// </summary>
        private static void CollectInstanceDeclarations(
            Session session,
            NodeId typeId,
            InstanceDeclaration parent,
            List <InstanceDeclaration> instances,
            IDictionary <string, InstanceDeclaration> map)
        {
            // find the children.
            BrowseDescription nodeToBrowse = new BrowseDescription();

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

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

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

            if (references == null)
            {
                return;
            }

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

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

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

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

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

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

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

                child.BrowsePath.Add(reference.BrowseName);

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

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

                map[child.BrowsePathDisplayText] = child;

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

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

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

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

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

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

            // recusively collect instance declarations for the tree below.
            for (int ii = 0; ii < children.Count; ii++)
            {
                if (!NodeId.IsNull(children[ii].ModellingRule))
                {
                    instances.Add(children[ii]);
                    CollectInstanceDeclarations(session, typeId, children[ii], instances, map);
                }
            }
        }
Ejemplo n.º 16
0
        /// <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");
            }

            case Attributes.DataTypeDefinition:
            {
                ExtensionObject field = value.Value as ExtensionObject;
                if (field != null)
                {
                    return(field.ToString());
                }
                break;
            }
            }

            // check for byte strings.
            if (value.Value is byte[])
            {
                return(Utils.ToHexString(value.Value as byte[]));
            }

            // use default format.
            return(value.ToString());
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Finds the targets for the specified reference.
        /// </summary>
        private static void UpdateInstanceDescriptions(Session session, List <InstanceDeclaration> instances, bool throwOnError)
        {
            try
            {
                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

                for (int ii = 0; ii < instances.Count; ii++)
                {
                    ReadValueId nodeToRead = new ReadValueId();
                    nodeToRead.NodeId      = instances[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.Description;
                    nodesToRead.Add(nodeToRead);

                    nodeToRead             = new ReadValueId();
                    nodeToRead.NodeId      = instances[ii].NodeId;
                    nodeToRead.AttributeId = Attributes.DataType;
                    nodesToRead.Add(nodeToRead);

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

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

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

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

                // update the instances.
                for (int ii = 0; ii < nodesToRead.Count; ii += 3)
                {
                    InstanceDeclaration instance = instances[ii / 3];

                    instance.Description = results[ii].GetValue <LocalizedText>(LocalizedText.Null).Text;
                    instance.DataType    = results[ii + 1].GetValue <NodeId>(NodeId.Null);
                    instance.ValueRank   = results[ii + 2].GetValue <int>(ValueRanks.Any);

                    if (!NodeId.IsNull(instance.DataType))
                    {
                        instance.BuiltInType         = DataTypes.GetBuiltInType(instance.DataType, session.TypeTree);
                        instance.DataTypeDisplayText = session.NodeCache.GetDisplayText(instance.DataType);

                        if (instance.ValueRank >= 0)
                        {
                            instance.DataTypeDisplayText += "[]";
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                if (throwOnError)
                {
                    throw new ServiceResultException(exception, StatusCodes.BadUnexpectedError);
                }
            }
        }
Ejemplo n.º 18
0
        private void BrowseCTRL_NodeSelected(object sender, EventArgs e)
        {
            try
            {
                // disable ok button if selection is not valid.
                OkBTN.IsEnabled = false;

                ReferenceDescription reference = sender as ReferenceDescription;

                if (reference == null)
                {
                    return;
                }

                if (NodeId.IsNull(reference.NodeId))
                {
                    return;
                }

                // set the display name.
                DisplayNameTB.Text       = reference.ToString();
                NodeClassCB.SelectedItem = (NodeClass)reference.NodeClass;

                // set identifier type.
                IdentifierTypeCB.SelectedItem = reference.NodeId.IdType;

                // set namespace uri.
                if (!String.IsNullOrEmpty(reference.NodeId.NamespaceUri))
                {
                    NamespaceUriCB.SelectedIndex = -1;
                    NamespaceUriCB.SelectedValue = reference.NodeId.NamespaceUri;
                }
                else
                {
                    if (reference.NodeId.NamespaceIndex < NamespaceUriCB.Items.Count)
                    {
                        NamespaceUriCB.SelectedIndex = (int)reference.NodeId.NamespaceIndex;
                    }
                    else
                    {
                        NamespaceUriCB.SelectedIndex = -1;
                        NamespaceUriCB.SelectedValue = String.Empty;
                    }
                }

                // set identifier.
                switch (reference.NodeId.IdType)
                {
                case IdType.Opaque:
                {
                    NodeIdentifierTB.Text = Convert.ToBase64String((byte[])reference.NodeId.Identifier);
                    break;
                }

                default:
                {
                    NodeIdentifierTB.Text = Utils.Format("{0}", reference.NodeId.Identifier);
                    break;
                }
                }

                // selection valid - enable ok.
                OkBTN.IsEnabled = true;
                m_reference     = reference;
            }
            catch (Exception exception)
            {
                GuiUtils.HandleException(String.Empty, GuiUtils.CallerName(), exception);
            }
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Updates the application after connecting to or disconnecting from the server.
        /// </summary>
        private void Server_ConnectComplete(object sender, EventArgs e)
        {
            try
            {
                m_session = ConnectServerCTRL.Session;

                if (m_session == null)
                {
                    StartBTN.Enabled = false;
                    return;
                }

                // set a suitable initial state.
                if (m_session != null && !m_connectedOnce)
                {
                    m_connectedOnce = true;
                }

                // this client has built-in knowledge of the information model used by the server.
                NamespaceTable wellKnownNamespaceUris = new NamespaceTable();
                wellKnownNamespaceUris.Append(Namespaces.Methods);

                string[] browsePaths = new string[]
                {
                    "1:My Process/1:State",
                    "1:My Process",
                    "1:My Process/1:Start"
                };

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

                // subscribe to the state if available.
                if (nodes.Count > 0 && !NodeId.IsNull(nodes[0]))
                {
                    m_subscription = new Subscription();

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

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

                    MonitoredItem monitoredItem = new MonitoredItem();
                    monitoredItem.StartNodeId   = nodes[0];
                    monitoredItem.AttributeId   = Attributes.Value;
                    monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification);
                    m_subscription.AddItem(monitoredItem);

                    m_subscription.ApplyChanges();
                }

                // save the object/method
                if (nodes.Count > 2)
                {
                    m_objectNode = nodes[1];
                    m_methodNode = nodes[2];
                }

                InitialStateTB.Text = "1";
                FinalStateTB.Text   = "100";
                StartBTN.Enabled    = true;
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Handles requests arriving from a channel.
        /// </summary>
        public async void SendAsync(HttpContext context)
        {
            IAsyncResult result = null;

            try
            {
                if (m_callback == null)
                {
                    context.Response.ContentLength = 0;
                    context.Response.ContentType   = "text/plain";
                    context.Response.StatusCode    = (int)HttpStatusCode.NotImplemented;
                    await context.Response.WriteAsync(string.Empty);

                    return;
                }

                byte[] buffer = new byte[(int)context.Request.ContentLength];
                lock (m_lock)
                {
                    Task <int> task = context.Request.Body.ReadAsync(buffer, 0, (int)context.Request.ContentLength);
                    task.Wait();
                }

                IServiceRequest input = (IServiceRequest)BinaryDecoder.DecodeMessage(buffer, null, m_quotas.MessageContext);

                // extract the JWT token from the HTTP headers.
                if (input.RequestHeader == null)
                {
                    input.RequestHeader = new RequestHeader();
                }

                if (NodeId.IsNull(input.RequestHeader.AuthenticationToken) && input.TypeId != DataTypeIds.CreateSessionRequest)
                {
                    if (context.Request.Headers.Keys.Contains("Authorization"))
                    {
                        foreach (string value in context.Request.Headers["Authorization"])
                        {
                            if (value.StartsWith("Bearer"))
                            {
                                input.RequestHeader.AuthenticationToken = new NodeId(value.Substring("Bearer ".Length).Trim());
                            }
                        }
                    }
                }

                EndpointDescription endpoint = null;

                foreach (var ep in m_descriptions)
                {
                    if (ep.EndpointUrl.StartsWith(Utils.UriSchemeHttps))
                    {
                        endpoint = ep;
                        break;
                    }
                }

                result = m_callback.BeginProcessRequest(
                    m_listenerId,
                    endpoint,
                    input as IServiceRequest,
                    null,
                    null);

                IServiceResponse output = m_callback.EndProcessRequest(result);

                byte[] response = BinaryEncoder.EncodeMessage(output, m_quotas.MessageContext);
                context.Response.ContentLength = response.Length;
                context.Response.ContentType   = context.Request.ContentType;
                context.Response.StatusCode    = (int)HttpStatusCode.OK;
                await context.Response.Body.WriteAsync(response, 0, response.Length);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "HTTPSLISTENER - Unexpected error processing request.");
                context.Response.ContentLength = e.Message.Length;
                context.Response.ContentType   = "text/plain";
                context.Response.StatusCode    = (int)HttpStatusCode.InternalServerError;
                await context.Response.WriteAsync(e.Message);
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Parses the specified node identifier.
        /// </summary>
        /// <param name="nodeId">The node identifier.</param>
        /// <returns>The parsed node identifier. Null if the identifier cannot be parsed.</returns>
        public static new AeParsedNodeId Parse(NodeId nodeId)
        {
            // can only parse non-null string node identifiers.
            if (NodeId.IsNull(nodeId))
            {
                return(null);
            }

            string identifier = nodeId.Identifier as string;

            if (String.IsNullOrEmpty(identifier))
            {
                return(null);
            }

            AeParsedNodeId parsedNodeId = new AeParsedNodeId();

            parsedNodeId.NamespaceIndex = nodeId.NamespaceIndex;

            int start = 0;

            // extract the type of identifier.
            parsedNodeId.RootType = (int)ExtractNumber(identifier, ref start);

            if (start >= identifier.Length || identifier[start] != ':')
            {
                return(null);
            }

            // extract any component path.
            StringBuilder buffer = new StringBuilder();

            int index = start + 1;

            parsedNodeId.RootId = ExtractAndUnescapeString(identifier, ref index, '&', '?');

            // extract any component.
            int end = index + 1;

            parsedNodeId.ComponentPath = null;

            // extract the component path.
            if (end < identifier.Length)
            {
                parsedNodeId.ComponentPath = identifier.Substring(end);
            }

            // extract the category and condition name.
            start      = 0;
            identifier = parsedNodeId.RootId;

            switch (parsedNodeId.RootType)
            {
            case AeModelUtils.AeEventTypeMapping:
            {
                EventTypeMapping mapping = (EventTypeMapping)(int)ExtractNumber(identifier, ref start);

                if (start < identifier.Length)
                {
                    return(null);
                }

                parsedNodeId.CategoryId = (int)mapping;
                break;
            }

            case AeModelUtils.AeSimpleEventType:
            case AeModelUtils.AeTrackingEventType:
            {
                parsedNodeId.CategoryId = Utils.ToInt32(ExtractNumber(identifier, ref start));

                if (start < identifier.Length)
                {
                    return(null);
                }

                break;
            }

            case AeModelUtils.AeConditionEventType:
            {
                parsedNodeId.CategoryId = Utils.ToInt32(ExtractNumber(identifier, ref start));

                if (start < identifier.Length)
                {
                    if (identifier[start] != ':')
                    {
                        return(null);
                    }

                    parsedNodeId.ConditionName = identifier.Substring(start + 1);
                }

                break;
            }

            case AeModelUtils.AeCondition:
            {
                parsedNodeId.SourceId = ExtractAndUnescapeString(identifier, ref start, '0', ':');

                if (start < identifier.Length && identifier[start] != ':')
                {
                    return(null);
                }

                start++;

                parsedNodeId.CategoryId = Utils.ToInt32(ExtractNumber(identifier, ref start));

                if (start < identifier.Length)
                {
                    if (identifier[start] != ':')
                    {
                        return(null);
                    }

                    parsedNodeId.ConditionName = identifier.Substring(start + 1);
                }

                break;
            }
            }

            // extract the attribute id.
            if (!String.IsNullOrEmpty(parsedNodeId.ComponentPath))
            {
                start      = 0;
                identifier = parsedNodeId.ComponentPath;

                switch (parsedNodeId.RootType)
                {
                case AeModelUtils.AeSimpleEventType:
                case AeModelUtils.AeTrackingEventType:
                case AeModelUtils.AeConditionEventType:
                {
                    parsedNodeId.AttributeName = identifier.Substring(start + 1);
                    break;
                }
                }
            }

            return(parsedNodeId);
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Exports a DataTypeDefinition
        /// </summary>
        private Opc.Ua.Export.DataTypeDefinition Export(
            DataTypeState dataType,
            ExtensionObject source,
            NamespaceTable namespaceUris,
            bool outputRedundantNames)
        {
            if (source == null || source.Body == null)
            {
                return(null);
            }

            DataTypeDefinition definition = new DataTypeDefinition();

            if (outputRedundantNames || dataType.BrowseName != null)
            {
                definition.Name = Export(dataType.BrowseName, namespaceUris);
            }

            if (dataType.BrowseName.Name != dataType.SymbolicName)
            {
                definition.SymbolicName = dataType.SymbolicName;
            }

            StructureDefinition sd = source.Body as StructureDefinition;

            if (sd != null)
            {
                if (sd.StructureType == StructureType.Union || sd.StructureType == (StructureType)4) // StructureType.UnionWithSubtypedValues)
                {
                    definition.IsUnion = true;
                }

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

                    for (int ii = sd.FirstExplicitFieldIndex; ii < sd.Fields.Count; ii++)
                    {
                        StructureField field = sd.Fields[ii];

                        Opc.Ua.Export.DataTypeField output = new Opc.Ua.Export.DataTypeField();

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

                        if (sd.StructureType == StructureType.StructureWithOptionalFields)
                        {
                            output.IsOptional    = field.IsOptional;
                            output.AllowSubTypes = false;
                        }
                        else if (sd.StructureType == (StructureType)3 || // StructureType.StructureWithSubtypedValues ||
                                 sd.StructureType == (StructureType)4)   // StructureType.UnionWithSubtypedValues)
                        {
                            output.IsOptional    = false;
                            output.AllowSubTypes = field.IsOptional;
                        }
                        else
                        {
                            output.IsOptional    = false;
                            output.AllowSubTypes = false;
                        }

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

                        output.ValueRank = field.ValueRank;

                        fields.Add(output);
                    }

                    definition.Field = fields.ToArray();
                }
            }

            EnumDefinition ed = source.Body as EnumDefinition;

            if (ed != null)
            {
                definition.IsOptionSet = ed.IsOptionSet;

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

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

                        output.Name = field.Name;

                        if (field.DisplayName != null && output.Name != field.DisplayName.Text)
                        {
                            output.DisplayName = Export(new Opc.Ua.LocalizedText[] { field.DisplayName });
                        }
                        else
                        {
                            output.DisplayName = Array.Empty <LocalizedText>();
                        }

                        output.Description = Export(new Opc.Ua.LocalizedText[] { field.Description });
                        output.ValueRank   = ValueRanks.Scalar;
                        output.Value       = (int)field.Value;

                        fields.Add(output);
                    }

                    definition.Field = fields.ToArray();
                }
            }

            return(definition);
        }
Ejemplo n.º 23
0
        public virtual NodeId RegisterApplication(
            ApplicationRecordDataType application
            )
        {
            if (application == null)
            {
                throw new ArgumentNullException(nameof(application));
            }

            if (application.ApplicationUri == null)
            {
                throw new ArgumentNullException("ApplicationUri");
            }

            if (!Uri.IsWellFormedUriString(application.ApplicationUri, UriKind.Absolute))
            {
                throw new ArgumentException(application.ApplicationUri + " is not a valid URI.", "ApplicationUri");
            }

            if (application.ApplicationType < ApplicationType.Server || application.ApplicationType > ApplicationType.DiscoveryServer)
            {
                throw new ArgumentException(application.ApplicationType.ToString() + " is not a valid ApplicationType.", "ApplicationType");
            }

            if (application.ApplicationNames == null || application.ApplicationNames.Count == 0 || LocalizedText.IsNullOrEmpty(application.ApplicationNames[0]))
            {
                throw new ArgumentException("At least one ApplicationName must be provided.", "ApplicationNames");
            }

            if (String.IsNullOrEmpty(application.ProductUri))
            {
                throw new ArgumentException("A ProductUri must be provided.", "ProductUri");
            }

            if (!Uri.IsWellFormedUriString(application.ProductUri, UriKind.Absolute))
            {
                throw new ArgumentException(application.ProductUri + " is not a valid URI.", "ProductUri");
            }

            if (application.DiscoveryUrls != null)
            {
                foreach (var discoveryUrl in application.DiscoveryUrls)
                {
                    if (String.IsNullOrEmpty(discoveryUrl))
                    {
                        continue;
                    }

                    if (!Uri.IsWellFormedUriString(discoveryUrl, UriKind.Absolute))
                    {
                        throw new ArgumentException(discoveryUrl + " is not a valid URL.", "DiscoveryUrls");
                    }
                }
            }

            if (application.ApplicationType != ApplicationType.Client)
            {
                if (application.DiscoveryUrls == null || application.DiscoveryUrls.Count == 0)
                {
                    throw new ArgumentException("At least one DiscoveryUrl must be provided.", "DiscoveryUrls");
                }

                if (application.ServerCapabilities == null || application.ServerCapabilities.Count == 0)
                {
                    application.ServerCapabilities = new StringCollection()
                    {
                        "NA"
                    };
                }
            }
            else
            {
                if (application.DiscoveryUrls != null && application.DiscoveryUrls.Count > 0)
                {
                    throw new ArgumentException("DiscoveryUrls must not be specified for clients.", "DiscoveryUrls");
                }
            }

            NodeId nodeId = new NodeId();

            if (!NodeId.IsNull(application.ApplicationId))
            {
                // verify node integrity
                switch (application.ApplicationId.IdType)
                {
                case IdType.Guid:
                    nodeId = new NodeId((Guid)application.ApplicationId.Identifier, NamespaceIndex);
                    break;

                case IdType.String:
                    nodeId = new NodeId((string)application.ApplicationId.Identifier, NamespaceIndex);
                    break;

                default:
                    throw new ArgumentException("The ApplicationId has invalid type {0}", application.ApplicationId.ToString());
                }
            }

            return(nodeId);
        }
Ejemplo n.º 24
0
        /// <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, GuiUtils2.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;
                        }
                    }
                }
            }

            AdjustColumns();
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Handles requests arriving from a channel.
        /// </summary>
        public async Task SendAsync(HttpContext context)
        {
            IAsyncResult result = null;

            try
            {
                if (m_callback == null)
                {
                    context.Response.ContentLength = 0;
                    context.Response.ContentType   = "text/plain";
                    context.Response.StatusCode    = (int)HttpStatusCode.NotImplemented;
                    await context.Response.WriteAsync(string.Empty).ConfigureAwait(false);

                    return;
                }

                if (context.Request.ContentType != "application/octet-stream")
                {
                    context.Response.ContentLength = 0;
                    context.Response.ContentType   = "text/plain";
                    context.Response.StatusCode    = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync("HTTPSLISTENER - Unsupported content type.").ConfigureAwait(false);

                    return;
                }

                int    length = (int)context.Request.ContentLength;
                byte[] buffer = await ReadBodyAsync(context.Request).ConfigureAwait(false);

                if (buffer.Length != length)
                {
                    context.Response.ContentLength = 0;
                    context.Response.ContentType   = "text/plain";
                    context.Response.StatusCode    = (int)HttpStatusCode.BadRequest;
                    await context.Response.WriteAsync("HTTPSLISTENER - Couldn't decode buffer.").ConfigureAwait(false);

                    return;
                }

                IServiceRequest input = (IServiceRequest)BinaryDecoder.DecodeMessage(buffer, null, m_quotas.MessageContext);

                // extract the JWT token from the HTTP headers.
                if (input.RequestHeader == null)
                {
                    input.RequestHeader = new RequestHeader();
                }

                if (NodeId.IsNull(input.RequestHeader.AuthenticationToken) && input.TypeId != DataTypeIds.CreateSessionRequest)
                {
                    if (context.Request.Headers.ContainsKey("Authorization"))
                    {
                        foreach (string value in context.Request.Headers["Authorization"])
                        {
                            if (value.StartsWith("Bearer", StringComparison.OrdinalIgnoreCase))
                            {
                                // note: use NodeId(string, uint) to avoid the NodeId.Parse call.
                                input.RequestHeader.AuthenticationToken = new NodeId(value.Substring("Bearer ".Length).Trim(), 0);
                            }
                        }
                    }
                }

                if (!context.Request.Headers.TryGetValue("OPCUA-SecurityPolicy", out var header))
                {
                    header = SecurityPolicies.None;
                }

                EndpointDescription endpoint = null;
                foreach (var ep in m_descriptions)
                {
                    if (ep.EndpointUrl.StartsWith(Utils.UriSchemeHttps, StringComparison.Ordinal))
                    {
                        if (!string.IsNullOrEmpty(header))
                        {
                            if (!string.Equals(ep.SecurityPolicyUri, header, StringComparison.Ordinal))
                            {
                                continue;
                            }
                        }

                        endpoint = ep;
                        break;
                    }
                }

                if (endpoint == null &&
                    input.TypeId != DataTypeIds.GetEndpointsRequest &&
                    input.TypeId != DataTypeIds.FindServersRequest)
                {
                    var message = "Connection refused, invalid security policy.";
                    Utils.LogError(message);
                    context.Response.ContentLength = message.Length;
                    context.Response.ContentType   = "text/plain";
                    context.Response.StatusCode    = (int)HttpStatusCode.Unauthorized;
                    await context.Response.WriteAsync(message).ConfigureAwait(false);
                }

                result = m_callback.BeginProcessRequest(
                    m_listenerId,
                    endpoint,
                    input as IServiceRequest,
                    null,
                    null);

                IServiceResponse output = m_callback.EndProcessRequest(result);

                byte[] response = BinaryEncoder.EncodeMessage(output, m_quotas.MessageContext);
                context.Response.ContentLength = response.Length;
                context.Response.ContentType   = context.Request.ContentType;
                context.Response.StatusCode    = (int)HttpStatusCode.OK;
#if NETSTANDARD2_1 || NET5_0_OR_GREATER || NETCOREAPP3_1_OR_GREATER
                await context.Response.Body.WriteAsync(response.AsMemory(0, response.Length)).ConfigureAwait(false);
#else
                await context.Response.Body.WriteAsync(response, 0, response.Length).ConfigureAwait(false);
#endif
            }
            catch (Exception e)
            {
                Utils.LogError(e, "HTTPSLISTENER - Unexpected error processing request.");
                context.Response.ContentLength = e.Message.Length;
                context.Response.ContentType   = "text/plain";
                context.Response.StatusCode    = (int)HttpStatusCode.InternalServerError;
                await context.Response.WriteAsync(e.Message).ConfigureAwait(false);
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Convert node model to vertex
        /// </summary>
        /// <param name="node"></param>
        /// <param name="sourceId"></param>
        /// <param name="revision"></param>
        /// <param name="codec"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public static BaseNodeVertexModel ToVertex(this BaseNodeModel node, string sourceId,
                                                   long revision, IVariantEncoder codec, ServiceMessageContext context)
        {
            if (node == null)
            {
                throw new ArgumentNullException(nameof(node));
            }
            if (NodeId.IsNull(node.NodeId))
            {
                throw new ArgumentException(nameof(node));
            }
            var builtInType = BuiltInType.Null;
            BaseNodeVertexModel vertex;

            switch (node)
            {
            case ObjectNodeModel oNode:
                vertex = new ObjectNodeVertexModel {
                    EventNotifier = (NodeEventNotifier?)oNode.EventNotifier
                };
                break;

            case PropertyNodeModel vNode:
                vertex = new PropertyNodeVertexModel {
                    ValueRank       = (NodeValueRank?)vNode.ValueRank,
                    ArrayDimensions = vNode.ArrayDimensions,
                    AccessLevel     = (vNode.AccessLevel != null || vNode.AccessLevelEx != null) ?
                                      (NodeAccessLevel?)((vNode.AccessLevel ?? 0) |
                                                         (vNode.AccessLevelEx ?? 0)) : null,
                    MinimumSamplingInterval = vNode.MinimumSamplingInterval,
                    Historizing             = vNode.Historizing,
                    Value = vNode.Value == null ? null : codec.Encode(vNode.Value.Value,
                                                                      out builtInType, context),
                    BuiltInType = builtInType
                };
                break;

            case VariableNodeModel vNode:
                vertex = new VariableNodeVertexModel {
                    ValueRank       = (NodeValueRank?)vNode.ValueRank,
                    ArrayDimensions = vNode.ArrayDimensions,
                    AccessLevel     = (vNode.AccessLevel != null || vNode.AccessLevelEx != null) ?
                                      (NodeAccessLevel?)((vNode.AccessLevel ?? 0) |
                                                         (vNode.AccessLevelEx ?? 0)) : null,
                    MinimumSamplingInterval = vNode.MinimumSamplingInterval,
                    Historizing             = vNode.Historizing,
                    Value = vNode.Value == null ? null : codec.Encode(vNode.Value.Value,
                                                                      out builtInType, context),
                    BuiltInType = builtInType
                };
                break;

            case MethodNodeModel mNode:
                vertex = new MethodNodeVertexModel {
                    Executable     = mNode.Executable.ToNullable(false),
                    UserExecutable = mNode.UserExecutable.ToNullable(false)
                };
                break;

            case ViewNodeModel vNode:
                vertex = new ViewNodeVertexModel {
                    ContainsNoLoops = vNode.ContainsNoLoops
                };
                break;

            case ObjectTypeNodeModel otNode:
                vertex = new ObjectTypeNodeVertexModel {
                    IsAbstract = otNode.IsAbstract
                };
                break;

            case PropertyTypeNodeModel vtNode:
                vertex = new PropertyTypeNodeVertexModel {
                    IsAbstract      = vtNode.IsAbstract ?? false,
                    ValueRank       = (NodeValueRank?)vtNode.ValueRank,
                    ArrayDimensions = vtNode.ArrayDimensions,
                    Value           = vtNode.Value == null ? null : codec.Encode(vtNode.Value.Value,
                                                                                 out builtInType, context),
                    BuiltInType = builtInType
                };
                break;

            case VariableTypeNodeModel vtNode:
                vertex = new VariableTypeNodeVertexModel {
                    IsAbstract      = vtNode.IsAbstract ?? false,
                    ValueRank       = (NodeValueRank?)vtNode.ValueRank,
                    ArrayDimensions = vtNode.ArrayDimensions,
                    Value           = vtNode.Value == null ? null : codec.Encode(vtNode.Value.Value,
                                                                                 out builtInType, context),
                    BuiltInType = builtInType
                };
                break;

            case DataTypeNodeModel dtNode:
                vertex = new DataTypeNodeVertexModel {
                    IsAbstract         = dtNode.IsAbstract,
                    DataTypeDefinition = dtNode.Definition == null ? null :
                                         codec.Encode(new Variant(new ExtensionObject(dtNode.Definition)),
                                                      out _, context)
                };
                break;

            case ReferenceTypeNodeModel rtNode:
                vertex = new ReferenceTypeNodeVertexModel {
                    IsAbstract  = rtNode.IsAbstract,
                    Symmetric   = rtNode.Symmetric,
                    InverseName = rtNode.InverseName.AsString()
                };
                break;

            default:
                return(null);
            }
            vertex.NodeId        = node.NodeId.AsString(context);
            vertex.BrowseName    = node.BrowseName.AsString(context);
            vertex.DisplayName   = node.DisplayName.AsString();
            vertex.Description   = node.Description.AsString();
            vertex.WriteMask     = (uint?)node.WriteMask;
            vertex.UserWriteMask = (uint?)node.UserWriteMask;
            if (!string.IsNullOrEmpty(node.SymbolicName) && node.SymbolicName != node.BrowseName.Name)
            {
                vertex.SymbolicName = node.SymbolicName;
            }

            vertex.Revision = revision;
            vertex.SourceId = sourceId;
            vertex.Id       = CreateAddressSpaceVertexId(sourceId, vertex.NodeId);

#if FALSE
            if (node.RolePermissions != null && node.RolePermissions.Count > 0)
            {
            }
            if (node.UserRolePermissions != null && node.UserRolePermissions.Count > 0)
            {
            }

            // export references.
            var exportedReferences = new List <Reference>();
            foreach (var reference in node.GetAllReferences(context))
            {
                if (node.NodeClass == NodeClass.Method)
                {
                    if (!reference.IsInverse &&
                        reference.ReferenceTypeId == ReferenceTypeIds.HasTypeDefinition)
                    {
                        continue;
                    }
                }
                exportedReferences.Add(new Reference {
                    ReferenceType = EncodeNodeId(reference.ReferenceTypeId, context),
                    IsForward     = !reference.IsInverse,
                    Value         = EncodeExpandedNodeId(reference.TargetId, context)
                });
            }
            vertex.References = exportedReferences.ToArray();
#endif
            return(vertex);
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Validates the items.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="requests">The requests.</param>
        /// <returns>The items. May contain null is validation failed.</returns>
        public ComDaGroupItem[] ValidateItems(ComDaGroup group, ComDaCreateItemRequest[] requests)
        {
            TraceState("ValidateItems", group.Name);

            // get the session to use for the operation.
            Session session = m_session;

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

            // validate items.
            ComDaGroupItem[] items = new ComDaGroupItem[requests.Length];

            for (int ii = 0; ii < requests.Length; ii += 10000)
            {
                ValidateItems(session, group, requests, items, ii, 10000);
            }

            // process results.
            for (int ii = 0; ii < requests.Length; ii++)
            {
                // check for the results.
                ComDaCreateItemRequest request = requests[ii];

                if (request.Error < 0)
                {
                    items[ii] = null;
                    continue;
                }

                // check access path.
                if (!String.IsNullOrEmpty(request.AccessPath))
                {
                    items[ii]     = null;
                    request.Error = ResultIds.E_UNKNOWNPATH;
                    continue;
                }

                ComDaGroupItem item = items[ii];

                // validate the datatype.
                if (request.RequestedDataType != 0)
                {
                    NodeId dataTypeId = ComUtils.GetDataTypeId(request.RequestedDataType);

                    if (NodeId.IsNull(dataTypeId))
                    {
                        items[ii]     = null;
                        request.Error = ResultIds.E_BADTYPE;
                        continue;
                    }

                    bool reqTypeIsArray    = (request.RequestedDataType & (short)VarEnum.VT_ARRAY) != 0;
                    bool actualTypeIsArray = (item.CanonicalDataType & (short)VarEnum.VT_ARRAY) != 0;

                    if (reqTypeIsArray != actualTypeIsArray)
                    {
                        items[ii]     = null;
                        request.Error = ResultIds.E_BADTYPE;
                        continue;
                    }
                }

                // create a new monitored item.
                MonitoredItem monitoredItem = new MonitoredItem();

                monitoredItem.StartNodeId      = item.NodeId;
                monitoredItem.RelativePath     = null;
                monitoredItem.AttributeId      = Attributes.Value;
                monitoredItem.MonitoringMode   = (request.Active)?MonitoringMode.Reporting:MonitoringMode.Disabled;
                monitoredItem.SamplingInterval = group.UpdateRate / 2;
                monitoredItem.QueueSize        = 0;
                monitoredItem.DiscardOldest    = true;
                monitoredItem.Filter           = null;

                // update item.
                item.ServerHandle  = (int)monitoredItem.ClientHandle;
                item.MonitoredItem = monitoredItem;

                // link the monitored item back to the group item.
                monitoredItem.Handle = item;

                // update return parameters.
                request.ServerHandle      = item.ServerHandle;
                request.CanonicalDataType = item.CanonicalDataType;
                request.AccessRights      = item.AccessRights;
                request.Error             = ResultIds.S_OK;
            }

            return(items);
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Updates the display with a new value for a monitored variable.
        /// </summary>
        private void MonitoredItem_Notification(MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs e)
        {
            if (this.InvokeRequired)
            {
                this.BeginInvoke(new MonitoredItemNotificationEventHandler(MonitoredItem_Notification), monitoredItem, e);
                return;
            }

            try
            {
                EventFieldList notification = e.NotificationValue as EventFieldList;

                if (notification == null)
                {
                    return;
                }

                // check the type of event.
                NodeId eventTypeId = FormUtils.FindEventType(monitoredItem, notification);

                // ignore unknown events.
                if (NodeId.IsNull(eventTypeId))
                {
                    return;
                }

                // check for refresh start.
                if (eventTypeId == ObjectTypeIds.RefreshStartEventType)
                {
                    ConditionsLV.Items.Clear();
                    return;
                }

                // check for refresh end.
                if (eventTypeId == ObjectTypeIds.RefreshEndEventType)
                {
                    return;
                }

                // construct the condition object.
                ConditionState condition = FormUtils.ConstructEvent(
                    m_session,
                    monitoredItem,
                    notification,
                    m_eventTypeMappings) as ConditionState;

                if (condition == null)
                {
                    return;
                }

                // look for existing entry.
                ListViewItem item = null;

                for (int ii = 0; ii < ConditionsLV.Items.Count; ii++)
                {
                    ConditionState current = (ConditionState)ConditionsLV.Items[ii].Tag;

                    // the combination of a condition and branch id uniquely identify an item in the display.
                    if (current.NodeId == condition.NodeId && BaseVariableState.GetValue(current.BranchId) == BaseVariableState.GetValue(condition.BranchId))
                    {
                        // match found but watch out for out of order events (async processing can cause this to happen).
                        if (BaseVariableState.GetValue(current.Time) > BaseVariableState.GetValue(condition.Time))
                        {
                            return;
                        }

                        item = ConditionsLV.Items[ii];
                        break;
                    }
                }

                // create a new entry.
                if (item == null)
                {
                    item = new ListViewItem(String.Empty);

                    item.SubItems.Add(String.Empty); // Condition
                    item.SubItems.Add(String.Empty); // Branch
                    item.SubItems.Add(String.Empty); // Type
                    item.SubItems.Add(String.Empty); // Severity
                    item.SubItems.Add(String.Empty); // Time
                    item.SubItems.Add(String.Empty); // State
                    item.SubItems.Add(String.Empty); // Message
                    item.SubItems.Add(String.Empty); // Comment

                    ConditionsLV.Items.Add(item);
                }

                // look up the condition type metadata in the local cache.
                INode type = m_session.NodeCache.Find(condition.TypeDefinitionId);

                // Source
                if (condition.SourceName != null)
                {
                    item.SubItems[0].Text = Utils.Format("{0}", condition.SourceName.Value);
                }
                else
                {
                    item.SubItems[0].Text = null;
                }

                // Condition
                if (condition.ConditionName != null)
                {
                    item.SubItems[1].Text = Utils.Format("{0}", condition.ConditionName.Value);
                }
                else
                {
                    item.SubItems[1].Text = null;
                }

                // Branch
                if (condition.BranchId != null && !NodeId.IsNull(condition.BranchId.Value))
                {
                    item.SubItems[2].Text = Utils.Format("{0}", condition.BranchId.Value);
                }
                else
                {
                    item.SubItems[2].Text = null;
                }

                // Type
                if (type != null)
                {
                    item.SubItems[3].Text = Utils.Format("{0}", type);
                }
                else
                {
                    item.SubItems[3].Text = null;
                }

                // Severity
                if (condition.Severity != null)
                {
                    item.SubItems[4].Text = Utils.Format("{0}", (EventSeverity)condition.Severity.Value);
                }
                else
                {
                    item.SubItems[4].Text = null;
                }

                // Time
                if (condition.Time != null)
                {
                    item.SubItems[5].Text = Utils.Format("{0:HH:mm:ss.fff}", condition.Time.Value.ToLocalTime());
                }
                else
                {
                    item.SubItems[5].Text = null;
                }

                // State
                if (condition.EnabledState != null && condition.EnabledState.EffectiveDisplayName != null)
                {
                    item.SubItems[6].Text = Utils.Format("{0}", condition.EnabledState.EffectiveDisplayName.Value);
                }
                else
                {
                    item.SubItems[6].Text = null;
                }

                // Message
                if (condition.Message != null)
                {
                    item.SubItems[7].Text = Utils.Format("{0}", condition.Message.Value);
                }
                else
                {
                    item.SubItems[7].Text = null;
                }

                // Comment
                if (condition.Comment != null)
                {
                    item.SubItems[8].Text = Utils.Format("{0}", condition.Comment.Value);
                }
                else
                {
                    item.SubItems[8].Text = null;
                }

                item.Tag = condition;

                // set the color based on the retain bit.
                if (!BaseVariableState.GetValue(condition.Retain))
                {
                    item.ForeColor = Color.DimGray;
                }
                else
                {
                    if (NodeId.IsNull(BaseVariableState.GetValue(condition.BranchId)))
                    {
                        item.ForeColor = Color.Empty;
                    }
                    else
                    {
                        item.ForeColor = Color.DarkGray;
                    }
                }

                // adjust the width of the columns.
                for (int ii = 0; ii < ConditionsLV.Columns.Count; ii++)
                {
                    ConditionsLV.Columns[ii].Width = -2;
                }
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(this.Text, exception);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Displays the value in the control.
        /// </summary>
        public void ShowValue(
            NodeId nodeId,
            uint attributeId,
            string name,
            object value,
            bool readOnly)
        {
            m_readOnly = readOnly;
            NavigationMENU.Items.Clear();

            if (m_readOnly)
            {
                ValuesDV.EditMode    = DataGridViewEditMode.EditProgrammatically;
                TextValueTB.ReadOnly = true;
            }

            Type type = null;

            // determine the expected data type for non-value attributes.
            if (attributeId != 0 && attributeId != Attributes.Value)
            {
                BuiltInType builtInType = TypeInfo.GetBuiltInType(Attributes.GetDataTypeId(attributeId));
                int         valueRank   = Attributes.GetValueRank(attributeId);
                type = TypeInfo.GetSystemType(builtInType, valueRank);
            }

            // determine the expected data type for value attributes.
            else if (!NodeId.IsNull(nodeId))
            {
                IVariableBase variable = m_session.NodeCache.Find(nodeId) as IVariableBase;

                if (variable != null)
                {
                    BuiltInType builtInType = TypeInfo.GetBuiltInType(variable.DataType, m_session.TypeTree);
                    int         valueRank   = variable.ValueRank;
                    type = TypeInfo.GetSystemType(builtInType, valueRank);

                    if (builtInType == BuiltInType.ExtensionObject && valueRank < 0)
                    {
                        type = TypeInfo.GetSystemType(variable.DataType, m_session.Factory);
                    }
                }
            }

            // use the value.
            else if (value != null)
            {
                type = value.GetType();
            }

            // go with default.
            else
            {
                type = typeof(string);
            }

            // assign a name.
            if (String.IsNullOrEmpty(name))
            {
                if (attributeId != 0)
                {
                    name = Attributes.GetBrowseName(attributeId);
                }
                else
                {
                    name = type.Name;
                }
            }

            AccessInfo info = new AccessInfo();

            info.Value    = Utils.Clone(value);
            info.TypeInfo = TypeInfo.Construct(type);

            if (value == null && info.TypeInfo.ValueRank < 0)
            {
                info.Value = TypeInfo.GetDefaultValue(info.TypeInfo.BuiltInType);
            }

            info.Name = name;
            m_value   = info;

            ShowValue(info);
        }
Ejemplo n.º 30
0
        public NodeId RegisterApplication(ApplicationRecordDataType application)
        {
            NodeId appNodeId = application.ApplicationId;

            if (NodeId.IsNull(appNodeId))
            {
                appNodeId = new NodeId(Guid.NewGuid(), NamespaceIndex);
            }
            Guid          applicationId = (Guid)appNodeId.Identifier;
            StringBuilder capabilities  = new StringBuilder();

            application.ServerCapabilities.Sort();
            foreach (string capability in application.ServerCapabilities)
            {
                if (string.IsNullOrEmpty(capability))
                {
                    continue;
                }
                if (capabilities.Length > 0)
                {
                    capabilities.Append(',');
                }
                capabilities.Append(capability);
            }
            lock (Lock)
            {
                Application record = null;
                if (applicationId != Guid.Empty)
                {
                    IEnumerable <Application> results = from x in Applications
                                                        where x.ApplicationId == applicationId
                                                        select x;
                    record = results.SingleOrDefault();
                    if (record != null)
                    {
                        List <ServerEndpoint> endpoints = (from ii in ServerEndpoints
                                                           where ii.ApplicationId == record.ApplicationId
                                                           select ii).ToList();
                        foreach (var endpoint in endpoints)
                        {
                            ServerEndpoints.Remove(endpoint);
                        }
                        List <ApplicationName> names = (from ii in ApplicationNames
                                                        where ii.ApplicationId == record.ApplicationId
                                                        select ii).ToList();
                        foreach (var name in names)
                        {
                            ApplicationNames.Remove(name);
                        }
                        SaveChanges();
                    }
                }
                bool isNew = false;
                if (record == null)
                {
                    applicationId = Guid.NewGuid();
                    record        = new Application()
                    {
                        ApplicationId = applicationId,
                        ID            = 0
                    };
                    isNew = true;
                }
                record.ApplicationUri     = application.ApplicationUri;
                record.ApplicationName    = application.ApplicationNames[0].Text;
                record.ApplicationType    = (int)application.ApplicationType;
                record.ProductUri         = application.ProductUri;
                record.ServerCapabilities = capabilities.ToString();
                if (isNew)
                {
                    Applications.Add(record);
                }
                SaveChanges();
                if (application.DiscoveryUrls != null)
                {
                    foreach (var discoveryUrl in application.DiscoveryUrls)
                    {
                        ServerEndpoints.Add(new ServerEndpoint()
                        {
                            ApplicationId = record.ApplicationId,
                            DiscoveryUrl  = discoveryUrl
                        });
                    }
                }
                if (application.ApplicationNames != null && application.ApplicationNames.Count > 0)
                {
                    foreach (var applicationName in application.ApplicationNames)
                    {
                        ApplicationNames.Add(new ApplicationName()
                        {
                            ApplicationId = record.ApplicationId,
                            Locale        = applicationName.Locale,
                            Text          = applicationName.Text
                        });
                    }
                }
                SaveChanges();
                return(new NodeId(applicationId, NamespaceIndex));
            }
        }