示例#1
0
        static void HistoryUpdate(Session session)
        {
            DiagnosticInfoCollection diagnosticInfos;

            // translate browse paths.
            IList <NodeOfInterest> nodeIds;

            nodeIds = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                                 VariableBrowsePaths.ToArray());

            ExtensionObjectCollection eoc = new ExtensionObjectCollection();

            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                UpdateDataDetails updateDetails = new UpdateDataDetails();

                updateDetails.NodeId = nodeIds[ii].NodeId;
                updateDetails.PerformInsertReplace = PerformUpdateType.Update;
                updateDetails.UpdateValues         = new DataValueCollection();

                for (int jj = 0; jj <= 5; jj++)
                {
                    DataValue dv = new DataValue(new Variant(jj * 10), StatusCodes.Good,
                                                 new DateTime(2008, 01, 01, 12, 0, jj * 2));
                    updateDetails.UpdateValues.Add(dv);
                }

                ExtensionObject eo = new ExtensionObject(updateDetails.TypeId, updateDetails);
                eoc.Add(eo);
            }

            HistoryUpdateResultCollection historyUpdateResults;

            ResponseHeader responseHeader =
                session.HistoryUpdate(null, eoc, out historyUpdateResults, out diagnosticInfos);


            // process results.

            for (int ii = 0; ii < historyUpdateResults.Count; ii++)
            {
                HistoryUpdateResult historyUpdateResult = historyUpdateResults[ii];

                Console.WriteLine("HistoryUpdate result code for {0}:  {1}", VariableBrowsePaths[ii],
                                  historyUpdateResult.StatusCode.ToString());

                if (StatusCode.IsGood(historyUpdateResult.StatusCode))
                {
                    for (int jj = 0; jj < historyUpdateResult.OperationResults.Count; jj++)
                    {
                        Console.WriteLine("    {0}: {1}", jj, historyUpdateResult.OperationResults[jj]);
                    }

                    Console.WriteLine("");
                }
            }
        }
示例#2
0
        /// <summary>
        /// Deletes the history of values for a set of variables at given time.
        /// </summary>
        static void HistoryDeleteAtTime(Session session)
        {
            // translate browse paths.
            IList <NodeOfInterest> results = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                                                        VariableBrowsePaths.ToArray());


            DiagnosticInfoCollection diagnosticInfos;

            ExtensionObjectCollection eoc = new ExtensionObjectCollection();

            for (int ii = 0; ii < results.Count; ii++)
            {
                DeleteAtTimeDetails deleteDetails = new DeleteAtTimeDetails();
                deleteDetails.ReqTimes = new DateTimeCollection();
                for (int jj = 0; jj < 5; jj++)
                {
                    deleteDetails.ReqTimes.Add(new DateTime(2008, 01, 01, 12, 0, jj * 2));
                }

                deleteDetails.NodeId    = results[ii].NodeId;
                deleteDetails.Processed = false;

                ExtensionObject eo = new ExtensionObject(deleteDetails.TypeId, deleteDetails);
                eoc.Add(eo);
            }

            HistoryUpdateResultCollection historyUpdateResults;

            ResponseHeader responseHeader =
                session.HistoryUpdate(null, eoc, out historyUpdateResults, out diagnosticInfos);

            // process results.

            for (int ii = 0; ii < historyUpdateResults.Count; ii++)
            {
                HistoryUpdateResult historyUpdateResult = historyUpdateResults[ii];

                Console.WriteLine("HistoryUpdate result code for {0}:  {1}", VariableBrowsePaths[ii],
                                  historyUpdateResult.StatusCode.ToString());

                if (StatusCode.IsGood(historyUpdateResult.StatusCode))
                {
                    for (int jj = 0; jj < historyUpdateResult.OperationResults.Count; jj++)
                    {
                        Console.WriteLine("    {0}: {1}", jj, historyUpdateResult.OperationResults[jj]);
                    }

                    Console.WriteLine("");
                }
            }
        }
示例#3
0
        /// <summary>
        /// 注册服务(每个在本机启动的服务端都会主动调用此方法进行注册)
        /// </summary>
        /// <param name="requestHeader"></param>
        /// <param name="server"></param>
        /// <param name="discoveryConfiguration"></param>
        /// <param name="configurationResults"></param>
        /// <param name="diagnosticInfos"></param>
        /// <returns></returns>
        public virtual ResponseHeader RegisterServer2(
            RequestHeader requestHeader,
            RegisteredServer server,
            ExtensionObjectCollection discoveryConfiguration,
            out StatusCodeCollection configurationResults,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            configurationResults = null;
            diagnosticInfos      = null;

            ValidateRequest(requestHeader);

            // Insert implementation.
            try
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ":服务注册:" + server.DiscoveryUrls.FirstOrDefault());
                RegisteredServerTable model = _serverTable.Where(d => d.ServerUri == server.ServerUri).FirstOrDefault();
                if (model != null)
                {
                    model.LastRegistered = DateTime.Now;
                }
                else
                {
                    model = new RegisteredServerTable()
                    {
                        DiscoveryUrls     = server.DiscoveryUrls,
                        GatewayServerUri  = server.GatewayServerUri,
                        IsOnline          = server.IsOnline,
                        LastRegistered    = DateTime.Now,
                        ProductUri        = server.ProductUri,
                        SemaphoreFilePath = server.SemaphoreFilePath,
                        ServerNames       = server.ServerNames,
                        ServerType        = server.ServerType,
                        ServerUri         = server.ServerUri
                    };
                    _serverTable.Add(model);
                }
                configurationResults = new StatusCodeCollection()
                {
                    StatusCodes.Good
                };
                return(CreateResponse(requestHeader, StatusCodes.Good));
            }
            catch (Exception ex)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("客户端调用RegisterServer2()注册服务时触发异常:" + ex.Message);
                Console.ResetColor();
            }
            return(CreateResponse(requestHeader, StatusCodes.BadUnexpectedError));
        }
