/// <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());
        }
        /// <summary>
        /// Method to remove the node from the subscription and stop publishing telemetry to IoTHub. Executes synchronously.
        /// </summary>
        private ServiceResult OnUnpublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            string logPrefix = "OnUnpublishNodeCall:";

            if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
            {
                Logger.Error($"{logPrefix} Invalid arguments!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments!"));
            }

            HttpStatusCode statusCode     = HttpStatusCode.InternalServerError;
            NodeId         nodeId         = null;
            ExpandedNodeId expandedNodeId = null;
            Uri            endpointUri    = null;
            bool           isNodeIdFormat = true;

            try
            {
                string id = inputArguments[0] as string;
                if (id.Contains("nsu=", StringComparison.InvariantCulture))
                {
                    expandedNodeId = ExpandedNodeId.Parse(id);
                    isNodeIdFormat = false;
                }
                else
                {
                    nodeId         = NodeId.Parse(id);
                    isNodeIdFormat = true;
                }
                endpointUri = new Uri(inputArguments[1] as string);
            }
            catch (UriFormatException)
            {
                Logger.Error($"{logPrefix} The endpointUrl is invalid '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{logPrefix} The NodeId has an invalid format '{inputArguments[0] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in NodeId or ExpandedNodeId format as first argument!"));
            }

            // find the session and stop monitoring the node.
            try
            {
                OpcSessionsListSemaphore.Wait();
                if (ShutdownTokenSource.IsCancellationRequested)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                try
                {
                    opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUrl.Equals(endpointUri.OriginalString, StringComparison.OrdinalIgnoreCase));
                }
                catch
                {
                    opcSession = null;
                }

                if (opcSession == null)
                {
                    // do nothing if there is no session for this endpoint.
                    Logger.Error($"{logPrefix} Session for endpoint '{endpointUri.OriginalString}' not found.");
                    return(ServiceResult.Create(StatusCodes.BadSessionIdInvalid, "Session for endpoint of node to unpublished not found!"));
                }
                else
                {
                    if (isNodeIdFormat)
                    {
                        // stop monitoring the node, execute syncronously
                        Logger.Information($"{logPrefix} Request to stop monitoring item with NodeId '{nodeId.ToString()}')");
                        statusCode = opcSession.RequestMonitorItemRemovalAsync(nodeId, null, ShutdownTokenSource.Token).Result;
                    }
                    else
                    {
                        // stop monitoring the node, execute syncronously
                        Logger.Information($"{logPrefix} Request to stop monitoring item with ExpandedNodeId '{expandedNodeId.ToString()}')");
                        statusCode = opcSession.RequestMonitorItemRemovalAsync(null, expandedNodeId, ShutdownTokenSource.Token).Result;
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{logPrefix} Exception while trying to configure publishing node '{nodeId.ToString()}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error unpublishing node: {e.Message}"));
            }
            finally
            {
                OpcSessionsListSemaphore.Release();
            }
            return(statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted ? ServiceResult.Good : ServiceResult.Create(StatusCodes.Bad, "Can not stop monitoring node!"));
        }
Beispiel #3
0
        private async void ShowMember(NodeId sourceId)
        {
            textBox_nodeId.Text = sourceId.ToString();

            // dataGridView1.Rows.Clear();
            int index = 0;
            ReferenceDescriptionCollection references;

            try
            {
                references = await Task.Run(() =>
                {
                    return(GetReferenceDescriptionCollection(sourceId));
                });
            }
            catch (Exception exception)
            {
                ClientUtils.HandleException(Text, exception);
                return;
            }


            if (references?.Count > 0)
            {
                // 获取所有要读取的子节点
                List <NodeId> nodeIds = new List <NodeId>();
                for (int ii = 0; ii < references.Count; ii++)
                {
                    ReferenceDescription target = references[ii];
                    nodeIds.Add((NodeId)target.NodeId);
                }

                DateTime dateTimeStart = DateTime.Now;

                // 获取所有的值
                DataValue[] dataValues = await Task.Run(() =>
                {
                    return(ReadOneNodeFiveAttributes(nodeIds));
                });

                label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";

                // 显示
                for (int jj = 0; jj < dataValues.Length; jj += 5)
                {
                    AddDataGridViewNewRow(dataValues, jj, index++, nodeIds[jj / 5]);
                }
            }
            else
            {
                // 子节点没有数据的情况
                try
                {
                    DateTime  dateTimeStart = DateTime.Now;
                    DataValue dataValue     = m_OpcUaClient.ReadNode(sourceId);

                    if (dataValue.WrappedValue.TypeInfo?.ValueRank == ValueRanks.OneDimension)
                    {
                        // 数组显示
                        AddDataGridViewArrayRow(sourceId, out index);
                    }
                    else
                    {
                        // 显示单个数本身
                        label_time_spend.Text = (int)(DateTime.Now - dateTimeStart).TotalMilliseconds + " ms";
                        AddDataGridViewNewRow(ReadOneNodeFiveAttributes(new List <NodeId>()
                        {
                            sourceId
                        }), 0, index++, sourceId);
                    }
                }
                catch (Exception exception)
                {
                    ClientUtils.HandleException(Text, exception);
                    return;
                }
            }

            ClearDataGridViewRows(index);
        }
        private async Task RequestNewCertificatePullMode(object sender, EventArgs e)
        {
            try
            {
                // check if we already have a private key
                NodeId requestId = null;
                if (!string.IsNullOrEmpty(m_application.CertificateStorePath))
                {
                    CertificateIdentifier id = new CertificateIdentifier
                    {
                        StoreType   = CertificateStoreIdentifier.DetermineStoreType(m_application.CertificateStorePath),
                        StorePath   = m_application.CertificateStorePath,
                        SubjectName = m_application.CertificateSubjectName.Replace("localhost", Utils.GetHostName())
                    };
                    m_certificate = await id.Find(true);

                    if (m_certificate != null &&
                        m_certificate.HasPrivateKey)
                    {
                        m_certificate = await id.LoadPrivateKey(m_certificatePassword);
                    }
                }

                bool hasPrivateKeyFile = false;
                if (!string.IsNullOrEmpty(m_application.CertificatePrivateKeyPath))
                {
                    FileInfo file = new FileInfo(m_application.CertificatePrivateKeyPath);
                    hasPrivateKeyFile = file.Exists;
                }

                var domainNames = m_application.GetDomainNames(m_certificate);
                if (m_certificate == null)
                {
                    // no private key
                    requestId = m_gds.StartNewKeyPairRequest(
                        m_application.ApplicationId,
                        null,
                        null,
                        m_application.CertificateSubjectName.Replace("localhost", Utils.GetHostName()),
                        domainNames,
                        "PFX",
                        m_certificatePassword);
                }
                else
                {
                    X509Certificate2 csrCertificate = null;
                    if (m_certificate.HasPrivateKey)
                    {
                        csrCertificate = m_certificate;
                    }
                    else
                    {
                        string absoluteCertificatePrivateKeyPath = Utils.GetAbsoluteFilePath(m_application.CertificatePrivateKeyPath, true, false, false);
                        byte[] pkcsData = File.ReadAllBytes(absoluteCertificatePrivateKeyPath);
                        if (m_application.GetPrivateKeyFormat(m_server?.GetSupportedKeyFormats()) == "PFX")
                        {
                            csrCertificate = CertificateFactory.CreateCertificateFromPKCS12(pkcsData, m_certificatePassword);
                        }
                        else
                        {
                            csrCertificate = CertificateFactory.CreateCertificateWithPEMPrivateKey(m_certificate, pkcsData, m_certificatePassword);
                        }
                    }
                    byte[] certificateRequest = CertificateFactory.CreateSigningRequest(csrCertificate, domainNames);
                    requestId = m_gds.StartSigningRequest(m_application.ApplicationId, null, null, certificateRequest);
                }

                m_application.CertificateRequestId = requestId.ToString();
                CertificateRequestTimer.Enabled    = true;
                RequestProgressLabel.Visible       = true;
                WarningLabel.Visible = false;
            }
            catch (Exception ex)
            {
                Opc.Ua.Client.Controls.ExceptionDlg.Show(Text, ex);
            }
        }
