private void ShowEndpointDescriptions(List <EndpointDescription> endpoints)
        {
            EndpointsTable.Rows.Clear();

            bool headerSet = false;

            foreach (EndpointDescription endpoint in endpoints)
            {
                if (!headerSet)
                {
                    ApplicationNameTextBox.Text = (LocalizedText.IsNullOrEmpty(endpoint.Server.ApplicationName)) ? "---" : endpoint.Server.ApplicationName.Text;
                    ApplicationTypeTextBox.Text = endpoint.Server.ApplicationType.ToString();
                    ApplicationUriTextBox.Text  = endpoint.Server.ApplicationUri;
                    ProductUriTextBox.Text      = endpoint.Server.ProductUri;

                    headerSet = true;
                }

                DataRow row = EndpointsTable.NewRow();

                row[0] = endpoint.EndpointUrl;
                row[1] = endpoint.SecurityMode.ToString();
                row[2] = SecurityPolicies.GetDisplayName(endpoint.SecurityPolicyUri);
                row[3] = endpoint;

                EndpointsTable.Rows.Add(row);
            }

            m_dataset.AcceptChanges();

            foreach (DataGridViewRow row in EndpointsGridView.Rows)
            {
                row.Selected = false;
            }
        }
Exemple #2
0
        /// <summary>
        /// Translates a service result.
        /// </summary>
        public ServiceResult Translate(IList <string> preferredLocales, ServiceResult result)
        {
            if (result == null)
            {
                return(null);
            }

            // translate localized text.
            LocalizedText translatedText = result.LocalizedText;

            if (LocalizedText.IsNullOrEmpty(result.LocalizedText))
            {
                // extract any additional arguments from the translation info.
                object[] args = null;

                if (result.LocalizedText != null && result.LocalizedText.TranslationInfo != null)
                {
                    TranslationInfo info = result.LocalizedText.TranslationInfo;

                    if (info != null && info.Args != null && info.Args.Length > 0)
                    {
                        args = info.Args;
                    }
                }

                if (!String.IsNullOrEmpty(result.SymbolicId))
                {
                    translatedText =
                        TranslateSymbolicId(preferredLocales, result.SymbolicId, result.NamespaceUri, args);
                }
                else
                {
                    translatedText = TranslateStatusCode(preferredLocales, result.StatusCode, args);
                }
            }
            else
            {
                if (preferredLocales == null || preferredLocales.Count == 0)
                {
                    return(result);
                }

                translatedText = Translate(preferredLocales, result.LocalizedText);
            }

            // construct new service result.
            ServiceResult translatedResult = new ServiceResult(
                result.StatusCode,
                result.SymbolicId,
                result.NamespaceUri,
                translatedText,
                result.AdditionalInfo,
                Translate(preferredLocales, result.InnerResult));

            return(translatedResult);
        }
        private void ShowApplicationDescriptions(TreeNodeCollection nodes)
        {
            ServersTable.Rows.Clear();

            foreach (TreeNode node in nodes)
            {
                ApplicationDescription server = node.Tag as ApplicationDescription;

                if (server == null)
                {
                    continue;
                }

                DataRow row = ServersTable.NewRow();

                row[0] = (LocalizedText.IsNullOrEmpty(server.ApplicationName)) ? "" : server.ApplicationName.Text;
                row[1] = server.ApplicationType.ToString();

                StringBuilder buffer = new StringBuilder();

                if (server.DiscoveryUrls != null)
                {
                    foreach (var url in server.DiscoveryUrls)
                    {
                        if (buffer.Length > 0)
                        {
                            buffer.Append(", ");
                        }

                        buffer.Append(url);
                    }
                }

                row[2] = buffer.ToString();
                row[3] = null;
                row[4] = server;

                ServersTable.Rows.Add(row);
            }

            m_dataset.AcceptChanges();

            foreach (DataGridViewRow row in ServersGridView.Rows)
            {
                row.Selected = false;
            }
        }