示例#4
0
 public static Entry For(ExtensionObjectCollection collection)
 {
     if (collection == null)
     {
         return(new NullEntry());
     }
     else
     {
         ArrayEntry array = new ArrayEntry();
         ExtensionObjectCollection.Enumerator e = collection.GetEnumerator();
         while (e.MoveNext())
         {
             array.Add(For(e.Current));
         }
         return(array);
     }
 }
        public void HistoryUpdate(bool eventDetails)
        {
            HistoryUpdateResultCollection results         = null;
            DiagnosticInfoCollection      diagnosticInfos = null;

            // there are no historizing nodes, instead use some real nodes to test
            var testSet = GetTestSetSimulation(Session.NamespaceUris);

            // see https://reference.opcfoundation.org/v104/Core/docs/Part11/6.8.1/ as to why
            // history update of event, data or annotations should be called individually
            ExtensionObjectCollection historyUpdateDetails;

            if (eventDetails)
            {
                historyUpdateDetails = new ExtensionObjectCollection(
                    testSet.Select(nodeId => new ExtensionObject(new UpdateEventDetails()
                {
                    NodeId = nodeId,
                    PerformInsertReplace = PerformUpdateType.Insert
                })));
            }
            else
            {
                historyUpdateDetails = new ExtensionObjectCollection(
                    testSet.Select(nodeId => new ExtensionObject(
                                       new UpdateDataDetails()
                {
                    NodeId = nodeId,
                    PerformInsertReplace = PerformUpdateType.Replace
                })));
            }

            var responseHeader = Session.HistoryUpdate(
                null,
                historyUpdateDetails,
                out results,
                out diagnosticInfos);

            Session.ValidateResponse(results, historyUpdateDetails);
            Session.ValidateDiagnosticInfos(diagnosticInfos, historyUpdateDetails);
        }
        public async Task HistoryUpdateAsync(bool eventDetails)
        {
            // there are no historizing nodes, instead use some real nodes to test
            var testSet = GetTestSetSimulation(Session.NamespaceUris);

            // see https://reference.opcfoundation.org/v104/Core/docs/Part11/6.8.1/ as to why
            // history update of event, data or annotations should be called individually
            ExtensionObjectCollection historyUpdateDetails;

            if (eventDetails)
            {
                historyUpdateDetails = new ExtensionObjectCollection(
                    testSet.Select(nodeId => new ExtensionObject(new UpdateEventDetails()
                {
                    NodeId = nodeId,
                    PerformInsertReplace = PerformUpdateType.Insert
                })));
            }
            else
            {
                historyUpdateDetails = new ExtensionObjectCollection(
                    testSet.Select(nodeId => new ExtensionObject(
                                       new UpdateDataDetails()
                {
                    NodeId = nodeId,
                    PerformInsertReplace = PerformUpdateType.Replace
                })));
            }

            var response = await Session.HistoryUpdateAsync(
                null,
                historyUpdateDetails,
                CancellationToken.None).ConfigureAwait(false);

            Session.ValidateResponse(response.Results, historyUpdateDetails);
            Session.ValidateDiagnosticInfos(response.DiagnosticInfos, historyUpdateDetails);
        }
示例#7
0
        /// <summary>
        /// Updates the history for a set of nodes.
        /// </summary>
        public virtual void HistoryUpdate(
            OperationContext                  context,
            ExtensionObjectCollection         historyUpdateDetails,
            out HistoryUpdateResultCollection results,
            out DiagnosticInfoCollection      diagnosticInfos)
        {
            Type detailsType = null;
            List<HistoryUpdateDetails> nodesToUpdate = new List<HistoryUpdateDetails>();

            // verify that all extension objects in the list have the same type.
            foreach (ExtensionObject details in historyUpdateDetails)
            {
                if (detailsType == null)
                {
                    detailsType = details.Body.GetType();
                }

                if (!ExtensionObject.IsNull(details))
                {                
                    nodesToUpdate.Add(details.Body as HistoryUpdateDetails);
                }
            }
            
            // create result lists.
            bool diagnosticsExist = false;
            results = new HistoryUpdateResultCollection(nodesToUpdate.Count);
            diagnosticInfos = new DiagnosticInfoCollection(nodesToUpdate.Count);

            // pre-validate items.
            bool validItems = false;

            for (int ii = 0; ii < nodesToUpdate.Count; ii++)
            {
                HistoryUpdateResult result = null;
                DiagnosticInfo diagnosticInfo = null;

                // check the type of details parameter.
                ServiceResult error = null;

                if (nodesToUpdate[ii].GetType() != detailsType)
                {
                    error = StatusCodes.BadHistoryOperationInvalid;
                }

                // pre-validate and pre-parse parameter.
                else
                {
                    error = HistoryUpdateDetails.Validate(nodesToUpdate[ii]);
                }
                
                // return error status.
                if (ServiceResult.IsBad(error))
                {
                    nodesToUpdate[ii].Processed = true;
                    result = new HistoryUpdateResult();
                    result.StatusCode = error.Code;

                    // add diagnostics if requested.
                    if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                    {
                        diagnosticInfo = ServerUtils.CreateDiagnosticInfo(m_server, context, error);
                        diagnosticsExist = true;
                    }
                }

                // found at least one valid item.
                else
                {
                    nodesToUpdate[ii].Processed = false;
                    validItems = true;
                }

                results.Add(result);
                diagnosticInfos.Add(diagnosticInfo);
            } 
            
            // call each node manager.
            if (validItems)
            {
                List<ServiceResult> errors = new List<ServiceResult>(results.Count);

                for (int ii = 0; ii < nodesToUpdate.Count; ii++)
                {
                    errors.Add(null);
                }

                foreach (INodeManager nodeManager in m_nodeManagers)
                {
                    nodeManager.HistoryUpdate(
                        context,
                        detailsType,
                        nodesToUpdate,
                        results,
                        errors);
                }
                                
                for (int ii = 0; ii < nodesToUpdate.Count; ii++)
                {
                    HistoryUpdateResult result = results[ii];
 
                    // set an error code for nodes that were not handled by any node manager.
                    if (!nodesToUpdate[ii].Processed)
                    {
                        nodesToUpdate[ii].Processed = true;
                        result = results[ii] = new HistoryUpdateResult();
                        result.StatusCode = StatusCodes.BadNodeIdUnknown;
                        errors[ii] = result.StatusCode;
                    }
                    
                    // update the diagnostic info and ensure the status code in the result is the same as the error code.
                    if (errors[ii] != null && errors[ii].Code != StatusCodes.Good)
                    {
                        if (result == null)
                        {
                            result = results[ii] = new HistoryUpdateResult();
                        }

                        result.StatusCode = errors[ii].Code;
                                                
                        // add diagnostics if requested.
                        if ((context.DiagnosticsMask & DiagnosticsMasks.OperationAll) != 0)
                        {
                            diagnosticInfos[ii] = ServerUtils.CreateDiagnosticInfo(m_server, context, errors[ii]);
                            diagnosticsExist = true;
                        }
                    }
                }
            }

            // clear the diagnostics array if no diagnostics requested or no errors occurred.
            UpdateDiagnostics(context, diagnosticsExist, ref diagnosticInfos);
        }