Beispiel #5
0
 private void RegisterTypes(IRedisPipeline p)
 {
     foreach (var typeName in TypeNames)
     {
         p.QueueCommand(q => q.Set("{0}:req:{1}:{2}".Fmt(RedisPrefix, typeName, NodeId.ToString()), HostContext.AppHost.Config.WebHostUrl, NodeTimeoutPeriod));
     }
 }
            private async Task FindObjects(Opc.Ua.Client.Session session, NodeId nodeid)
            {
                if (session == null)
                {
                    return;
                }

                try
                {
                    ReferenceDescriptionCollection references;
                    Byte[] continuationPoint;

                    if (NodeIdsFromObjects.Contains(nodeid.ToString()))
                    {
                        return;
                    }

                    session.Browse(
                        null,
                        null,
                        nodeid,
                        0u,
                        BrowseDirection.Forward,
                        ReferenceTypeIds.HierarchicalReferences,
                        true,
                        (uint)NodeClass.Variable | (uint)NodeClass.Object,
                        out continuationPoint,
                        out references);

                    foreach (var rd in references)
                    {
                        Log(conn_name + " - " + rd.NodeId + ", " + rd.DisplayName + ", " + rd.BrowseName + ", " + rd.NodeClass);
                        if (rd.NodeClass == NodeClass.Variable && !NodeIds.Contains(rd.NodeId.ToString()))
                        {
                            NodeIds.Add(rd.NodeId.ToString());
                            ListMon.Add(
                                new MonitoredItem()
                            {
                                DisplayName      = rd.DisplayName.ToString(),
                                StartNodeId      = rd.NodeId.ToString(),
                                SamplingInterval = System.Convert.ToInt32(System.Convert.ToDouble(OPCUA_conn.autoCreateTagSamplingInterval) * 1000),
                                QueueSize        = System.Convert.ToUInt32(OPCUA_conn.autoCreateTagQueueSize),
                                MonitoringMode   = MonitoringMode.Reporting,
                                DiscardOldest    = true,
                                AttributeId      = Attributes.Value
                            });
                        }
                        else
                        if (rd.NodeClass == NodeClass.Object)
                        {
                            NodeIdsFromObjects.Add(nodeid.ToString());
                            await FindObjects(session, ExpandedNodeId.ToNodeId(rd.NodeId, session.NamespaceUris));

                            Thread.Yield();
                            //Thread.Sleep(1);
                            //await Task.Delay(1);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Log(conn_name + " - " + ex.Message);
                }
            }
Beispiel #7
0
        /// <exception cref="System.Exception"/>
        private void TestNMTokens(Configuration conf)
        {
            NMTokenSecretManagerInRM nmTokenSecretManagerRM = yarnCluster.GetResourceManager(
                ).GetRMContext().GetNMTokenSecretManager();
            NMTokenSecretManagerInNM nmTokenSecretManagerNM = yarnCluster.GetNodeManager(0).GetNMContext
                                                                  ().GetNMTokenSecretManager();
            RMContainerTokenSecretManager containerTokenSecretManager = yarnCluster.GetResourceManager
                                                                            ().GetRMContext().GetContainerTokenSecretManager();
            NodeManager nm = yarnCluster.GetNodeManager(0);

            WaitForNMToReceiveNMTokenKey(nmTokenSecretManagerNM, nm);
            // Both id should be equal.
            NUnit.Framework.Assert.AreEqual(nmTokenSecretManagerNM.GetCurrentKey().GetKeyId()
                                            , nmTokenSecretManagerRM.GetCurrentKey().GetKeyId());

            /*
             * Below cases should be tested.
             * 1) If Invalid NMToken is used then it should be rejected.
             * 2) If valid NMToken but belonging to another Node is used then that
             * too should be rejected.
             * 3) NMToken for say appAttempt-1 is used for starting/stopping/retrieving
             * status for container with containerId for say appAttempt-2 should
             * be rejected.
             * 4) After start container call is successful nmtoken should have been
             * saved in NMTokenSecretManagerInNM.
             * 5) If start container call was successful (no matter if container is
             * still running or not), appAttempt->NMToken should be present in
             * NMTokenSecretManagerInNM's cache. Any future getContainerStatus call
             * for containerId belonging to that application attempt using
             * applicationAttempt's older nmToken should not get any invalid
             * nmToken error. (This can be best tested if we roll over NMToken
             * master key twice).
             */
            YarnRPC              rpc               = YarnRPC.Create(conf);
            string               user              = "******";
            Resource             r                 = Resource.NewInstance(1024, 1);
            ApplicationId        appId             = ApplicationId.NewInstance(1, 1);
            ApplicationAttemptId validAppAttemptId = ApplicationAttemptId.NewInstance(appId,
                                                                                      1);
            ContainerId validContainerId = ContainerId.NewContainerId(validAppAttemptId, 0);
            NodeId      validNode        = yarnCluster.GetNodeManager(0).GetNMContext().GetNodeId();
            NodeId      invalidNode      = NodeId.NewInstance("InvalidHost", 1234);
            Token       validNMToken     = nmTokenSecretManagerRM.CreateNMToken(validAppAttemptId, validNode
                                                                                , user);
            Token validContainerToken = containerTokenSecretManager.CreateContainerToken(validContainerId
                                                                                         , validNode, user, r, Priority.NewInstance(10), 1234);
            ContainerTokenIdentifier identifier = BuilderUtils.NewContainerTokenIdentifier(validContainerToken
                                                                                           );

            NUnit.Framework.Assert.AreEqual(Priority.NewInstance(10), identifier.GetPriority(
                                                ));
            NUnit.Framework.Assert.AreEqual(1234, identifier.GetCreationTime());
            StringBuilder sb;
            // testInvalidNMToken ... creating NMToken using different secret manager.
            NMTokenSecretManagerInRM tempManager = new NMTokenSecretManagerInRM(conf);

            tempManager.RollMasterKey();
            do
            {
                tempManager.RollMasterKey();
                tempManager.ActivateNextMasterKey();
            }while (tempManager.GetCurrentKey().GetKeyId() == nmTokenSecretManagerRM.GetCurrentKey
                        ().GetKeyId());
            // Making sure key id is different.
            // Testing that NM rejects the requests when we don't send any token.
            if (UserGroupInformation.IsSecurityEnabled())
            {
                sb = new StringBuilder("Client cannot authenticate via:[TOKEN]");
            }
            else
            {
                sb = new StringBuilder("SIMPLE authentication is not enabled.  Available:[TOKEN]"
                                       );
            }
            string errorMsg = TestStartContainer(rpc, validAppAttemptId, validNode, validContainerToken
                                                 , null, true);

            NUnit.Framework.Assert.IsTrue(errorMsg.Contains(sb.ToString()));
            Token invalidNMToken = tempManager.CreateNMToken(validAppAttemptId, validNode, user
                                                             );

            sb = new StringBuilder("Given NMToken for application : ");
            sb.Append(validAppAttemptId.ToString()).Append(" seems to have been generated illegally."
                                                           );
            NUnit.Framework.Assert.IsTrue(sb.ToString().Contains(TestStartContainer(rpc, validAppAttemptId
                                                                                    , validNode, validContainerToken, invalidNMToken, true)));
            // valid NMToken but belonging to other node
            invalidNMToken = nmTokenSecretManagerRM.CreateNMToken(validAppAttemptId, invalidNode
                                                                  , user);
            sb = new StringBuilder("Given NMToken for application : ");
            sb.Append(validAppAttemptId).Append(" is not valid for current node manager.expected : "
                                                ).Append(validNode.ToString()).Append(" found : ").Append(invalidNode.ToString()
                                                                                                          );
            NUnit.Framework.Assert.IsTrue(sb.ToString().Contains(TestStartContainer(rpc, validAppAttemptId
                                                                                    , validNode, validContainerToken, invalidNMToken, true)));
            // using correct tokens. nmtoken for app attempt should get saved.
            conf.SetInt(YarnConfiguration.RmContainerAllocExpiryIntervalMs, 4 * 60 * 1000);
            validContainerToken = containerTokenSecretManager.CreateContainerToken(validContainerId
                                                                                   , validNode, user, r, Priority.NewInstance(0), 0);
            NUnit.Framework.Assert.IsTrue(TestStartContainer(rpc, validAppAttemptId, validNode
                                                             , validContainerToken, validNMToken, false).IsEmpty());
            NUnit.Framework.Assert.IsTrue(nmTokenSecretManagerNM.IsAppAttemptNMTokenKeyPresent
                                              (validAppAttemptId));
            // using a new compatible version nmtoken, expect container can be started
            // successfully.
            ApplicationAttemptId validAppAttemptId2 = ApplicationAttemptId.NewInstance(appId,
                                                                                       2);
            ContainerId validContainerId2    = ContainerId.NewContainerId(validAppAttemptId2, 0);
            Token       validContainerToken2 = containerTokenSecretManager.CreateContainerToken(validContainerId2
                                                                                                , validNode, user, r, Priority.NewInstance(0), 0);
            Token validNMToken2 = nmTokenSecretManagerRM.CreateNMToken(validAppAttemptId2, validNode
                                                                       , user);
            // First, get a new NMTokenIdentifier.
            NMTokenIdentifier newIdentifier = new NMTokenIdentifier();

            byte[]          tokenIdentifierContent = ((byte[])validNMToken2.GetIdentifier().Array());
            DataInputBuffer dib = new DataInputBuffer();

            dib.Reset(tokenIdentifierContent, tokenIdentifierContent.Length);
            newIdentifier.ReadFields(dib);
            // Then, generate a new version NMTokenIdentifier (NMTokenIdentifierNewForTest)
            // with additional field of message.
            NMTokenIdentifierNewForTest newVersionIdentifier = new NMTokenIdentifierNewForTest
                                                                   (newIdentifier, "message");

            // check new version NMTokenIdentifier has correct info.
            NUnit.Framework.Assert.AreEqual("The ApplicationAttemptId is changed after set to "
                                            + "newVersionIdentifier", validAppAttemptId2.GetAttemptId(), newVersionIdentifier
                                            .GetApplicationAttemptId().GetAttemptId());
            NUnit.Framework.Assert.AreEqual("The message is changed after set to newVersionIdentifier"
                                            , "message", newVersionIdentifier.GetMessage());
            NUnit.Framework.Assert.AreEqual("The NodeId is changed after set to newVersionIdentifier"
                                            , validNode, newVersionIdentifier.GetNodeId());
            // create new Token based on new version NMTokenIdentifier.
            Token newVersionedNMToken = BaseNMTokenSecretManager.NewInstance(nmTokenSecretManagerRM
                                                                             .RetrievePassword(newVersionIdentifier), newVersionIdentifier);

            // Verify startContainer is successful and no exception is thrown.
            NUnit.Framework.Assert.IsTrue(TestStartContainer(rpc, validAppAttemptId2, validNode
                                                             , validContainerToken2, newVersionedNMToken, false).IsEmpty());
            NUnit.Framework.Assert.IsTrue(nmTokenSecretManagerNM.IsAppAttemptNMTokenKeyPresent
                                              (validAppAttemptId2));
            //Now lets wait till container finishes and is removed from node manager.
            WaitForContainerToFinishOnNM(validContainerId);
            sb = new StringBuilder("Attempt to relaunch the same container with id ");
            sb.Append(validContainerId);
            NUnit.Framework.Assert.IsTrue(TestStartContainer(rpc, validAppAttemptId, validNode
                                                             , validContainerToken, validNMToken, true).Contains(sb.ToString()));
            // Container is removed from node manager's memory by this time.
            // trying to stop the container. It should not throw any exception.
            TestStopContainer(rpc, validAppAttemptId, validNode, validContainerId, validNMToken
                              , false);
            // Rolling over master key twice so that we can check whether older keys
            // are used for authentication.
            RollNMTokenMasterKey(nmTokenSecretManagerRM, nmTokenSecretManagerNM);
            // Key rolled over once.. rolling over again
            RollNMTokenMasterKey(nmTokenSecretManagerRM, nmTokenSecretManagerNM);
            // trying get container status. Now saved nmToken should be used for
            // authentication... It should complain saying container was recently
            // stopped.
            sb = new StringBuilder("Container ");
            sb.Append(validContainerId);
            sb.Append(" was recently stopped on node manager");
            NUnit.Framework.Assert.IsTrue(TestGetContainer(rpc, validAppAttemptId, validNode,
                                                           validContainerId, validNMToken, true).Contains(sb.ToString()));
            // Now lets remove the container from nm-memory
            nm.GetNodeStatusUpdater().ClearFinishedContainersFromCache();
            // This should fail as container is removed from recently tracked finished
            // containers.
            sb = new StringBuilder("Container ");
            sb.Append(validContainerId.ToString());
            sb.Append(" is not handled by this NodeManager");
            NUnit.Framework.Assert.IsTrue(TestGetContainer(rpc, validAppAttemptId, validNode,
                                                           validContainerId, validNMToken, false).Contains(sb.ToString()));
            // using appAttempt-1 NMtoken for launching container for appAttempt-2 should
            // succeed.
            ApplicationAttemptId attempt2 = ApplicationAttemptId.NewInstance(appId, 2);
            Token attempt1NMToken         = nmTokenSecretManagerRM.CreateNMToken(validAppAttemptId, validNode
                                                                                 , user);
            Token newContainerToken = containerTokenSecretManager.CreateContainerToken(ContainerId
                                                                                       .NewContainerId(attempt2, 1), validNode, user, r, Priority.NewInstance(0), 0);

            NUnit.Framework.Assert.IsTrue(TestStartContainer(rpc, attempt2, validNode, newContainerToken
                                                             , attempt1NMToken, false).IsEmpty());
        }
Beispiel #8
0
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         btnNew.OnClientClick = winEdit.GetSaveStateReference(hfRefresh.ClientID) + winEdit.GetShowReference("FRM005C.aspx?Mode=New&nodeId=" + NodeId.ToString());
         BindGrid();
         btnClose.OnClientClick = ActiveWindow.GetConfirmHideReference();
     }
 }