Exemple #4
0
        /// <summary>
        /// Displays the references in the control.
        /// </summary>
        private void DisplayReferences(Session session, List <ReferenceDescription> references)
        {
            ReferencesLV.Items.Clear();

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

                string referenceType = null;

                // look up the name for the reference
                IReferenceType referenceTypeNode = session.NodeCache.Find(reference.ReferenceTypeId) as IReferenceType;

                if (referenceTypeNode != null)
                {
                    referenceType = referenceTypeNode.DisplayName.Text;

                    if (!reference.IsForward && !LocalizedText.IsNullOrEmpty(referenceTypeNode.InverseName))
                    {
                        referenceType = referenceTypeNode.InverseName.Text;
                    }
                }

                // the node cache is used to store the type model so it can be accessed locally.
                string typeDefinition = session.NodeCache.GetDisplayText(reference.TypeDefinition);

                ListViewItem item = new ListViewItem(referenceType);

                // the ToString() operator on the ReferenceDescription returns the target name.
                item.SubItems.Add(reference.ToString());
                item.SubItems.Add(reference.NodeClass.ToString());
                item.SubItems.Add(typeDefinition);

                item.Tag = reference;

                ReferencesLV.Items.Add(item);
            }

            // auto size the columns.
            for (int ii = 0; ii < ReferencesLV.Columns.Count; ii++)
            {
                ReferencesLV.Columns[ii].Width = -2;
            }
        }
Exemple #5
0
 /// <inheritdoc/>
 public void WriteLocalizedText(string property, LocalizedText value)
 {
     if (LocalizedText.IsNullOrEmpty(value))
     {
         WriteNull(property);
     }
     else if (UseReversibleEncoding || value.Locale != null)
     {
         PushObject(property);
         WriteString("Text", value.Text);
         if (!string.IsNullOrEmpty(value.Locale))
         {
             WriteString("Locale", value.Locale);
         }
         PopObject();
     }
     else
     {
         WriteString(property, value.Text);
     }
 }
Exemple #6
0
        /// <summary>
        /// Updates the EUInfo for the items.
        /// </summary>
        /// <param name="group">The group.</param>
        /// <param name="items">The items. Null entries are ignored.</param>
        public void UpdateItemEuInfo(
            ComDaGroup group,
            IList <ComDaGroupItem> items)
        {
            // get the session to use for the operation.
            Session session = m_session;

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

            // build list of properties that need to be read.
            BrowsePathCollection browsePaths = new BrowsePathCollection();

            for (int ii = 0; ii < items.Count; ii++)
            {
                ComDaGroupItem item = (ComDaGroupItem)items[ii];

                // ignore invalid items or items which have already checked their EU type.
                if (item == null || item.EuType >= 0)
                {
                    continue;
                }

                BrowsePath browsePath = new BrowsePath();
                browsePath.StartingNode = item.NodeId;
                RelativePathElement element = new RelativePathElement();
                element.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                element.IsInverse       = false;
                element.IncludeSubtypes = false;
                element.TargetName      = Opc.Ua.BrowseNames.EURange;
                browsePath.RelativePath.Elements.Add(element);
                browsePath.Handle = item;
                browsePaths.Add(browsePath);

                browsePath = new BrowsePath();
                browsePath.StartingNode = item.NodeId;
                element = new RelativePathElement();
                element.ReferenceTypeId = ReferenceTypeIds.HasProperty;
                element.IsInverse       = false;
                element.IncludeSubtypes = false;
                element.TargetName      = Opc.Ua.BrowseNames.EnumStrings;
                browsePath.RelativePath.Elements.Add(element);
                browsePath.Handle = item;
                browsePaths.Add(browsePath);
            }

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

            // translate browse paths.
            BrowsePathResultCollection results         = null;
            DiagnosticInfoCollection   diagnosticInfos = null;

            try
            {
                session.TranslateBrowsePathsToNodeIds(
                    null,
                    browsePaths,
                    out results,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(results, browsePaths);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, browsePaths);
            }
            catch (Exception)
            {
                for (int ii = 0; ii < browsePaths.Count; ii++)
                {
                    ComDaGroupItem item = (ComDaGroupItem)browsePaths[ii].Handle;
                    item.EuType = 0;
                }

                return;
            }

            // build list of properties that need to be read.
            ReadValueIdCollection propertiesToRead = new ReadValueIdCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                ComDaGroupItem   item   = (ComDaGroupItem)browsePaths[ii].Handle;
                BrowsePathResult result = results[ii];

                if (StatusCode.IsBad(result.StatusCode))
                {
                    if (item.EuType < 0 && result.StatusCode == StatusCodes.BadNoMatch)
                    {
                        item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
                    }

                    continue;
                }

                if (result.Targets.Count == 0 || result.Targets[0].TargetId.IsAbsolute)
                {
                    if (item.EuType < 0)
                    {
                        item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_NOENUM;
                    }

                    continue;
                }

                ReadValueId propertyToRead = new ReadValueId();
                propertyToRead.NodeId      = (NodeId)result.Targets[0].TargetId;
                propertyToRead.AttributeId = Attributes.Value;
                propertyToRead.Handle      = item;
                propertiesToRead.Add(propertyToRead);

                if (browsePaths[ii].RelativePath.Elements[0].TargetName.Name == Opc.Ua.BrowseNames.EURange)
                {
                    item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_ANALOG;
                }
                else
                {
                    item.EuType = (int)OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED;
                }
            }

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

            // read attribute values from the server.
            DataValueCollection values = null;

            try
            {
                session.Read(
                    null,
                    0,
                    TimestampsToReturn.Neither,
                    propertiesToRead,
                    out values,
                    out diagnosticInfos);

                ClientBase.ValidateResponse(values, propertiesToRead);
                ClientBase.ValidateDiagnosticInfos(diagnosticInfos, propertiesToRead);
            }
            catch (Exception)
            {
                for (int ii = 0; ii < propertiesToRead.Count; ii++)
                {
                    ComDaGroupItem item = (ComDaGroupItem)propertiesToRead[ii].Handle;
                    item.EuType = 0;
                }

                return;
            }

            // process results.
            for (int ii = 0; ii < values.Count; ii++)
            {
                ComDaGroupItem item = (ComDaGroupItem)propertiesToRead[ii].Handle;

                if (StatusCode.IsBad(values[ii].StatusCode))
                {
                    item.EuType = 0;
                    continue;
                }

                if (item.EuType == (int)OpcRcw.Da.OPCEUTYPE.OPC_ANALOG)
                {
                    Range range = (Range)values[ii].GetValue <Range>(null);

                    if (range == null)
                    {
                        item.EuType = 0;
                        continue;
                    }

                    item.EuInfo = new double[] { range.Low, range.High };
                    continue;
                }

                if (item.EuType == (int)OpcRcw.Da.OPCEUTYPE.OPC_ENUMERATED)
                {
                    LocalizedText[] texts = (LocalizedText[])values[ii].GetValue <LocalizedText[]>(null);

                    if (texts == null)
                    {
                        item.EuType = 0;
                        continue;
                    }

                    string[] strings = new string[texts.Length];

                    for (int jj = 0; jj < strings.Length; jj++)
                    {
                        if (!LocalizedText.IsNullOrEmpty(texts[jj]))
                        {
                            strings[jj] = texts[jj].Text;
                        }
                    }

                    item.EuInfo = strings;
                    continue;
                }
            }
        }
        /// <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);
                }
            }
        }