示例#8
0
        /// <summary>
        /// Reads an extension object array from the stream.
        /// </summary>
        public ExtensionObjectCollection ReadExtensionObjectArray(string fieldName)
        {
            int length = ReadArrayLength();

            if (length == -1)
            {
                return null;
            }

            ExtensionObjectCollection values = new ExtensionObjectCollection(length);

            for (int ii = 0; ii < length; ii++)
            {
                values.Add(ReadExtensionObject(null));
            }

            return values;
        }
示例#9
0
        /// <summary>
        /// Calls the server and updates the history.
        /// </summary>
        private int[] UpdateHistory(
            Session session,
            List<HdaUpdateRequest> requests,
            bool checkOperationError)
        {
            int[] errors = new int[requests.Count];

            // build list of nodes to update.
            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();
            List<int> indexes = new List<int>();

            for (int ii = 0; ii < requests.Count; ii++)
            {
                if (requests[ii].Error < 0)
                {
                    errors[ii] = requests[ii].Error;
                    continue;
                }

                // check if nothing to do.
                if (requests[ii].Details == null)
                {
                    continue;
                }

                nodesToUpdate.Add(requests[ii].Details);
                indexes.Add(ii);
            }

            if (nodesToUpdate.Count == 0)
            {
                return errors;
            }

            // call the server.
            HistoryUpdateResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

            Session.ValidateResponse(results, nodesToUpdate);
            Session.ValidateDiagnosticInfos(diagnosticInfos, nodesToUpdate);

            // process results.
            for (int ii = 0; ii < nodesToUpdate.Count; ii++)
            {
                HdaUpdateRequest request = requests[indexes[ii]];

                request.Error = MapUpdateStatusToErrorCode(results[ii].StatusCode);

                if (checkOperationError)
                {
                    if (StatusCode.IsGood(results[ii].StatusCode))
                    {
                        request.Error = MapUpdateStatusToErrorCode(results[ii].OperationResults[0]);
                    }
                }

                errors[indexes[ii]] = request.Error;
            }

            return errors;
        }