Beispiel #9
0
        /// <summary>
        /// Event which fires before the node prop data row is written to the database
        /// </summary>
        /// <param name="IsCopy">True if the update is part of a Copy operation</param>
        public void onBeforeUpdateNodePropRow(CswNbtNode Node, bool IsCopy, bool OverrideUniqueValidation, bool Creating)
        {
            onBeforeUpdateNodePropRowLogic();
            if (false == Node.Properties[this.NodeTypeProp].Empty)  //case 26546 - we allow unique properties to be empty
            {
                //bz # 6686
                if (IsUnique() && wasAnySubFieldModified() && false == OverrideUniqueValidation)
                {
                    CswNbtView CswNbtView = new CswNbtView(_CswNbtResources);
                    CswNbtView.ViewName = "Other Nodes, for Property Uniqueness";

                    CswNbtViewRelationship ViewRel = null;
                    if (NodeTypeProp.IsGlobalUnique())  // BZ 9754
                    {
                        ViewRel = CswNbtView.AddViewRelationship(_CswNbtResources.MetaData.getObjectClassByNodeTypeId(NodeTypeProp.NodeTypeId), false);
                    }
                    else
                    {
                        ViewRel = CswNbtView.AddViewRelationship(NodeTypeProp.getNodeType(), false);
                    }

                    if (NodeId != null)
                    {
                        ViewRel.NodeIdsToFilterOut.Add(NodeId);
                    }

                    //bz# 5959
                    CswNbtViewProperty UniqueValProperty = CswNbtView.AddViewProperty(ViewRel, NodeTypeProp);

                    // BZ 10099
                    this.NodeTypeProp.getFieldTypeRule().AddUniqueFilterToView(CswNbtView, UniqueValProperty, Node.Properties[this.NodeTypeProp]);

                    ICswNbtTree NodeTree = _CswNbtResources.Trees.getTreeFromView(_CswNbtResources.CurrentNbtUser, CswNbtView, true, false, false);

                    if (NodeTree.getChildNodeCount() > 0)
                    {
                        NodeTree.goToNthChild(0);
                        if (IsCopy && Required && NodeTypeProp.getFieldType().FieldType == CswEnumNbtFieldType.Text)
                        {
                            //CIS-53150 - we want to name mangle things like role names when we try to copy them
                            ((CswNbtNodePropText)this).makeUnique();
                        }
                        else if (false == Required)
                        {
                            //if the prop isn't required, we can just blank it out
                            // BZ 9987 - Clear the value
                            this._CswNbtNodePropData.ClearValue();
                            //this.clearModifiedFlag();
                            this.clearSubFieldModifiedFlags();
                        }
                        else
                        {
                            CswNbtNode CswNbtNode      = NodeTree.getNodeForCurrentPosition();
                            string     EsotericMessage = "Unique constraint violation: The proposed value '" + this.Gestalt + "' ";
                            EsotericMessage += "of property '" + NodeTypeProp.PropName + "' ";
                            EsotericMessage += "for nodeid (" + NodeId.ToString() + ") ";
                            EsotericMessage += "of nodetype '" + NodeTypeProp.getNodeType().NodeTypeName + "' ";
                            EsotericMessage += "is invalid because the same value is already set for node '" + CswNbtNode.NodeName + "' (" + CswNbtNode.NodeId.ToString() + ").";
                            string ExotericMessage = "The " + NodeTypeProp.PropName + " property value must be unique";
                            throw (new CswDniException(CswEnumErrorType.Warning, ExotericMessage, EsotericMessage));
                        }
                    }
                } //if IsUnique
            }     //if empty

            // case 25780 - copy first 512 characters of gestalt to gestaltsearch
            if (_CswNbtNodePropData.wasAnySubFieldModified())
            {
                //string GestaltSearchValue = _CswNbtNodePropData.Gestalt.ToLower();
                //if( GestaltSearchValue.Length > 508 )  // why 508, not 512?  see case 31525.
                //{
                //    GestaltSearchValue = GestaltSearchValue.Substring( 0, 508 );
                //}
                //SetPropRowValue( CswEnumNbtSubFieldName.GestaltSearch, CswEnumNbtPropColumn.GestaltSearch, GestaltSearchValue );

                // We fire this here so that it only fires once per row, not once per subfield.  See case 27241.
                if (null != OnPropChange)
                {
                    OnPropChange(this, Creating);
                }
            }
        } // onBeforeUpdateNodePropRow()
Beispiel #10
0
        internal static Result <DataResponse> GetDataResponseForDataValue(ILogger log, DataValue dataValue, NodeId nodeId, OpcUAQuery query, BrowsePath relativePath)
        {
            try
            {
                if (Opc.Ua.StatusCode.IsGood(dataValue.StatusCode))
                {
                    DataResponse dataResponse = new DataResponse();
                    DataFrame    dataFrame    = new DataFrame(query.refId);

                    var   timeField  = dataFrame.AddField("Time", typeof(DateTime));
                    var   fieldName  = GetFieldName(query, relativePath);
                    Field valueField = dataFrame.AddField(fieldName, dataValue?.Value != null ? dataValue.Value.GetType() : typeof(string));
                    timeField.Append(LimitDateTime(dataValue.SourceTimestamp));
                    valueField.Append(dataValue?.Value != null ? dataValue?.Value : "");
                    dataResponse.Frames.Add(dataFrame.ToGprcArrowFrame());
                    return(new Result <DataResponse>(dataResponse));
                }
                else
                {
                    return(new Result <DataResponse>(dataValue.StatusCode, string.Format("Error reading node with id {0}", nodeId.ToString())));
                }
            }
            catch (Exception e)
            {
                log.LogError(e.Message);
                return(new Result <DataResponse>(dataValue.StatusCode, string.Format("Error reading node with id {0}: {1}", nodeId.ToString(), e.Message)));
            }
        }
Beispiel #11
0
 public IUANodeContext GetOrCreateNodeContext(NodeId nodeId, Func <NodeId, IUANodeContext> createUAModelContext)
 {
     return(m_NodesDictionary[nodeId.ToString()]);
 }