Exemple #8
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);
        }
Exemple #9
0
        public ApplicationRecordDataType ShowDialog(IWin32Window owner, IList <ApplicationRecordDataType> records, NodeId defaultRecord)
        {
            ApplicationsTable.Rows.Clear();

            DataRow selectedRow = null;

            if (records != null)
            {
                foreach (var record in records)
                {
                    DataRow row = ApplicationsTable.NewRow();

                    if (selectedRow == null && defaultRecord != null)
                    {
                        if (defaultRecord == record.ApplicationId)
                        {
                            selectedRow = row;
                        }
                    }

                    row[0] = record.ApplicationId;
                    row[1] = (record.ApplicationNames != null && record.ApplicationNames.Count > 0 && !LocalizedText.IsNullOrEmpty(record.ApplicationNames[0]))?record.ApplicationNames[0].Text:String.Empty;
                    row[2] = record.ApplicationType;
                    row[3] = record.ProductUri;

                    StringBuilder buffer = new StringBuilder();

                    if (record.DiscoveryUrls != null)
                    {
                        foreach (var url in record.DiscoveryUrls)
                        {
                            if (buffer.Length > 0)
                            {
                                buffer.Append(',');
                            }

                            buffer.Append(url);
                        }
                    }

                    row[4] = buffer.ToString();

                    buffer = new StringBuilder();

                    if (record.ServerCapabilities != null)
                    {
                        foreach (var id in record.ServerCapabilities)
                        {
                            if (buffer.Length > 0)
                            {
                                buffer.Append(',');
                            }

                            buffer.Append(id);
                        }
                    }

                    row[5] = buffer.ToString();
                    row[6] = record;

                    ApplicationsTable.Rows.Add(row);
                }

                m_dataset.AcceptChanges();
            }

            if (selectedRow != null)
            {
                foreach (DataGridViewRow row in ApplicationRecordDataGridView.Rows)
                {
                    DataRowView source = row.DataBoundItem as DataRowView;

                    if (Object.ReferenceEquals(source.Row, selectedRow))
                    {
                        row.Selected = true;
                        break;
                    }
                }
            }

            if (base.ShowDialog(owner) != DialogResult.OK)
            {
                return(null);
            }

            if (ApplicationRecordDataGridView.SelectedRows.Count > 0)
            {
                DataRowView source = ApplicationRecordDataGridView.SelectedRows[0].DataBoundItem as DataRowView;
                return((ApplicationRecordDataType)source.Row[6]);
            }

            return(null);
        }
        private void DiscoveryTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (RootFolders.LocalMachine.Equals(e.Node.Tag))
                {
                    ServersTable.Rows.Clear();
                    ShowPanel(true);

                    if (e.Node.Nodes.Count == 1 && String.IsNullOrEmpty(e.Node.Nodes[0].Text))
                    {
                        e.Node.Nodes.Clear();

                        m_lds.BeginFindServers(
                            OnFindServersComplete,
                            new ExpandNodeData()
                        {
                            Parent = e.Node, Lds = m_lds
                        });
                    }
                    else
                    {
                        ShowApplicationDescriptions(e.Node.Nodes);
                    }

                    return;
                }

                if (RootFolders.LocalNetwork.Equals(e.Node.Tag))
                {
                    ServersTable.Rows.Clear();
                    ShowPanel(true);

                    if (e.Node.Nodes.Count == 1 && String.IsNullOrEmpty(e.Node.Nodes[0].Text))
                    {
                        e.Node.Nodes.Clear();

                        m_lds.BeginFindServersOnNetwork(
                            0,
                            1000,
                            OnFindServersOnNetworkComplete,
                            new ExpandNodeData()
                        {
                            Parent = e.Node, Lds = m_lds
                        });
                    }
                    else
                    {
                        ShowServerOnNetworks(e.Node.Nodes);
                    }

                    return;
                }

                if (RootFolders.GlobalDiscovery.Equals(e.Node.Tag))
                {
                    ServersTable.Rows.Clear();
                    ShowPanel(true);

                    if (e.Node.Nodes.Count == 1 && String.IsNullOrEmpty(e.Node.Nodes[0].Text))
                    {
                        e.Node.Nodes.Clear();

                        var servers = new ViewServersOnNetworkDialog(m_gds).ShowDialog(this, ref m_filters);

                        if (servers != null)
                        {
                            foreach (var server in servers)
                            {
                                TreeNode node = new TreeNode(String.Format("{0}", server.ServerName));
                                node.SelectedImageIndex = node.ImageIndex = ImageIndex.Server;
                                node.Tag = server;
                                node.Nodes.Add(new TreeNode());
                                e.Node.Nodes.Add(node);
                            }
                        }
                    }

                    ShowServerOnNetworks(e.Node.Nodes);

                    return;
                }

                if (RootFolders.CustomDiscovery.Equals(e.Node.Tag))
                {
                    ServersTable.Rows.Clear();
                    ShowPanel(true);
                    return;
                }

                if (e.Node.Tag is ApplicationDescription)
                {
                    EndpointsTable.Rows.Clear();
                    ShowPanel(false);

                    ApplicationDescription application = (ApplicationDescription)e.Node.Tag;

                    ApplicationNameTextBox.Text = (LocalizedText.IsNullOrEmpty(application.ApplicationName))?"---":application.ApplicationName.Text;
                    ApplicationTypeTextBox.Text = application.ApplicationType.ToString();
                    ApplicationUriTextBox.Text  = application.ApplicationUri;
                    ProductUriTextBox.Text      = application.ProductUri;

                    string discoveryUrl = SelectDiscoveryUrl(application);

                    if (discoveryUrl != null)
                    {
                        m_lds.BeginGetEndpoints(
                            discoveryUrl,
                            null,
                            OnGetEndpointsComplete,
                            new GetEndpointsData()
                        {
                            Parent = e.Node, Lds = m_lds
                        });
                    }
                }

                if (e.Node.Tag is ServerOnNetwork)
                {
                    EndpointsTable.Rows.Clear();
                    ShowPanel(false);

                    ServerOnNetwork server = (ServerOnNetwork)e.Node.Tag;

                    ApplicationNameTextBox.Text = server.ServerName;
                    ApplicationTypeTextBox.Text = "---";
                    ApplicationUriTextBox.Text  = "---";
                    ProductUriTextBox.Text      = "---";

                    try
                    {
                        Cursor = Cursors.WaitCursor;

                        m_lds.BeginGetEndpoints(
                            server.DiscoveryUrl,
                            null,
                            OnGetEndpointsComplete,
                            new GetEndpointsData()
                        {
                            Parent = e.Node, Lds = m_lds
                        });
                    }
                    finally
                    {
                        Cursor = Cursors.Default;
                    }
                }

                if (e.Node.Tag is ConfiguredEndpoint)
                {
                    EndpointsTable.Rows.Clear();
                    ShowPanel(false);

                    ConfiguredEndpoint server = (ConfiguredEndpoint)e.Node.Tag;

                    ApplicationNameTextBox.Text = "---";
                    ApplicationTypeTextBox.Text = "---";
                    ApplicationUriTextBox.Text  = "---";
                    ProductUriTextBox.Text      = "---";

                    m_lds.BeginGetEndpoints(
                        server.EndpointUrl.ToString(),
                        null,
                        OnGetEndpointsComplete,
                        new GetEndpointsData()
                    {
                        Parent = e.Node, Lds = m_lds
                    });
                }
            }
            catch (Exception ex)
            {
                Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex);
            }
        }
        /// <summary>
        /// Recursively populates the event types table.
        /// </summary>
        private void IndexTypesFromServer(NodeId baseTypeId, int eventType)
        {
            // check if event type needs to be revised.
            if (baseTypeId == Opc.Ua.ObjectTypeIds.ConditionType)
            {
                eventType = OpcRcw.Ae.Constants.CONDITION_EVENT;
            }

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

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

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

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

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

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

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

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

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

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

                // recursively look for subtypes.
                IndexTypesFromServer(typeId, eventType);
            }
        }
        /// <summary>
        /// Indexes the well known subtypes.
        /// </summary>
        private void IndexWellKnownTypes()
        {
            SystemContext context = new SystemContext();

            context.EncodeableFactory = m_session.MessageContext.Factory;
            context.NamespaceUris     = m_session.NamespaceUris;
            context.ServerUris        = m_session.ServerUris;

            NodeStateCollection predefinedNodes = new NodeStateCollection();

            predefinedNodes.LoadFromBinaryResource(context, "Opc.Ua.Stack.Generated.Opc.Ua.PredefinedNodes.uanodes", typeof(NodeState).Assembly, true);

            NodeIdDictionary <BaseTypeState> types = new NodeIdDictionary <BaseTypeState>();

            // collect the instance declarations for all types.
            for (int ii = 0; ii < predefinedNodes.Count; ii++)
            {
                BaseTypeState type = predefinedNodes[ii] as BaseTypeState;

                if (type != null)
                {
                    types.Add(type.NodeId, type);
                }
            }

            // index only those types which are subtypes of BaseEventType.
            foreach (BaseTypeState type in types.Values)
            {
                BaseTypeState subType   = type;
                BaseTypeState superType = null;

                int eventType = 0;

                while (subType != null)
                {
                    if (subType.NodeId == Opc.Ua.ObjectTypeIds.ConditionType || subType.SuperTypeId == Opc.Ua.ObjectTypeIds.ConditionType)
                    {
                        eventType = OpcRcw.Ae.Constants.CONDITION_EVENT;
                    }

                    else if (subType.NodeId == Opc.Ua.ObjectTypeIds.AuditEventType || subType.SuperTypeId == Opc.Ua.ObjectTypeIds.AuditEventType)
                    {
                        eventType = OpcRcw.Ae.Constants.TRACKING_EVENT;
                    }

                    else if (subType.NodeId == Opc.Ua.ObjectTypeIds.BaseEventType || subType.SuperTypeId == Opc.Ua.ObjectTypeIds.BaseEventType)
                    {
                        eventType = OpcRcw.Ae.Constants.SIMPLE_EVENT;
                    }

                    // found an event, collect the attribute and index it.
                    if (eventType != 0)
                    {
                        List <AeEventAttribute> declarations      = new List <AeEventAttribute>();
                        Dictionary <string, AeEventAttribute> map = new Dictionary <string, AeEventAttribute>();

                        ComAeUtils.CollectInstanceDeclarations(
                            m_session,
                            this,
                            type,
                            null,
                            declarations,
                            map);

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

                    // follow the tree to the parent.
                    if (!types.TryGetValue(subType.SuperTypeId, out superType))
                    {
                        break;
                    }

                    subType = superType;
                }
            }

            // hide the built in attributes.
            AeEventCategory category = GetCategory(Opc.Ua.ObjectTypeIds.BaseEventType);

            if (category != null)
            {
                for (int ii = 0; ii < category.Attributes.Count; ii++)
                {
                    switch (category.Attributes[ii].BrowsePathDisplayText)
                    {
                    case Opc.Ua.BrowseNames.Message:
                    case Opc.Ua.BrowseNames.Severity:
                    case Opc.Ua.BrowseNames.SourceName:
                    case Opc.Ua.BrowseNames.Time:
                    case Opc.Ua.BrowseNames.ReceiveTime:
                    case Opc.Ua.BrowseNames.LocalTime:
                    {
                        category.Attributes[ii].Hidden = true;
                        break;
                    }
                    }
                }
            }
        }
Exemple #13
0
        public 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");
                }
            }
            else
            {
                if (application.DiscoveryUrls != null && application.DiscoveryUrls.Count > 0)
                {
                    throw new ArgumentException("DiscoveryUrls must not be specified for clients.", "DiscoveryUrls");
                }
            }

            StringBuilder capabilities = new StringBuilder();

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

                    if (capabilities.Length > 0)
                    {
                        capabilities.Append(',');
                    }

                    capabilities.Append(capability);
                }
            }

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

            Guid applicationId = Guid.Empty;

            if (!NodeId.IsNull(application.ApplicationId))
            {
                if (application.ApplicationId.IdType != IdType.Guid)
                {
                    throw new ArgumentException("The ApplicationId to does refer to a existing record.", "ApplicationId");
                }

                applicationId = (Guid)application.ApplicationId.Identifier;
            }

            using (gdsdbEntities entities = new gdsdbEntities())
            {
                Application record = null;

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

                    record = results.SingleOrDefault();

                    if (record != null)
                    {
                        var endpoints = from ii in entities.ServerEndpoints
                                        where ii.ApplicationId == record.ID
                                        select ii;

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

                        var names = from ii in entities.ApplicationNames
                                    where ii.ApplicationId == record.ID
                                    select ii;

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

                        entities.SaveChanges();
                    }
                }

                bool isNew = false;

                if (record == null)
                {
                    record = new Application()
                    {
                        ApplicationId = Guid.NewGuid()
                    };
                    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)
                {
                    entities.Applications.Add(record);
                }

                entities.SaveChanges();

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

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

                entities.SaveChanges();

                return(new NodeId(record.ApplicationId, NamespaceIndex));
            }
        }