示例#10
0
        /// <summary>
        /// Deletes the history.
        /// </summary>
        private void DeleteAtTime()
        {
            DeleteAtTimeDetails details = new DeleteAtTimeDetails();
            details.NodeId = m_nodeId;

            foreach (DataRowView row in m_dataset.Tables[0].DefaultView)
            {
                DateTime value = (DateTime)row.Row[1];
                details.ReqTimes.Add(value);
            }

            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();
            nodesToUpdate.Add(new ExtensionObject(details));

            HistoryUpdateResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            ResultsDV.Columns[ResultsDV.Columns.Count-1].Visible = true;

            for (int ii = 0; ii < m_dataset.Tables[0].DefaultView.Count; ii++)
            {
                m_dataset.Tables[0].DefaultView[ii].Row[10] = results[0].OperationResults[ii];
            }

            m_dataset.AcceptChanges();
        }
        /// <summary>
        /// Invokes the RegisterServer2 service.
        /// </summary>
        public virtual ResponseHeader RegisterServer2(
            RequestHeader                requestHeader,
            RegisteredServer             server,
            ExtensionObjectCollection    discoveryConfiguration,
            out StatusCodeCollection     configurationResults,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            configurationResults = null;
            diagnosticInfos = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
示例#12
0
        /// <summary>
        /// Deletes the history of values for a set of variables at given time interval.
        /// </summary>
        static void HistoryDeleteRaw(Session session)
        {
            // translate browse paths.
            IList<NodeOfInterest> results = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder, 
                VariableBrowsePaths.ToArray());


            DiagnosticInfoCollection diagnosticInfos;

            ExtensionObjectCollection eoc = new ExtensionObjectCollection();
            for (int ii = 0; ii < results.Count; ii++)
            {
                DeleteRawModifiedDetails deleteDetails = new DeleteRawModifiedDetails();
                deleteDetails.StartTime = new DateTime(2008, 1, 1, 12, 0, 0);
                deleteDetails.EndTime = new DateTime(2008, 1, 1, 12, 0, 10);

                deleteDetails.NodeId = results[ii].NodeId;
                deleteDetails.IsDeleteModified = false;

                ExtensionObject eo = new ExtensionObject(deleteDetails.TypeId, deleteDetails);
                eoc.Add(eo);
            }

            HistoryUpdateResultCollection historyUpdateResults;

            ResponseHeader responseHeader =
                session.HistoryUpdate(null, eoc, out historyUpdateResults, out diagnosticInfos);

            // process results.

            for (int ii = 0; ii < historyUpdateResults.Count; ii++)
            {
                HistoryUpdateResult historyUpdateResult = historyUpdateResults[ii];

                Console.WriteLine("HistoryUpdate result code for {0}:  {1}", VariableBrowsePaths[ii], historyUpdateResult.StatusCode.ToString());

                if (StatusCode.IsGood(historyUpdateResult.StatusCode))
                {
                    for (int jj = 0; jj < historyUpdateResult.OperationResults.Count; jj++)
                    {
                        Console.WriteLine("    {0}: {1}", jj, historyUpdateResult.OperationResults[jj]);
                    }
                    Console.WriteLine("");
                }
            }
        }
        /// <summary>
        /// Invokes the HistoryUpdate service.
        /// </summary>
        /// <param name="requestHeader">The request header.</param>
        /// <param name="historyUpdateDetails">The details defined for the update.</param>
        /// <param name="results">The list of update results for the history update details.</param>
        /// <param name="diagnosticInfos">The diagnostic information for the results.</param>
        /// <returns>
        /// Returns a <see cref="ResponseHeader"/> object
        /// </returns>
        public override ResponseHeader HistoryUpdate(
            RequestHeader                     requestHeader,
            ExtensionObjectCollection         historyUpdateDetails,
            out HistoryUpdateResultCollection results,
            out DiagnosticInfoCollection      diagnosticInfos)
        {   
            OperationContext context = ValidateRequest(requestHeader, RequestType.HistoryUpdate);
            
            try
            {
                if (historyUpdateDetails == null || historyUpdateDetails.Count == 0)
                {            
                    throw new ServiceResultException(StatusCodes.BadNothingToDo);
                }

                m_serverInternal.NodeManager.HistoryUpdate(
                    context,
                    historyUpdateDetails,
                    out results,
                    out diagnosticInfos);            

                return CreateResponse(requestHeader, context.StringTable);    
            }
            catch (ServiceResultException e)
            {
                lock (ServerInternal.DiagnosticsLock)
                {
                    ServerInternal.ServerDiagnostics.RejectedRequestsCount++;

                    if (IsSecurityError(e.StatusCode))
                    {
                        ServerInternal.ServerDiagnostics.SecurityRejectedRequestsCount++;
                    }
                }

                throw TranslateException(context, e);
            }  
            finally
            {
                OnRequestComplete(context);
            }
        }
示例#14
0
        /// <summary>
        /// Updates the history.
        /// </summary>
        private HistoryUpdateResultCollection InsertReplace(NodeId nodeId, PerformUpdateType updateType, bool isStructure, IList<DataValue> values)
        {
            HistoryUpdateDetails details = null;

            if (isStructure)
            {
                UpdateStructureDataDetails details2 = new UpdateStructureDataDetails();
                details2.NodeId = nodeId;
                details2.PerformInsertReplace = updateType;
                details2.UpdateValues.AddRange(values);
                details = details2;
            }
            else
            {
                UpdateDataDetails details2 = new UpdateDataDetails();
                details2.NodeId = nodeId;
                details2.PerformInsertReplace = updateType;
                details2.UpdateValues.AddRange(values);
                details = details2;
            }

            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();
            nodesToUpdate.Add(new ExtensionObject(details));

            HistoryUpdateResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            return results;
        }