Beispiel #12
0
        /// <summary>
        /// read specified node data from server
        /// <summary>
        private object Read_Node(NodeId nodeid)
        {
            DataValueCollection      results;
            DiagnosticInfoCollection diagnosticInfos;
            ReadValueIdCollection    valuesToRead = new ReadValueIdCollection();

            ReadValueId valueToRead = new ReadValueId();

            valueToRead.NodeId      = nodeid;
            valueToRead.AttributeId = Attributes.Value;

            valuesToRead.Add(valueToRead);

            m_design_session.Read(
                null,
                0,
                TimestampsToReturn.Neither,
                valuesToRead,
                out results,
                out diagnosticInfos);

            object val           = results.Last().Value;
            string message_value = String.Format("Read from node: '{0}'({1}) = '{2}'", "", nodeid.ToString(), val);

            if (!StatusCode.IsGood(results.Last().StatusCode))
            {
                string message_status = String.Format("Error! Read from node ({0}) status code: {1}", nodeid.ToString(), results.Last().StatusCode);
                Debug.WriteLine(message_status);
            }
            return(val);
        }
Beispiel #13
0
        protected override bool onButtonClick( NbtButtonData ButtonData )
        {
            if( null != ButtonData.NodeTypeProp )
            {
                bool HasPermission = false;
                string OCPPropName = ButtonData.NodeTypeProp.getObjectClassPropName();
                switch( OCPPropName )
                {
                    case PropertyName.Request:
                        if( _CswNbtResources.Permit.can( CswEnumNbtActionName.Submit_Request ) )
                        {
                            // Case CIS-52280
                            if( Obsolete.Checked == CswEnumTristate.True )
                            {
                                throw new CswDniException( CswEnumErrorType.Warning, "Can't request Material " + TradeName + " because it is obsolete.", "Material is obsolete" );
                            }

                            HasPermission = true;
                            CswNbtActRequesting RequestAct = new CswNbtActRequesting( _CswNbtResources );

                            CswNbtObjClassRequestItem RequestItem = RequestAct.makeMaterialRequestItem( this, ButtonData );

                            ButtonData.Data["requestaction"] = ButtonData.SelectedText;
                            //ButtonData.Data["requestaction"] = OCPPropName;
                            //Case 31298: Default Option Text "Request" != "Request By Bulk"
                            if( ButtonData.SelectedText == "Request" )
                            {
                                ButtonData.SelectedText = CswEnumRequestOption.Bulk;
                            }
                            ButtonData.Data["titleText"] = ButtonData.SelectedText + " for " + TradeName.Text;
                            ButtonData.Data["requestItemProps"] = RequestAct.getRequestItemAddProps( RequestItem.Node );
                            ButtonData.Data["requestItemNodeTypeId"] = RequestItem.NodeTypeId;
                            ButtonData.Data["relatednodeid"] = NodeId.ToString();
                            ButtonData.Action = CswEnumNbtButtonAction.request;
                        }
                        break;
                    case PropertyName.Receive:
                        if( _CswNbtResources.Permit.can( CswEnumNbtActionName.Receiving ) )
                        {
                            // Case CIS-52280
                            if( Obsolete.Checked == CswEnumTristate.True )
                            {
                                throw new CswDniException( CswEnumErrorType.Warning, "Can't receive Material " + TradeName + " because it is obsolete.", "Material is obsolete" );
                            }

                            HasPermission = true;
                            CswNbtActReceiving Act = new CswNbtActReceiving( _CswNbtResources, NodeId );
                            _CswNbtResources.setAuditActionContext( CswEnumNbtActionName.Receiving );

                            Action<CswNbtNode> After = delegate( CswNbtNode NewNode )
                                {
                                    CswNbtObjClassContainer newContainer = NewNode;
                                    //Case 29436
                                    if( newContainer.isLocationInAccessibleInventoryGroup( _CswNbtResources.CurrentNbtUser.DefaultLocationId ) )
                                    {
                                        newContainer.Location.SelectedNodeId = _CswNbtResources.CurrentNbtUser.DefaultLocationId;
                                    }
                                    newContainer.Owner.RelatedNodeId = _CswNbtResources.CurrentNbtUser.UserId;
                                    DateTime ExpirationDate = getDefaultExpirationDate( DateTime.Now );
                                    if( DateTime.MinValue != ExpirationDate )
                                    {
                                        newContainer.ExpirationDate.DateTimeValue = ExpirationDate;
                                    }
                                    //Container.postChanges( false );
                                };
                            CswNbtObjClassContainer Container = Act.makeContainer( After );

                            ButtonData.Data["state"] = new JObject();
                            ButtonData.Data["state"]["materialId"] = NodeId.ToString();
                            ButtonData.Data["state"]["materialNodeTypeId"] = NodeTypeId;
                            ButtonData.Data["state"]["tradeName"] = TradeName.Text;
                            ButtonData.Data["state"]["nodeName"] = NodeName;

                            Int32 ContainerLimit = CswConvert.ToInt32( _CswNbtResources.ConfigVbls.getConfigVariableValue( CswEnumNbtConfigurationVariables.container_receipt_limit.ToString() ) );
                            ButtonData.Data["state"]["containerlimit"] = ContainerLimit;
                            ButtonData.Data["state"]["containerNodeId"] = Container.NodeId.ToString();
                            ButtonData.Data["state"]["containerNodeTypeId"] = Container.NodeTypeId;
                            bool customBarcodes = CswConvert.ToBoolean( _CswNbtResources.ConfigVbls.getConfigVariableValue( CswEnumNbtConfigurationVariables.custom_barcodes.ToString() ) );
                            ButtonData.Data["state"]["customBarcodes"] = customBarcodes;
                            ButtonData.Data["state"]["nodetypename"] = this.NodeType.NodeTypeName;
                            ButtonData.Data["state"]["containerAddLayout"] = Act.getContainerAddProps( Container );

                            onReceiveButtonClick( ButtonData );
                            _setCofAData( ButtonData );
                            ButtonData.Action = CswEnumNbtButtonAction.receive;
                        }
                        break;
                    case CswNbtObjClass.PropertyName.Save:
                        HasPermission = true;
                        break;
                }
                HasPermission = HasPermission || onPropertySetButtonClick( ButtonData );
                if( false == HasPermission )
                {
                    throw new CswDniException( CswEnumErrorType.Warning, "You do not have permission to the " + OCPPropName + " action.", "You do not have permission to the " + OCPPropName + " action." );
                }
            }

            return true;
        }
Beispiel #14
0
        public void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                NodeAddress = Convert.ToInt32(numericUpDown.Value);

                if (btnConnect.Text == "Connect")
                {
                    //pARAMETERSToolStripMenuItem.Enabled = true;
                    bool valid   = false;
                    bool validee = false;
                    int  cnt     = 0;
                    while (!validee && cnt < 20)
                    {
                        this.Connecting = true;
                        if (this.NodeAddress > 0)
                        {
                            try
                            {
                                loadNode.Visible = true;
                                valid            = AddItemCallback(NodeId.ToString());
                                if (valid)
                                {
                                    loadNode.Visible = false;
                                    //ob.device1ToolStripMenuItem
                                    validee         = true;
                                    this.Connecting = false;
                                    this.ButtonText = "Disconnect";

                                    numericUpDown.Enabled = false;
                                    //ob.ContainerFilter();
                                    break;
                                }
                                cnt++;
                            }
                            catch (Exception ae)
                            {
                                loadNode.Visible = false;
                            }
                        }
                        if (this.NodeAddress <= 0)
                        {
                            MessageBox.Show(new Form()
                            {
                                TopMost = true
                            }, "Select node address!",
                                            "Device Status",
                                            MessageBoxButtons.OK,
                                            MessageBoxIcon.Question);
                            // MessageBox.Show("Select node address!!");
                            cnt = 20;
                        }
                    }
                    loadNode.Visible = false;
                    if (valid == false)
                    {
                        //MessageBox.Show("Reconnect Device! device not found");
                        MessageBox.Show(new Form()
                        {
                            TopMost = true
                        }, "Reconnect Device! device not found.",
                                        "Device Status",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Question);
                    }
                }
                else if (btnConnect.Text == "Disconnect")
                {
                    //pARAMETERSToolStripMenuItem.Enabled = false;
                    bool valid = false;
                    this.Connecting = true;
                    try
                    {
                        valid = RemoveItemCallback(NodeId.ToString());
                    }
                    catch
                    {
                        valid = true;
                    }

                    if (valid)
                    {
                        ResetControls();
                    }
                }
            }
            catch (Exception ex)
            {
                //throw;
            }
        }
Beispiel #15
0
 public override string ToString()
 => NodeId.ToString();
Beispiel #16
0
 public void NodeIdToStringTestMethod3()
 {
     System.Guid _gd = new System.Guid("e08edc80-e771-43ff-b8f6-1fbb62ae5cda");
       NodeId _property = new NodeId(_gd, 1);
       string _res = _property.ToString();
       Assert.AreEqual<string>("ns=1;g=e08edc80-e771-43ff-b8f6-1fbb62ae5cda", _res);
 }