Exemple #14
0
        /// <summary>
        /// Marshals an event for return to the client.
        /// </summary>
        private OpcRcw.Ae.ONEVENTSTRUCT Translate(AeEvent e)
        {
            OpcRcw.Ae.ONEVENTSTRUCT e2 = new ONEVENTSTRUCT();

            e2.wNewState       = 0;
            e2.wChangeMask     = 0xFF;
            e2.szSource        = e.SourceName;
            e2.wQuality        = ComUtils.GetQualityCode(e.Quality);
            e2.dwEventType     = e.Category.EventType;
            e2.dwEventCategory = (int)e.Category.LocalId;
            e2.bAckRequired    = 0;
            e2.dwSeverity      = e.Severity;
            e2.ftTime          = ComUtils.GetFILETIME(e.Time);
            e2.szMessage       = (e.Message != null) ? e.Message.Text : null;
            e2.szActorID       = e.AuditUserId;
            e2.dwCookie        = e.Cookie;

            if (e.AttributeValues != null && e.AttributeValues.Length > 0)
            {
                e2.dwNumEventAttrs  = e.AttributeValues.Length;
                e2.pEventAttributes = ComUtils.GetVARIANTs(e.AttributeValues, true);
            }

            if ((e2.dwEventType & OpcRcw.Ae.Constants.CONDITION_EVENT) != 0)
            {
                e2.szConditionName = e.ConditionName;
                e2.ftActiveTime    = ComUtils.GetFILETIME(e.ActiveTime);
                e2.bAckRequired    = (e.AckedState)?0:1;

                // set the condition state.
                e2.wNewState = 0;

                if (e.EnabledState)
                {
                    e2.wNewState |= OpcRcw.Ae.Constants.CONDITION_ENABLED;
                }

                if (e.AckedState)
                {
                    e2.wNewState |= OpcRcw.Ae.Constants.CONDITION_ACKED;
                }

                if (e.ActiveState)
                {
                    e2.wNewState |= OpcRcw.Ae.Constants.CONDITION_ACTIVE;
                }

                // set the subcondition if available.
                if (!LocalizedText.IsNullOrEmpty(e.LowState))
                {
                    e2.szSubconditionName = e.LowState.Text;
                }

                if (!LocalizedText.IsNullOrEmpty(e.HighState))
                {
                    e2.szSubconditionName = e.HighState.Text;
                }

                if (!LocalizedText.IsNullOrEmpty(e.LowLowState))
                {
                    e2.szSubconditionName = e.LowLowState.Text;
                }

                if (!LocalizedText.IsNullOrEmpty(e.HighHighState))
                {
                    e2.szSubconditionName = e.HighHighState.Text;
                }

                if (!LocalizedText.IsNullOrEmpty(e.LimitState))
                {
                    e2.szSubconditionName = e.LimitState.Text;
                }
            }

            if (e2.szMessage == null)
            {
                e2.szMessage = String.Empty;
            }
            if (e2.szSource == null)
            {
                e2.szSource = String.Empty;
            }
            if (e2.szConditionName == null)
            {
                e2.szConditionName = String.Empty;
            }
            if (e2.szSubconditionName == null)
            {
                e2.szSubconditionName = String.Empty;
            }
            if (e2.szActorID == null)
            {
                e2.szActorID = String.Empty;
            }

            return(e2);
        }
        /// <summary>
        /// Collects instance declarations nodes from with a type.
        /// </summary>
        public static void CollectInstanceDeclarations(
            Session session,
            ComNamespaceMapper mapper,
            NodeState node,
            AeEventAttribute parent,
            List <AeEventAttribute> instances,
            IDictionary <string, AeEventAttribute> map)
        {
            List <BaseInstanceState> children = new List <BaseInstanceState>();

            node.GetChildren(session.SystemContext, children);

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

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

                // only interested in objects and variables.
                if (instance.NodeClass != NodeClass.Object && instance.NodeClass != NodeClass.Variable)
                {
                    return;
                }

                // ignore instances without a modelling rule.
                if (NodeId.IsNull(instance.ModellingRuleId))
                {
                    return;
                }

                // create a new declaration.
                AeEventAttribute declaration = new AeEventAttribute();

                declaration.RootTypeId  = (parent != null)?parent.RootTypeId:node.NodeId;
                declaration.NodeId      = (NodeId)instance.NodeId;
                declaration.BrowseName  = instance.BrowseName;
                declaration.NodeClass   = instance.NodeClass;
                declaration.Description = (instance.Description != null)?instance.Description.ToString():null;

                // get data type information.
                BaseVariableState variable = instance as BaseVariableState;

                if (variable != null)
                {
                    declaration.DataType  = variable.DataType;
                    declaration.ValueRank = variable.ValueRank;

                    if (!NodeId.IsNull(variable.DataType))
                    {
                        declaration.BuiltInType = DataTypes.GetBuiltInType(declaration.DataType, session.TypeTree);
                    }
                }

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

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

                declaration.BrowsePath.Add(instance.BrowseName);

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

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

                map[declaration.BrowsePathDisplayText] = declaration;

                // only interested in variables.
                if (instance.NodeClass == NodeClass.Variable)
                {
                    instances.Add(declaration);
                }

                // recusively build tree.
                CollectInstanceDeclarations(session, mapper, instance, declaration, instances, map);
            }
        }
        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)
                {
                    throw new ArgumentException("At least one Server Capability must be provided.", "ServerCapabilities");
                }
            }
            else
            {
                if (application.DiscoveryUrls != null && application.DiscoveryUrls.Count > 0)
                {
                    throw new ArgumentException("DiscoveryUrls must not be specified for clients.", "DiscoveryUrls");
                }
            }

            Guid applicationId = Guid.Empty;

            if (!NodeId.IsNull(application.ApplicationId))
            {
                if (application.ApplicationId.IdType != IdType.Guid)
                {
                    throw new ArgumentException("The ApplicationId has not the type Guid.", "ApplicationId");
                }

                applicationId = (Guid)application.ApplicationId.Identifier;
            }

            return(new NodeId(applicationId, NamespaceIndex));
        }