示例#15
0
        public void ExtensionObject()
        {
            ExtensionObject extensionObject_null = null;
            // Validate the default constructor
            ExtensionObject extensionObject_Default = new Ua.ExtensionObject();

            Assert.NotNull(extensionObject_Default);
            Assert.AreEqual(ExpandedNodeId.Null, extensionObject_Default.TypeId);
            Assert.AreEqual(ExtensionObjectEncoding.None, extensionObject_Default.Encoding);
            Assert.Null(extensionObject_Default.Body);
            // Constructor by ExtensionObject
            ExtensionObject extensionObject = new ExtensionObject(ExpandedNodeId.Null);

            Assert.NotNull(extensionObject);
            Assert.AreEqual(ExpandedNodeId.Null, extensionObject.TypeId);
            Assert.AreEqual(ExtensionObjectEncoding.None, extensionObject.Encoding);
            Assert.Null(extensionObject.Body);
            // static extensions
            Assert.True(Ua.ExtensionObject.IsNull(extensionObject));
            Assert.Null(Ua.ExtensionObject.ToEncodeable(null));
            Assert.Null(Ua.ExtensionObject.ToArray(null, typeof(object)));
            Assert.Null(Ua.ExtensionObject.ToList <object>(null));
            // constructor by ExpandedNodeId
            extensionObject = new ExtensionObject((ExpandedNodeId)null);
            Assert.AreEqual(0, extensionObject.GetHashCode());
            Assert.Throws <ArgumentNullException>(() => new ExtensionObject(extensionObject_null));
            Assert.Throws <ServiceResultException>(() => new ExtensionObject(new object()));
            // constructor by object
            object byteArray = new byte[] { 1, 2, 3 };

            extensionObject = new ExtensionObject(byteArray);
            Assert.NotNull(extensionObject);
            Assert.AreEqual(extensionObject, extensionObject);
            // string extension
            var extensionObjectString = extensionObject.ToString();

            Assert.Throws <FormatException>(() => extensionObject.ToString("123", null));
            Assert.NotNull(extensionObjectString);
            // clone
            var clonedExtensionObject = (ExtensionObject)Utils.Clone(extensionObject);

            Assert.AreEqual(extensionObject, clonedExtensionObject);
            // IsEqual operator
            clonedExtensionObject.TypeId = new ExpandedNodeId(333);
            Assert.AreNotEqual(extensionObject, clonedExtensionObject);
            Assert.AreNotEqual(extensionObject, extensionObject_Default);
            Assert.AreNotEqual(extensionObject, new object());
            Assert.AreEqual(clonedExtensionObject, clonedExtensionObject);
            Assert.AreEqual(ExpandedNodeId.Null, extensionObject.TypeId);
            Assert.AreEqual(ExpandedNodeId.Null.GetHashCode(), extensionObject.TypeId.GetHashCode());
            Assert.AreEqual(ExtensionObjectEncoding.Binary, extensionObject.Encoding);
            Assert.AreEqual(byteArray, extensionObject.Body);
            Assert.AreEqual(byteArray.GetHashCode(), extensionObject.Body.GetHashCode());
            // collection
            ExtensionObjectCollection collection = new ExtensionObjectCollection();

            Assert.NotNull(collection);
            collection = new ExtensionObjectCollection(100);
            Assert.NotNull(collection);
            collection = new ExtensionObjectCollection(collection);
            Assert.NotNull(collection);
            collection = (ExtensionObjectCollection)collection.MemberwiseClone();
            // default value is null
            Assert.Null(TypeInfo.GetDefaultValue(BuiltInType.ExtensionObject));
        }
示例#16
0
        /// <summary>
        /// Deletes the recent history.
        /// </summary>
        private void DeleteHistory(NodeId areaId, List<VariantCollection> events, FilterDeclaration filter)
        {
            // find the event id.
            int index = 0;

            foreach (FilterDeclarationField field in filter.Fields)
            {
                if (field.InstanceDeclaration.BrowseName == Opc.Ua.BrowseNames.EventId)
                {
                    break;
                }

                index++;
            }

            // can't delete events if no event id.
            if (index >= filter.Fields.Count)
            {
                throw ServiceResultException.Create(StatusCodes.BadEventIdUnknown, "Cannot delete events if EventId was not selected.");
            }

            // build list of nodes to delete.
            DeleteEventDetails details = new DeleteEventDetails();
            details.NodeId = areaId;

            foreach (VariantCollection e in events)
            {
                byte[] eventId = null;

                if (e.Count > index)
                {
                    eventId = e[index].Value as byte[];
                }

                details.EventIds.Add(eventId);
            }

            // delete the events.
            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();
            nodesToUpdate.Add(new ExtensionObject(details));

            HistoryUpdateResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            // check for item level errors.
            if (results[0].OperationResults.Count > 0)
            {
                int count = 0;

                for (int ii = 0; ii < results[0].OperationResults.Count; ii++)
                {
                    if (StatusCode.IsBad(results[0].OperationResults[ii]))
                    {
                        count++;
                    }
                }

                // raise an error.
                if (count > 0)
                {
                    throw ServiceResultException.Create(
                        StatusCodes.BadEventIdUnknown, 
                        "Error deleting events. Only {0} of {1} deletes succeeded.",
                        events.Count - count,
                        events.Count);
                }
            }
        }
示例#17
0
 public override ResponseHeader RegisterServer2(RequestHeader requestHeader, RegisteredServer server, ExtensionObjectCollection discoveryConfiguration, out StatusCodeCollection configurationResults, out DiagnosticInfoCollection diagnosticInfos)
 {
     return(base.RegisterServer2(requestHeader, server, discoveryConfiguration, out configurationResults, out diagnosticInfos));
 }
        /// <summary>
        /// Reads an array of extension objects from the stream.
        /// </summary>
        public ExtensionObjectCollection ReadExtensionObjectArray(string fieldName)
        {
            var values = new ExtensionObjectCollection();

            List<object> token = null;

            if (!ReadArrayField(fieldName, out token))
            {
                return values;
            }

            for (int ii = 0; ii < token.Count; ii++)
            {
                try
                {
                    m_stack.Push(token[ii]);
                    var element = ReadExtensionObject(null);
                    values.Add(element);
                }
                finally
                {
                    m_stack.Pop();
                }
            }

            return values;
        }        
示例#19
0
        /// <summary>
        /// Begins an asynchronous invocation of the RegisterServer2 service.
        /// </summary>
        public IAsyncResult BeginRegisterServer2(
            RequestHeader             requestHeader,
            RegisteredServer          server,
            ExtensionObjectCollection discoveryConfiguration,
            AsyncCallback             callback,
            object                    asyncState)
        {
            RegisterServer2Request request = new RegisterServer2Request();

            request.RequestHeader          = requestHeader;
            request.Server                 = server;
            request.DiscoveryConfiguration = discoveryConfiguration;

            UpdateRequestHeader(request, requestHeader == null, "RegisterServer2");

            if (UseTransportChannel)
            {
                return TransportChannel.BeginSendRequest(request, callback, asyncState);
            }

            return InnerChannel.BeginRegisterServer2(new RegisterServer2Message(request), callback, asyncState);
        }