Beispiel #17
0
        /// <summary>
        /// Finishes a drag and drop action whereas this control is used as target.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void MonitoredItems_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                // Retrieve the event data and create the according nodeid.
                String sNodeId = (String)e.Data.GetData(typeof(System.String));
                NodeId nodeId  = new NodeId(sNodeId);

                // Create the subscription if it does not already exist.
                if (m_Subscription == null)
                {
                    m_Subscription = m_Server.AddSubscription(100);
                }

                // Add the attribute name/value to the list view.
                ListViewItem item         = new ListViewItem(sNodeId);
                object       serverHandle = null;

                // Prepare further columns.
                item.SubItems.Add("100"); // Sampling interval by default.
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);

                try
                {
                    // Add the item and apply any changes to it.
                    m_Subscription.AddDataMonitoredItem(nodeId, item, ClientApi_ValueChanged, 100, out serverHandle);

                    // Update status label.
                    OnUpdateStatusLabel("Adding monitored item succeeded for NodeId:" +
                                        nodeId.ToString(), true);
                }
                catch (ServiceResultException monitoredItemResult)
                {
                    item.SubItems[5].Text = monitoredItemResult.StatusCode.ToString();

                    // Update status label.
                    OnUpdateStatusLabel("An exception occured while adding an item: " +
                                        monitoredItemResult.Message, false);
                }

                item.Tag = serverHandle;
                MonitoredItemsLV.Items.Add(item);

                // Fit column width to the longest item and add a few pixel:
                MonitoredItemsLV.Columns[0].Width  = -1;
                MonitoredItemsLV.Columns[0].Width += 15;
                // Fit column width to the column content:
                MonitoredItemsLV.Columns[1].Width = -2;
                MonitoredItemsLV.Columns[5].Width = -2;
                // Fix settings:
                MonitoredItemsLV.Columns[2].Width = 95;
                MonitoredItemsLV.Columns[3].Width = 75;
                MonitoredItemsLV.Columns[4].Width = 75;
            }
            catch (Exception exception)
            {
                // Update status label.
                OnUpdateStatusLabel("An exception occured while creating a subscription: " +
                                    exception.Message, false);
            }
        }
 public static string GetNodeString(NodeId nodeId)
 {
     return(nodeId.ToString().Replace(":", "_"));
 }
        public void addMonitoredItem(NodeId nodeId)
        {
            try
            {
                // Create the subscription if it does not already exist.
                if (m_Subscription == null)
                {
                    m_Subscription = new Subscription(m_Session);
                    m_Subscription.PublishingEnabled  = m_PublishingEnabled;
                    m_Subscription.PublishingInterval = m_PublishingInterval;
                    m_Subscription.DataChanged       += new DataChangedEventHandler(Subscription_DataChanged);
                    m_Subscription.StatusChanged     += new SubscriptionStatusChangedEventHandler(Subscription_StatusChanged);
                    m_Subscription.Create();
                }

                // Add the attribute name/value to the list view.
                ListViewItem item = new ListViewItem(nodeId.ToString());

                // Prepare further columns.
                item.SubItems.Add("250"); // Sampling interval by default.
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);
                item.SubItems.Add(String.Empty);

                List <MonitoredItem> monitoredItems = new List <MonitoredItem>();
                List <StatusCode>    results        = new List <StatusCode>();

                monitoredItems.Add(new DataMonitoredItem(nodeId)
                {
                    DiscardOldest    = true,
                    QueueSize        = 1,
                    SamplingInterval = 250,
                    UserData         = item,
                });

                try
                {
                    // Add the item and apply any changes to it.
                    results = m_Subscription.CreateMonitoredItems(monitoredItems);

                    // Update status label.
                    OnUpdateStatusLabel("Adding monitored item succeeded for NodeId:" +
                                        nodeId.ToString(), true);
                }
                catch (Exception exception)
                {
                    item.SubItems[5].Text = results[0].ToString();

                    // Update status label.
                    OnUpdateStatusLabel("An exception occured while adding an item: " +
                                        exception.Message, false);
                }

                item.Tag = monitoredItems[0];

                MonitoredItemsLV.Items.Add(item);

                // Fit column width to the longest item and add a few pixel:
                MonitoredItemsLV.Columns[0].Width  = -1;
                MonitoredItemsLV.Columns[0].Width += 15;
                // Fit column width to the column content:
                MonitoredItemsLV.Columns[1].Width = -2;
                MonitoredItemsLV.Columns[5].Width = -2;
                // Fix settings:
                MonitoredItemsLV.Columns[2].Width = 95;
                MonitoredItemsLV.Columns[3].Width = 75;
                MonitoredItemsLV.Columns[4].Width = 75;
            }
            catch (Exception exception)
            {
                // Update status label.
                OnUpdateStatusLabel("An exception occured while creating a subscription: " +
                                    exception.Message, false);
            }
        }
Beispiel #20
0
        /// <exception cref="System.Exception"/>
        public virtual void TestFetchApplictionLogs()
        {
            string        remoteLogRootDir = "target/logs/";
            Configuration configuration    = new Configuration();

            configuration.SetBoolean(YarnConfiguration.LogAggregationEnabled, true);
            configuration.Set(YarnConfiguration.NmRemoteAppLogDir, remoteLogRootDir);
            configuration.SetBoolean(YarnConfiguration.YarnAclEnable, true);
            configuration.Set(YarnConfiguration.YarnAdminAcl, "admin");
            FileSystem           fs           = FileSystem.Get(configuration);
            UserGroupInformation ugi          = UserGroupInformation.GetCurrentUser();
            ApplicationId        appId        = ApplicationIdPBImpl.NewInstance(0, 1);
            ApplicationAttemptId appAttemptId = ApplicationAttemptIdPBImpl.NewInstance(appId,
                                                                                       1);
            ContainerId containerId0 = ContainerIdPBImpl.NewContainerId(appAttemptId, 0);
            ContainerId containerId1 = ContainerIdPBImpl.NewContainerId(appAttemptId, 1);
            ContainerId containerId2 = ContainerIdPBImpl.NewContainerId(appAttemptId, 2);
            NodeId      nodeId       = NodeId.NewInstance("localhost", 1234);
            // create local logs
            string rootLogDir     = "target/LocalLogs";
            Path   rootLogDirPath = new Path(rootLogDir);

            if (fs.Exists(rootLogDirPath))
            {
                fs.Delete(rootLogDirPath, true);
            }
            NUnit.Framework.Assert.IsTrue(fs.Mkdirs(rootLogDirPath));
            Path appLogsDir = new Path(rootLogDirPath, appId.ToString());

            if (fs.Exists(appLogsDir))
            {
                fs.Delete(appLogsDir, true);
            }
            NUnit.Framework.Assert.IsTrue(fs.Mkdirs(appLogsDir));
            IList <string> rootLogDirs = Arrays.AsList(rootLogDir);

            // create container logs in localLogDir
            CreateContainerLogInLocalDir(appLogsDir, containerId1, fs);
            CreateContainerLogInLocalDir(appLogsDir, containerId2, fs);
            Path path = new Path(remoteLogRootDir + ugi.GetShortUserName() + "/logs/application_0_0001"
                                 );

            if (fs.Exists(path))
            {
                fs.Delete(path, true);
            }
            NUnit.Framework.Assert.IsTrue(fs.Mkdirs(path));
            // upload container logs into remote directory
            // the first two logs is empty. When we try to read first two logs,
            // we will meet EOF exception, but it will not impact other logs.
            // Other logs should be read successfully.
            UploadEmptyContainerLogIntoRemoteDir(ugi, configuration, rootLogDirs, nodeId, containerId0
                                                 , path, fs);
            UploadEmptyContainerLogIntoRemoteDir(ugi, configuration, rootLogDirs, nodeId, containerId1
                                                 , path, fs);
            UploadContainerLogIntoRemoteDir(ugi, configuration, rootLogDirs, nodeId, containerId1
                                            , path, fs);
            UploadContainerLogIntoRemoteDir(ugi, configuration, rootLogDirs, nodeId, containerId2
                                            , path, fs);
            YarnClient mockYarnClient = CreateMockYarnClient(YarnApplicationState.Finished);
            LogsCLI    cli            = new TestLogsCLI.LogsCLIForTest(mockYarnClient);

            cli.SetConf(configuration);
            int exitCode = cli.Run(new string[] { "-applicationId", appId.ToString() });

            NUnit.Framework.Assert.IsTrue(exitCode == 0);
            NUnit.Framework.Assert.IsTrue(sysOutStream.ToString().Contains("Hello container_0_0001_01_000001!"
                                                                           ));
            NUnit.Framework.Assert.IsTrue(sysOutStream.ToString().Contains("Hello container_0_0001_01_000002!"
                                                                           ));
            sysOutStream.Reset();
            // uploaded two logs for container1. The first log is empty.
            // The second one is not empty.
            // We can still successfully read logs for container1.
            exitCode = cli.Run(new string[] { "-applicationId", appId.ToString(), "-nodeAddress"
                                              , nodeId.ToString(), "-containerId", containerId1.ToString() });
            NUnit.Framework.Assert.IsTrue(exitCode == 0);
            NUnit.Framework.Assert.IsTrue(sysOutStream.ToString().Contains("Hello container_0_0001_01_000001!"
                                                                           ));
            NUnit.Framework.Assert.IsTrue(sysOutStream.ToString().Contains("Log Upload Time")
                                          );
            NUnit.Framework.Assert.IsTrue(!sysOutStream.ToString().Contains("Logs for container "
                                                                            + containerId1.ToString() + " are not present in this log-file."));
            sysOutStream.Reset();
            // Uploaded the empty log for container0.
            // We should see the message showing the log for container0
            // are not present.
            exitCode = cli.Run(new string[] { "-applicationId", appId.ToString(), "-nodeAddress"
                                              , nodeId.ToString(), "-containerId", containerId0.ToString() });
            NUnit.Framework.Assert.IsTrue(exitCode == -1);
            NUnit.Framework.Assert.IsTrue(sysOutStream.ToString().Contains("Logs for container "
                                                                           + containerId0.ToString() + " are not present in this log-file."));
            fs.Delete(new Path(remoteLogRootDir), true);
            fs.Delete(new Path(rootLogDir), true);
        }
Beispiel #21
0
        public void TestNodeIdToString()
        {
            var nodeId = new NodeId(999);

            Assert.That(nodeId.ToString(), Is.EqualTo("999"));
        }
Beispiel #22
0
        /// <summary>
        /// Method to remove the node from the subscription and stop publishing telemetry to IoTHub.
        /// </summary>
        private ServiceResult OnUnpublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            if (inputArguments[0] == null || inputArguments[1] == null)
            {
                Trace("UnpublishNode: Invalid arguments!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments!"));
            }

            NodeId nodeId      = null;
            Uri    endpointUri = null;

            try
            {
                if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
                {
                    Trace($"UnpublishNode: Arguments (0 (nodeId), 1 (endpointUrl)) are not valid strings!");
                    return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
                }
                nodeId      = inputArguments[0] as string;
                endpointUri = new Uri(inputArguments[1] as string);
            }
            catch (UriFormatException)
            {
                Trace($"UnpublishNode: The endpointUrl is invalid '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }

            // find the session and stop monitoring the node.
            try
            {
                if (PublisherShutdownInProgress)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                try
                {
                    OpcSessionsSemaphore.Wait();
                    opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUri == endpointUri);
                }
                catch
                {
                    opcSession = null;
                }
                finally
                {
                    OpcSessionsSemaphore.Release();
                }
                if (opcSession == null)
                {
                    // do nothing if there is no session for this endpoint.
                    Trace($"UnpublishNode: Session for endpoint '{endpointUri.OriginalString}' not found.");
                    return(ServiceResult.Create(StatusCodes.BadSessionIdInvalid, "Session for endpoint of published node not found!"));
                }
                else
                {
                    Trace($"UnpublishNode: Session found for endpoint '{endpointUri.OriginalString}'");
                }

                // remove the node from the sessions monitored items list.
                opcSession.TagNodeForMonitoringStop(nodeId);
                Trace("UnpublishNode: Requested to stop monitoring of node.");

                // remove node from persisted config file
                try
                {
                    PublishDataSemaphore.Wait();
                    var entryToRemove = PublisherConfigFileEntries.Find(l => l.NodeId == nodeId && l.EndpointUri == endpointUri);
                    PublisherConfigFileEntries.Remove(entryToRemove);
                    File.WriteAllText(NodesToPublishAbsFilename, JsonConvert.SerializeObject(PublisherConfigFileEntries));
                }
                finally
                {
                    PublishDataSemaphore.Release();
                }
            }
            catch (Exception e)
            {
                Trace(e, $"UnpublishNode: Exception while trying to configure publishing node '{nodeId.ToString()}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error publishing node: {e.Message}"));
            }
            return(ServiceResult.Good);
        }
Beispiel #23
0
        /// <summary>
        /// Adds a node as an attribute to the EventCategories list
        /// </summary>
        /// <param name="EventTypeNodeId">The event type node</param>
        /// <param name="AttrRef">The reference node being added as an attribute</param>
        private void ProcessNodeAsAttribute(NodeId EventTypeNodeId, ReferenceDescription AttrRef)
        {
            try
            {
                EventAttribute attr = new EventAttribute();
                DataValue value = new DataValue();

                attr.AttributeID = m_attrID++;
                attr.strNodeId = AttrRef.NodeId.ToString();
                attr.BrowseName = AttrRef.BrowseName.Name;
                attr.BrowseNameNSIndex = AttrRef.BrowseName.NamespaceIndex;
                attr.AttrDesc = AttrRef.DisplayName.Text;

                Node node = m_session.ReadNode((NodeId)AttrRef.NodeId);
                node.Read(null, Attributes.DataType, value);
                NodeId typenode = (NodeId)value.Value;
                attr.strDataTypeNodeId = typenode.ToString();
                attr.ActualDataType = DataTypes.GetSystemType(typenode, EncodeableFactory.GlobalFactory);
                attr.strEventNodeId = EventTypeNodeId.ToString();

                node.Read(null, Attributes.ValueRank, value);
                //TODO: Used to be ArraySize. Does ValueRank have the same definition?
                if ((int)value.Value >= 0) //TODO: is there a constant that can be used
                    attr.IsArray = true;
                else
                    attr.IsArray = false;

                m_EventAttributes.Add(attr);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error in ProcessNodesAsAttribute");
            }
        }
Beispiel #24
0
        /// <summary>
        /// Adds a event node to be monitored. If there is no subscription with the requested publishing interval,
        /// one is created.
        /// </summary>
        public async Task <HttpStatusCode> AddEventNodeForMonitoringAsync(NodeId nodeId, ExpandedNodeId expandedNodeId,
                                                                          int?opcPublishingInterval, int?opcSamplingInterval, string displayName,
                                                                          int?heartbeatInterval, bool?skipFirst, CancellationToken ct, IotCentralItemPublishMode?iotCentralItemPublishMode,
                                                                          PublishNodesMethodRequestModel publishEventsMethodData)
        {
            string logPrefix     = "AddEventNodeForMonitoringAsync:";
            bool   sessionLocked = false;

            try
            {
                sessionLocked = await LockSessionAsync().ConfigureAwait(false);

                if (!sessionLocked || ct.IsCancellationRequested)
                {
                    return(HttpStatusCode.Gone);
                }

                // check if there is already a subscription with the same publishing interval, which can be used to monitor the node
                int opcPublishingIntervalForNode      = opcPublishingInterval ?? OpcPublishingIntervalDefault;
                IOpcSubscription opcEventSubscription = OpcEventSubscriptions.FirstOrDefault(s => s.RequestedPublishingInterval == opcPublishingIntervalForNode);

                // if there was none found, create one
                if (opcEventSubscription == null)
                {
                    if (opcPublishingInterval == null)
                    {
                        Logger.Information($"{logPrefix} No matching subscription with default publishing interval found.");
                        Logger.Information($"Create a new subscription with a default publishing interval.");
                    }
                    else
                    {
                        Logger.Information($"{logPrefix} No matching subscription with publishing interval of {opcPublishingInterval} found.");
                        Logger.Information($"Create a new subscription with a publishing interval of {opcPublishingInterval}.");
                    }
                    opcEventSubscription = new OpcSubscription(opcPublishingInterval);
                    OpcEventSubscriptions.Add(opcEventSubscription);
                }

                // create objects for publish check
                ExpandedNodeId expandedNodeIdCheck = expandedNodeId;
                NodeId         nodeIdCheck         = nodeId;
                if (State == SessionState.Connected)
                {
                    if (expandedNodeId == null)
                    {
                        string namespaceUri = _namespaceTable.ToArray().ElementAtOrDefault(nodeId.NamespaceIndex);
                        expandedNodeIdCheck = new ExpandedNodeId(nodeId.Identifier, nodeId.NamespaceIndex, namespaceUri, 0);
                    }
                    if (nodeId == null)
                    {
                        nodeIdCheck = new NodeId(expandedNodeId.Identifier, (ushort)(_namespaceTable.GetIndex(expandedNodeId.NamespaceUri)));
                    }
                }

                // if it is already published, we do nothing, else we create a new monitored event item
                if (!IsEventNodePublishedInSessionInternal(nodeIdCheck, expandedNodeIdCheck))
                {
                    OpcMonitoredItem           opcMonitoredItem     = null;
                    EncryptedNetworkCredential encryptedCredentials = null;

                    if (publishEventsMethodData.OpcAuthenticationMode == OpcAuthenticationMode.UsernamePassword)
                    {
                        if (string.IsNullOrWhiteSpace(publishEventsMethodData.UserName) && string.IsNullOrWhiteSpace(publishEventsMethodData.Password))
                        {
                            throw new ArgumentException($"If {nameof(publishEventsMethodData.OpcAuthenticationMode)} is set to '{OpcAuthenticationMode.UsernamePassword}', you have to specify '{nameof(publishEventsMethodData.UserName)}' and/or '{nameof(publishEventsMethodData.Password)}'.");
                        }

                        encryptedCredentials = await EncryptedNetworkCredential.FromPlainCredential(publishEventsMethodData.UserName, publishEventsMethodData.Password);
                    }

                    // add a new item to monitor
                    if (expandedNodeId == null)
                    {
                        opcMonitoredItem = new OpcMonitoredItem(new EventConfigurationModel(publishEventsMethodData.EndpointId, publishEventsMethodData.EndpointName, publishEventsMethodData.EndpointUrl, publishEventsMethodData.UseSecurity, publishEventsMethodData.OpcAuthenticationMode ?? OpcAuthenticationMode.Anonymous, encryptedCredentials,
                                                                                            publishEventsMethodData.OpcEvents[0].Id, publishEventsMethodData.OpcEvents[0].DisplayName, publishEventsMethodData.OpcEvents[0].SelectClauses,
                                                                                            publishEventsMethodData.OpcEvents[0].WhereClause, publishEventsMethodData.OpcEvents[0].IotCentralEventPublishMode), EndpointId, EndpointUrl);;
                    }
                    else
                    {
                        opcMonitoredItem = new OpcMonitoredItem(new EventConfigurationModel(publishEventsMethodData.EndpointId, publishEventsMethodData.EndpointName, publishEventsMethodData.EndpointUrl, publishEventsMethodData.UseSecurity, publishEventsMethodData.OpcAuthenticationMode ?? OpcAuthenticationMode.Anonymous, encryptedCredentials,
                                                                                            expandedNodeId.ToString(), publishEventsMethodData.OpcEvents[0].DisplayName, publishEventsMethodData.OpcEvents[0].SelectClauses,
                                                                                            publishEventsMethodData.OpcEvents[0].WhereClause, publishEventsMethodData.OpcEvents[0].IotCentralEventPublishMode), EndpointId, EndpointUrl);
                    }
                    opcEventSubscription.OpcMonitoredItems.Add(opcMonitoredItem);
                    Interlocked.Increment(ref NodeConfigVersion);
                    Logger.Debug($"{logPrefix} Added event item with nodeId '{(expandedNodeId == null ? nodeId.ToString() : expandedNodeId.ToString())}' for monitoring.");

                    // trigger the actual OPC communication with the server to be done
                    ConnectAndMonitorSession.Set();
                    return(HttpStatusCode.Accepted);
                }
                else
                {
                    Logger.Debug($"{logPrefix} Node with Id '{(expandedNodeId == null ? nodeId.ToString() : expandedNodeId.ToString())}' is already monitored.");
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{logPrefix} Exception while trying to add node '{(expandedNodeId == null ? nodeId.ToString() : expandedNodeId.ToString())}' for monitoring.");
                return(HttpStatusCode.InternalServerError);
            }
            finally
            {
                if (sessionLocked)
                {
                    ReleaseSession();
                }
            }
            return(HttpStatusCode.OK);
        }
        /// <summary>
        /// Method to start monitoring a node and publish the data to IoTHub. Executes synchronously.
        /// </summary>
        private ServiceResult OnPublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
            {
                Trace("PublishNode: Invalid Arguments when trying to publish a node.");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            NodeId nodeId      = null;
            Uri    endpointUri = null;

            try
            {
                nodeId      = NodeId.Parse(inputArguments[0] as string);
                endpointUri = new Uri(inputArguments[1] as string);
            }
            catch (UriFormatException)
            {
                Trace($"PublishNode: The EndpointUri has an invalid format '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }
            catch (Exception e)
            {
                Trace(e, $"PublishNode: The NodeId has an invalid format '{inputArguments[0] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in NodeId format as first argument!"));
            }

            // find/create a session to the endpoint URL and start monitoring the node.
            try
            {
                // lock the publishing configuration till we are done
                OpcSessionsListSemaphore.WaitAsync();

                if (ShutdownTokenSource.IsCancellationRequested)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUri.AbsoluteUri.Equals(endpointUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase));
                string         namespaceUri   = null;
                ExpandedNodeId expandedNodeId = null;

                // add a new session.
                if (opcSession == null)
                {
                    // create new session info.
                    opcSession = new OpcSession(endpointUri, true, OpcSessionCreationTimeout);
                    OpcSessions.Add(opcSession);
                    Trace($"PublishNode: No matching session found for endpoint '{endpointUri.OriginalString}'. Requested to create a new one.");
                }
                else
                {
                    Trace($"PublishNode: Session found for endpoint '{endpointUri.OriginalString}'");

                    // check if node is already published
                    namespaceUri = opcSession.GetNamespaceUri(nodeId.NamespaceIndex);
                    if (string.IsNullOrEmpty(namespaceUri))
                    {
                        return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"The namespace index of the node id is invalid."));
                    }
                    expandedNodeId = new ExpandedNodeId(nodeId.Identifier, nodeId.NamespaceIndex, namespaceUri, 0);
                }

                // add the node info to the subscription with the default publishing interval, execute syncronously
                opcSession.AddNodeForMonitoring(nodeId, expandedNodeId, OpcPublishingInterval, OpcSamplingInterval, ShutdownTokenSource.Token).Wait();
                Trace($"PublishNode: Requested to monitor item with NodeId '{nodeId.ToString()}' (PublishingInterval: {OpcPublishingInterval}, SamplingInterval: {OpcSamplingInterval})");
            }
            catch (Exception e)
            {
                Trace(e, $"PublishNode: Exception while trying to configure publishing node '{nodeId.ToString()}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error publishing node: {e.Message}"));
            }
            finally
            {
                OpcSessionsListSemaphore.Release();
            }
            return(ServiceResult.Good);
        }