示例#20
0
        /// <summary>
        /// Invokes the RegisterServer2 service.
        /// </summary>
        public virtual ResponseHeader RegisterServer2(
            RequestHeader                requestHeader,
            RegisteredServer             server,
            ExtensionObjectCollection    discoveryConfiguration,
            out StatusCodeCollection     configurationResults,
            out DiagnosticInfoCollection diagnosticInfos)
        {
            RegisterServer2Request request = new RegisterServer2Request();
            RegisterServer2Response response = null;

            request.RequestHeader          = requestHeader;
            request.Server                 = server;
            request.DiscoveryConfiguration = discoveryConfiguration;

            UpdateRequestHeader(request, requestHeader == null, "RegisterServer2");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (RegisterServer2Response)genericResponse;
                }
                else
                {
                    RegisterServer2ResponseMessage responseMessage = InnerChannel.RegisterServer2(new RegisterServer2Message(request));

                    if (responseMessage == null || responseMessage.RegisterServer2Response == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.RegisterServer2Response;
                    ValidateResponse(response.ResponseHeader);
                }

                configurationResults = response.ConfigurationResults;
                diagnosticInfos      = response.DiagnosticInfos;
            }
            finally
            {
                RequestCompleted(request, response, "RegisterServer2");
            }

            return response.ResponseHeader;
        }
示例#21
0
        /// <summary>
        /// Deletes the recent history.
        /// </summary>
        private void DeleteHistory(NodeId areaId, List <VariantCollection> events, FilterDeclaration filter)
        {
            // find the event id.
            int index = 0;

            foreach (FilterDeclarationField field in filter.Fields)
            {
                if (field.InstanceDeclaration.BrowseName == Opc.Ua.BrowseNames.EventId)
                {
                    break;
                }

                index++;
            }

            // can't delete events if no event id.
            if (index >= filter.Fields.Count)
            {
                throw ServiceResultException.Create(StatusCodes.BadEventIdUnknown, "Cannot delete events if EventId was not selected.");
            }

            // build list of nodes to delete.
            DeleteEventDetails details = new DeleteEventDetails();

            details.NodeId = areaId;

            foreach (VariantCollection e in events)
            {
                byte[] eventId = null;

                if (e.Count > index)
                {
                    eventId = e[index].Value as byte[];
                }

                details.EventIds.Add(eventId);
            }

            // delete the events.
            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();

            nodesToUpdate.Add(new ExtensionObject(details));

            HistoryUpdateResultCollection results         = null;
            DiagnosticInfoCollection      diagnosticInfos = null;

            m_session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            // check for item level errors.
            if (results[0].OperationResults.Count > 0)
            {
                int count = 0;

                for (int ii = 0; ii < results[0].OperationResults.Count; ii++)
                {
                    if (StatusCode.IsBad(results[0].OperationResults[ii]))
                    {
                        count++;
                    }
                }

                // raise an error.
                if (count > 0)
                {
                    throw ServiceResultException.Create(
                              StatusCodes.BadEventIdUnknown,
                              "Error deleting events. Only {0} of {1} deletes succeeded.",
                              events.Count - count,
                              events.Count);
                }
            }
        }
示例#22
0
        /// <summary>
        /// Registers the server with the discovery server.
        /// </summary>
        /// <returns>Boolean value.</returns>
        public bool RegisterWithDiscoveryServer()
        {
            ApplicationConfiguration configuration = string.IsNullOrEmpty(base.Configuration.SourceFilePath) ? base.Configuration : ApplicationConfiguration.Load(new FileInfo(base.Configuration.SourceFilePath), ApplicationType.Server, null, false);
            CertificateValidationEventHandler registrationCertificateValidator = new CertificateValidationEventHandler(RegistrationValidator_CertificateValidation);
            configuration.CertificateValidator.CertificateValidation += registrationCertificateValidator;            

            try
            {
                // try each endpoint.
                foreach (ConfiguredEndpoint endpoint in m_registrationEndpoints.Endpoints)
                {
                    RegistrationClient client = null;

                    try
                    {
                        // update from the server.
                        bool updateRequired = true;

                        lock (m_registrationLock)
                        {
                            updateRequired = endpoint.UpdateBeforeConnect;
                        }

                        if (updateRequired)
                        {
                            endpoint.UpdateFromServer(m_bindingFactory);
                        }

                        lock (m_registrationLock)
                        {
                            endpoint.UpdateBeforeConnect = false;
                        }

                        // create the client.
                        client = RegistrationClient.Create(
                            configuration,
                            endpoint.Description,
                            endpoint.Configuration,
                            m_bindingFactory,
                            base.InstanceCertificate);

                        // register the server.
                        RequestHeader requestHeader = new RequestHeader();
                        requestHeader.Timestamp = DateTime.UtcNow;
                        client.OperationTimeout = 10000;

                        try
                        {
                            ExtensionObjectCollection discoveryConfiguration = new ExtensionObjectCollection();
                            StatusCodeCollection configurationResults = null;
                            DiagnosticInfoCollection diagnosticInfos = null;

                            client.RegisterServer2(
                                requestHeader,
                                m_registrationInfo,
                                discoveryConfiguration,
                                out configurationResults,
                                out diagnosticInfos);

                            return true;
                        }
                        catch (Exception e)
                        {
                            // fall back to calling RegisterServer in case RegisterServer2 fails.
                            Utils.Trace("RegisterServer2 failed for: {0}. Falling back to RegisterServer. Exception={1}.", endpoint.EndpointUrl, e.Message);

                            client.RegisterServer(requestHeader, m_registrationInfo);
                            return true;
                        }
                    }
                    catch (Exception e)
                    {
                        Utils.Trace("RegisterServer failed for: {0}. Exception={1}", endpoint.EndpointUrl, e.Message);
                    }
                    finally
                    {
                        if (client != null)
                        {
                            try
                            {
                                client.Close();
                            }
                            catch (Exception e)
                            {
                                Utils.Trace("Could not cleanly close connection with LDS. Exception={0}", e.Message);
                            }
                        }
                    }
                }
            }
            finally
            {
                if (configuration != null)
                {
                    configuration.CertificateValidator.CertificateValidation -= registrationCertificateValidator;
                }
            }

            return false;
        }