Beispiel #26
0
        /// <summary>
        /// Displays the attributes and properties in the attributes view.
        /// </summary>
        /// <param name="sourceId">The NodeId of the Node to browse.</param>
        private void DisplayAttributes(NodeId sourceId)
        {
            try
            {
                AttributesView.Items.Clear();

                ReadValueIdCollection nodesToRead = new ReadValueIdCollection();

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

                int startOfProperties = nodesToRead.Count;

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

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

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

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

                if (references == null)
                {
                    return;
                }

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

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

                // read all values.
                OperationContext         context         = new OperationContext(new RequestHeader(), RequestType.Browse);
                DataValueCollection      results         = null;
                DiagnosticInfoCollection diagnosticInfos = null;

                m_server.CurrentInstance.NodeManager.Read(
                    context,
                    0,
                    TimestampsToReturn.Neither,
                    nodesToRead,
                    out results,
                    out diagnosticInfos);

                ListViewItem idnode = new ListViewItem("NodeID");
                idnode.SubItems.Add(sourceId.ToString());
                AttributesView.Items.Add(idnode);
                // process results.
                for (int ii = 0; ii < results.Count; ii++)
                {
                    string name     = null;
                    string datatype = null;
                    string value    = null;

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

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

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

                            datatype = typeInfo.BuiltInType.ToString();

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

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

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

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

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

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

                            datatype = typeInfo.BuiltInType.ToString();

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

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

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

                // adjust width of all columns.
                for (int ii = 0; ii < AttributesView.Columns.Count; ii++)
                {
                    AttributesView.Columns[ii].Width = -2;
                }
            }
            catch (Exception exception)
            {
                ServerUtils.HandleException(this.Text, exception);
            }
        }
        /// <summary>
        /// Method to remove the node from the subscription and stop publishing telemetry to IoTHub. Executes synchronously.
        /// </summary>
        private ServiceResult OnUnpublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
            {
                Trace("UnpublishNode: Invalid arguments!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments!"));
            }

            NodeId nodeId      = null;
            Uri    endpointUri = null;

            try
            {
                nodeId      = NodeId.Parse(inputArguments[0] as string);
                endpointUri = new Uri(inputArguments[1] as string);
            }
            catch (UriFormatException)
            {
                Trace($"UnpublishNode: The endpointUrl is invalid '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }

            // find the session and stop monitoring the node.
            try
            {
                if (ShutdownTokenSource.IsCancellationRequested)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                try
                {
                    OpcSessionsListSemaphore.WaitAsync();
                    opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUri.AbsoluteUri.Equals(endpointUri.AbsoluteUri, StringComparison.OrdinalIgnoreCase));
                }
                catch
                {
                    opcSession = null;
                }
                finally
                {
                    OpcSessionsListSemaphore.Release();
                }


                ExpandedNodeId expandedNodeId = null;
                if (opcSession == null)
                {
                    // do nothing if there is no session for this endpoint.
                    Trace($"UnpublishNode: Session for endpoint '{endpointUri.OriginalString}' not found.");
                    return(ServiceResult.Create(StatusCodes.BadSessionIdInvalid, "Session for endpoint of node to unpublished not found!"));
                }
                else
                {
                    // check if node is already published
                    string namespaceUri = opcSession.GetNamespaceUri(nodeId.NamespaceIndex);
                    if (string.IsNullOrEmpty(namespaceUri))
                    {
                        return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"The namespace index of the node id is invalid."));
                    }
                    expandedNodeId = new ExpandedNodeId(nodeId.Identifier, nodeId.NamespaceIndex, namespaceUri, 0);
                    if (!OpcSession.IsNodePublished(nodeId, expandedNodeId, endpointUri))
                    {
                        Trace($"UnpublishNode: Node with id '{nodeId.Identifier.ToString()}' on endpoint '{endpointUri.OriginalString}' is not published.");
                        return(ServiceResult.Good);
                    }
                }

                // remove the node from the sessions monitored items list.
                opcSession.RequestMonitorItemRemoval(nodeId, expandedNodeId, ShutdownTokenSource.Token).Wait();
                Trace("UnpublishNode: Requested to stop monitoring of node.");
            }
            catch (Exception e)
            {
                Trace(e, $"UnpublishNode: Exception while trying to configure publishing node '{nodeId.ToString()}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error unpublishing node: {e.Message}"));
            }
            return(ServiceResult.Good);
        }
        /// <summary>
        /// Method to start monitoring a node and publish the data to IoTHub. Executes synchronously.
        /// </summary>
        private ServiceResult OnPublishNodeCall(ISystemContext context, MethodState method, IList <object> inputArguments, IList <object> outputArguments)
        {
            string logPrefix = "OnPublishNodeCall:";

            if (string.IsNullOrEmpty(inputArguments[0] as string) || string.IsNullOrEmpty(inputArguments[1] as string))
            {
                Logger.Error($"{logPrefix} Invalid Arguments when trying to publish a node.");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide all arguments as strings!"));
            }

            HttpStatusCode statusCode     = HttpStatusCode.InternalServerError;
            NodeId         nodeId         = null;
            ExpandedNodeId expandedNodeId = null;
            Uri            endpointUri    = null;
            bool           isNodeIdFormat = true;

            try
            {
                string id = inputArguments[0] as string;
                if (id.Contains("nsu=", StringComparison.InvariantCulture))
                {
                    expandedNodeId = ExpandedNodeId.Parse(id);
                    isNodeIdFormat = false;
                }
                else
                {
                    nodeId         = NodeId.Parse(id);
                    isNodeIdFormat = true;
                }
                endpointUri = new Uri(inputArguments[1] as string);
            }
            catch (UriFormatException)
            {
                Logger.Error($"{logPrefix} The EndpointUrl has an invalid format '{inputArguments[1] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA endpoint URL as second argument!"));
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{logPrefix} The NodeId has an invalid format '{inputArguments[0] as string}'!");
                return(ServiceResult.Create(StatusCodes.BadArgumentsMissing, "Please provide a valid OPC UA NodeId in NodeId or ExpandedNodeId format as first argument!"));
            }

            // find/create a session to the endpoint URL and start monitoring the node.
            try
            {
                // lock the publishing configuration till we are done
                OpcSessionsListSemaphore.Wait();

                if (ShutdownTokenSource.IsCancellationRequested)
                {
                    return(ServiceResult.Create(StatusCodes.BadUnexpectedError, $"Publisher shutdown in progress."));
                }

                // find the session we need to monitor the node
                OpcSession opcSession = null;
                opcSession = OpcSessions.FirstOrDefault(s => s.EndpointUrl.Equals(endpointUri.OriginalString, StringComparison.OrdinalIgnoreCase));

                // add a new session.
                if (opcSession == null)
                {
                    // create new session info.
                    opcSession = new OpcSession(endpointUri.OriginalString, true, OpcSessionCreationTimeout);
                    OpcSessions.Add(opcSession);
                    Logger.Information($"OnPublishNodeCall: No matching session found for endpoint '{endpointUri.OriginalString}'. Requested to create a new one.");
                }

                if (isNodeIdFormat)
                {
                    // add the node info to the subscription with the default publishing interval, execute syncronously
                    Logger.Debug($"{logPrefix} Request to monitor item with NodeId '{nodeId.ToString()}' (with default PublishingInterval and SamplingInterval)");
                    statusCode = opcSession.AddNodeForMonitoringAsync(nodeId, null, null, null, null, null, null, ShutdownTokenSource.Token).Result;
                }
                else
                {
                    // add the node info to the subscription with the default publishing interval, execute syncronously
                    Logger.Debug($"{logPrefix} Request to monitor item with ExpandedNodeId '{expandedNodeId.ToString()}' (with default PublishingInterval and SamplingInterval)");
                    statusCode = opcSession.AddNodeForMonitoringAsync(null, expandedNodeId, null, null, null, null, null, ShutdownTokenSource.Token).Result;
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, $"{logPrefix} Exception while trying to configure publishing node '{(isNodeIdFormat ? nodeId.ToString() : expandedNodeId.ToString())}'");
                return(ServiceResult.Create(e, StatusCodes.BadUnexpectedError, $"Unexpected error publishing node: {e.Message}"));
            }
            finally
            {
                OpcSessionsListSemaphore.Release();
            }

            if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Accepted)
            {
                return(ServiceResult.Good);
            }
            return(ServiceResult.Create(StatusCodes.Bad, "Can not start monitoring node! Reason unknown."));
        }