示例#23
0
        /// <summary>
        /// Invokes the HistoryUpdate service.
        /// </summary>
        public virtual ResponseHeader HistoryUpdate(
            RequestHeader                     requestHeader,
            ExtensionObjectCollection         historyUpdateDetails,
            out HistoryUpdateResultCollection results,
            out DiagnosticInfoCollection      diagnosticInfos)
        {
            HistoryUpdateRequest request = new HistoryUpdateRequest();
            HistoryUpdateResponse response = null;

            request.RequestHeader        = requestHeader;
            request.HistoryUpdateDetails = historyUpdateDetails;

            UpdateRequestHeader(request, requestHeader == null, "HistoryUpdate");

            try
            {
                if (UseTransportChannel)
                {
                    IServiceResponse genericResponse = TransportChannel.SendRequest(request);

                    if (genericResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    ValidateResponse(genericResponse.ResponseHeader);
                    response = (HistoryUpdateResponse)genericResponse;
                }
                else
                {
                    HistoryUpdateResponseMessage responseMessage = InnerChannel.HistoryUpdate(new HistoryUpdateMessage(request));

                    if (responseMessage == null || responseMessage.HistoryUpdateResponse == null)
                    {
                        throw new ServiceResultException(StatusCodes.BadUnknownResponse);
                    }

                    response = responseMessage.HistoryUpdateResponse;
                    ValidateResponse(response.ResponseHeader);
                }

                results         = response.Results;
                diagnosticInfos = response.DiagnosticInfos;
            }
            finally
            {
                RequestCompleted(request, response, "HistoryUpdate");
            }

            return response.ResponseHeader;
        }
示例#24
0
        static void HistoryUpdate(Session session)
        {
            DiagnosticInfoCollection diagnosticInfos;

            // translate browse paths.
            IList<NodeOfInterest> nodeIds;

            nodeIds = GetNodeIds(session, Opc.Ua.Objects.ObjectsFolder,
                VariableBrowsePaths.ToArray());

            ExtensionObjectCollection eoc = new ExtensionObjectCollection();
            for (int ii = 0; ii < nodeIds.Count; ii++)
            {
                UpdateDataDetails updateDetails = new UpdateDataDetails();

                updateDetails.NodeId = nodeIds[ii].NodeId;
                updateDetails.PerformInsertReplace = PerformUpdateType.Update;
                updateDetails.UpdateValues = new DataValueCollection();

                for (int jj = 0; jj <= 5; jj++)
                {
                    DataValue dv = new DataValue(new Variant(jj*10), StatusCodes.Good, new DateTime(2008, 01, 01, 12, 0, jj*2));
                    updateDetails.UpdateValues.Add(dv);
                }
                ExtensionObject eo = new ExtensionObject(updateDetails.TypeId, updateDetails);
                eoc.Add(eo);
            }

            HistoryUpdateResultCollection historyUpdateResults;

            ResponseHeader responseHeader =
                session.HistoryUpdate(null, eoc, out historyUpdateResults, out diagnosticInfos);

            
            // process results.

            for (int ii = 0; ii < historyUpdateResults.Count; ii++)
            {
                HistoryUpdateResult historyUpdateResult = historyUpdateResults[ii];

                Console.WriteLine("HistoryUpdate result code for {0}:  {1}", VariableBrowsePaths[ii], historyUpdateResult.StatusCode.ToString());

                if (StatusCode.IsGood(historyUpdateResult.StatusCode))
                {
                    for (int jj = 0; jj < historyUpdateResult.OperationResults.Count; jj++)
                    {
                        Console.WriteLine("    {0}: {1}", jj, historyUpdateResult.OperationResults[jj]);
                    }
                    Console.WriteLine("");
                }
            }
        }
示例#25
0
        /// <summary>
        /// Begins an asynchronous invocation of the HistoryUpdate service.
        /// </summary>
        public IAsyncResult BeginHistoryUpdate(
            RequestHeader             requestHeader,
            ExtensionObjectCollection historyUpdateDetails,
            AsyncCallback             callback,
            object                    asyncState)
        {
            HistoryUpdateRequest request = new HistoryUpdateRequest();

            request.RequestHeader        = requestHeader;
            request.HistoryUpdateDetails = historyUpdateDetails;

            UpdateRequestHeader(request, requestHeader == null, "HistoryUpdate");

            if (UseTransportChannel)
            {
                return TransportChannel.BeginSendRequest(request, callback, asyncState);
            }

            return InnerChannel.BeginHistoryUpdate(new HistoryUpdateMessage(request), callback, asyncState);
        }
示例#26
0
        /// <summary>
        /// Reads an array of extension objects from the stream.
        /// </summary>
        public ExtensionObjectCollection ReadExtensionObjectArray(string fieldName)
        {
            bool isNil = false;

            ExtensionObjectCollection values = new ExtensionObjectCollection();
                                    
            if (BeginField(fieldName, true, out isNil))
            {                                
                PushNamespace(Namespaces.OpcUaXsd);
                
                while (MoveToElement("ExtensionObject"))
                {
                    values.Add(ReadExtensionObject("ExtensionObject"));
                }

                // check the length.
                if (m_context.MaxArrayLength > 0 && m_context.MaxArrayLength < values.Count)
                {
                    throw new ServiceResultException(StatusCodes.BadEncodingLimitsExceeded);
                }

                PopNamespace();

                EndField(fieldName);
                return values;
            }

            if (isNil)
            {
                return null;
            }

            return values;
        }        
        /// <summary>
        /// Registers the server with the discovery server.
        /// </summary>
        /// <returns>Boolean value.</returns>
        public async Task<bool> RegisterWithDiscoveryServer()
        {
            ApplicationConfiguration configuration = string.IsNullOrEmpty(base.Configuration.SourceFilePath) ? base.Configuration : await ApplicationConfiguration.Load(new FileInfo(base.Configuration.SourceFilePath), ApplicationType.Server, null, false);
            CertificateValidationEventHandler registrationCertificateValidator = new CertificateValidationEventHandler(RegistrationValidator_CertificateValidation);
            configuration.CertificateValidator.CertificateValidation += registrationCertificateValidator;            

            try
            {
                // try each endpoint.
                if (m_registrationEndpoints != null)
                {
                    foreach (ConfiguredEndpoint endpoint in m_registrationEndpoints.Endpoints)
                    {
                        RegistrationClient client = null;
                        int i = 0;

                        while (i++ < 2)
                        {
                            try
                            {
                                // update from the server.
                                bool updateRequired = true;

                                lock (m_registrationLock)
                                {
                                    updateRequired = endpoint.UpdateBeforeConnect;
                                }

                                if (updateRequired)
                                {
                                    endpoint.UpdateFromServer();
                                }

                                lock (m_registrationLock)
                                {
                                    endpoint.UpdateBeforeConnect = false;
                                }

                                RequestHeader requestHeader = new RequestHeader();
                                requestHeader.Timestamp = DateTime.UtcNow;

                                // create the client.
                                client = RegistrationClient.Create(
                                    configuration,
                                    endpoint.Description,
                                    endpoint.Configuration,
                                    base.InstanceCertificate);

                                client.OperationTimeout = 10000;

                                // register the server.
                                if (m_useRegisterServer2)
                                {
                                    ExtensionObjectCollection discoveryConfiguration = new ExtensionObjectCollection();
                                    StatusCodeCollection configurationResults = null;
                                    DiagnosticInfoCollection diagnosticInfos = null;

                                    client.RegisterServer2(
                                        requestHeader,
                                        m_registrationInfo,
                                        discoveryConfiguration,
                                        out configurationResults,
                                        out diagnosticInfos);
                                }
                                else
                                {
                                    client.RegisterServer(requestHeader, m_registrationInfo);
                                }

                                return true;
                            }
                            catch (Exception e)
                            {
                                Utils.Trace("RegisterServer{0} failed for at: {1}. Exception={2}",
                                    m_useRegisterServer2 ? "2" : "", endpoint.EndpointUrl, e.Message);
                                m_useRegisterServer2 = !m_useRegisterServer2;
                            }
                            finally
                            {
                                if (client != null)
                                {
                                    try
                                    {
                                        client.Close();
                                        client = null;
                                    }
                                    catch (Exception e)
                                    {
                                        Utils.Trace("Could not cleanly close connection with LDS. Exception={0}", e.Message);
                                    }
                                }
                            }
                        }
                    }
                    // retry to start with RegisterServer2 if both failed
                    m_useRegisterServer2 = true;
                }
            }
            finally
            {
                if (configuration != null)
                {
                    configuration.CertificateValidator.CertificateValidation -= registrationCertificateValidator;
                }
            }            
            
            return false;
        }
        /// <summary>
        /// Invokes the HistoryUpdate service.
        /// </summary>
        public virtual ResponseHeader HistoryUpdate(
            RequestHeader                     requestHeader,
            ExtensionObjectCollection         historyUpdateDetails,
            out HistoryUpdateResultCollection results,
            out DiagnosticInfoCollection      diagnosticInfos)
        {
            results = null;
            diagnosticInfos = null;

            ValidateRequest(requestHeader);

            // Insert implementation.

            return CreateResponse(requestHeader, StatusCodes.BadServiceUnsupported);
        }
示例#29
0
        /// <summary>
        /// Deletes the block of data.
        /// </summary>
        private void DeleteRaw(bool isModified)
        {
            DeleteRawModifiedDetails details = new DeleteRawModifiedDetails();
            details.NodeId = m_nodeId;
            details.IsDeleteModified = isModified;
            details.StartTime = StartTimeDP.Value;
            details.EndTime = EndTimeDP.Value;

            ExtensionObjectCollection nodesToUpdate = new ExtensionObjectCollection();
            nodesToUpdate.Add(new ExtensionObject(details));

            HistoryUpdateResultCollection results = null;
            DiagnosticInfoCollection diagnosticInfos = null;

            m_session.HistoryUpdate(
                null,
                nodesToUpdate,
                out results,
                out diagnosticInfos);

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

            if (StatusCode.IsBad(results[0].StatusCode))
            {
                throw new ServiceResultException(results[0].StatusCode);
            }

            ResultsDV.Columns[ResultsDV.Columns.Count - 1].Visible = false;
            m_dataset.Clear();
        }