Beispiel #29
0
 public override string ToString()
 {
     return(string.Format("{0} ID:{1}", DisplayName, TagRef.ToString()));
 }
Beispiel #30
0
        public void NodeConnect(int a)
        {
            try
            {
                // MonitorOnline ob = new MonitorOnline();
                // NodeAddress = Convert.ToInt32(numericUpDown.Value);
                NodeAddress = a;
                if (btnConnect.Text == "Connect")
                {
                    bool validee = false;
                    int  cnt     = 0;
                    while (!validee && cnt < 50)
                    {
                        // System.Threading.Thread.Sleep(500);
                        this.Connecting = true;
                        if (this.NodeAddress > 0)
                        {
                            try
                            {
                                bool valid = AddItemCallback(NodeId.ToString());

                                if (valid)
                                {
                                    loadNode.Visible = false;
                                    validee          = true;
                                    this.Connecting  = false;
                                    this.ButtonText  = "Disconnect";

                                    numericUpDown.Enabled = false;
                                    //ob.ContainerFilter();
                                    break;
                                }
                                cnt++;
                            }
                            catch (Exception ae)
                            { }
                        }
                        if (this.NodeAddress <= 0)
                        {
                            //  DeviceLoader.Visible = false;
                            MessageBox.Show("Select node address!!");
                        }
                    }
                }
                else if (btnConnect.Text == "Disconnect")
                {
                    bool valid = false;
                    this.Connecting = true;
                    try
                    {
                        valid = RemoveItemCallback(NodeId.ToString());
                    }
                    catch
                    {
                        valid = true;
                    }

                    if (valid)
                    {
                        ResetControls();
                    }
                }
            }
            catch (Exception ex)
            {
                //throw;
            }
        }
Beispiel #31
0
 public override string ToString()
 {
     return($"enode://{NodeId?.ToString(false)}@{Host}:{Port}");
 }
        }//afterPopulateProps()

        /// <summary>
        ///
        /// </summary>
        public override bool onPropertySetButtonClick(NbtButtonData ButtonData)
        {
            if (null != ButtonData.NodeTypeProp)
            {
                //Remember: Save is an OCP too
                switch (ButtonData.NodeTypeProp.getObjectClassPropName())
                {
                case PropertyName.Fulfill:
                    switch (ButtonData.SelectedText)
                    {
                    case FulfillMenu.Order:
                        ButtonData.Action         = CswEnumNbtButtonAction.editprop;
                        ButtonData.Data["nodeid"] = NodeId.ToString();
                        CswPropIdAttr OrdIdAttr = new CswPropIdAttr(Node, ExternalOrderNumber.NodeTypeProp);
                        ButtonData.Data["propidattr"] = OrdIdAttr.ToString();
                        ButtonData.Data["title"]      = "Enter the External Order Number";
                        break;

                    case FulfillMenu.Receive:
                        CswNbtPropertySetMaterial NodeAsMaterial = _CswNbtResources.Nodes.GetNode(Material.RelatedNodeId);
                        if (null != NodeAsMaterial)
                        {
                            if (null != NodeAsMaterial.Receive.NodeTypeProp)
                            {
                                NbtButtonData ReceiveData = new NbtButtonData(NodeAsMaterial.Receive.NodeTypeProp);
                                NodeAsMaterial.triggerOnButtonClick(ReceiveData);
                                ButtonData.clone(ReceiveData);
                                if (_CswNbtResources.Modules.IsModuleEnabled(CswEnumNbtModuleName.SDS))
                                {
                                    CswNbtMetaDataObjectClass SDSDocOC = _CswNbtResources.MetaData.getObjectClass(CswEnumNbtObjectClass.SDSDocumentClass);
                                    Int32 SDSNodeTypeId = SDSDocOC.FirstNodeType.NodeTypeId;
                                    if (Int32.MinValue != SDSNodeTypeId)
                                    {
                                        ButtonData.Data["documenttypeid"] = SDSNodeTypeId;
                                    }
                                }
                            }
                        }
                        break;

                    case FulfillMenu.Dispense:
                        JObject InitialQuantity = null;
                        if (false == Quantity.Empty)
                        {
                            InitialQuantity = new JObject();
                            Quantity.ToJSON(InitialQuantity);
                        }
                        if (null != InitialQuantity)
                        {
                            ButtonData.Data["initialQuantity"] = InitialQuantity;
                        }
                        string Title = "Fulfill Request for " + Quantity.Gestalt + " of " + Material.Gestalt;
                        if (TotalDispensed.Quantity > 0)
                        {
                            Title += " (" + TotalDispensed.Gestalt + ") dispensed.";
                        }
                        ButtonData.Data["title"] = Title;
                        ButtonData.Action        = CswEnumNbtButtonAction.dispense;
                        break;

                    case FulfillMenu.Move:
                        ButtonData.Data["title"]    = "Fulfill Request for " + Count.Value + " x " + Size.Gestalt + " of " + Material.Gestalt;
                        ButtonData.Data["sizeid"]   = Size.RelatedNodeId.ToString();
                        ButtonData.Data["location"] = Location.Gestalt;
                        ButtonData.Action           = CswEnumNbtButtonAction.move;
                        break;
                    }     //switch( ButtonData.SelectedText )

                    _getNextStatus(ButtonData.SelectedText);
                    ButtonData.Data["requestitem"] = ButtonData.Data["requestitem"] ?? new JObject();
                    ButtonData.Data["requestitem"]["requestMode"]      = Type.Value.ToLower();
                    ButtonData.Data["requestitem"]["requestitemid"]    = NodeId.ToString();
                    ButtonData.Data["requestitem"]["inventorygroupid"] = (InventoryGroup.RelatedNodeId ?? new CswPrimaryKey()).ToString();
                    ButtonData.Data["requestitem"]["materialid"]       = (Material.RelatedNodeId ?? new CswPrimaryKey()).ToString();
                    ButtonData.Data["requestitem"]["locationid"]       = (Location.SelectedNodeId ?? new CswPrimaryKey()).ToString();
                    break;     //case PropertyName.Fulfill:
                }
            }
            return(true);
        }
Beispiel #33
0
 public void NodeIdToStringTestMethod2()
 {
     NodeId _property = new NodeId(68, 1);
       Assert.AreNotSame(_property, VariableTypeIds.PropertyType);
       string _res = _property.ToString();
       Assert.AreEqual<string>("ns=1;i=68", _res);
 }