/// <summary>
 /// Constructs a new instance.
 /// </summary>
 public DataChangeMonitoredItem(
     MonitoredNode source,
     uint id,
     uint attributeId,
     NumericRange indexRange,
     QualifiedName dataEncoding,
     DiagnosticsMasks diagnosticsMasks,
     TimestampsToReturn timestampsToReturn,
     MonitoringMode monitoringMode,
     uint clientHandle,
     double samplingInterval,
     bool alwaysReportUpdates)
 {
     m_source = source;
     m_id = id;
     m_attributeId = attributeId;
     m_indexRange = indexRange;
     m_dataEncoding = dataEncoding;
     m_timestampsToReturn = timestampsToReturn;
     m_diagnosticsMasks = diagnosticsMasks;
     m_monitoringMode = monitoringMode;
     m_clientHandle = clientHandle;
     m_samplingInterval = samplingInterval;
     m_nextSampleTime = DateTime.UtcNow.Ticks;
     m_readyToPublish = false;
     m_readyToTrigger = false;
     m_alwaysReportUpdates = alwaysReportUpdates;
 }
Example #2
0
			public static void AddUnknownFunctionCall(QualifiedName name)
			{
                var info = StaticInfo.Get;
                if (info.UnknownCalls == null) info.UnknownCalls = new Dictionary<QualifiedName, int>();

                CollectionUtils.IncrementValue(info.UnknownCalls, name, 1);
			}
Example #3
0
        public INamedTypeSymbol GetType(QualifiedName name)
        {
            // std // TODO: table of types in PchpCor
            if (name == NameUtils.SpecialNames.stdClass)
            {
                return _compilation.PhpCorLibrary.GetTypeByMetadataName(name.ClrName());
            }

            // TODO: reserved type names: self, parent, static
            Debug.Assert(!name.IsReservedClassName);

            // library types
            foreach (AssemblySymbol ass in _compilation.ProbingAssemblies)
            {
                if (!ass.IsPchpCorLibrary)
                {
                    var candidate = ass.GetTypeByMetadataName(name.ClrName());
                    if (candidate != null && !candidate.IsErrorType())
                    {
                        if (ass is PEAssemblySymbol && ((PEAssemblySymbol)ass).IsExtensionLibrary && candidate.IsStatic)
                        {
                            continue;
                        }

                        return candidate;
                    }
                }
            }

            //
            return Next.GetType(name);
        }
Example #4
0
        public DirectFcnCall(Text.Span span,
            QualifiedName qualifiedName, QualifiedName? fallbackQualifiedName, Text.Span qualifiedNameSpan,
            List<ActualParam>/*!*/ parameters, List<TypeRef>/*!*/ genericParams)
            : base(span, qualifiedNameSpan, parameters, genericParams)
		{
            this.qualifiedName = qualifiedName;
            this.fallbackQualifiedName = fallbackQualifiedName;
		}
Example #5
0
        public DirectFcnCall(Position position,
            QualifiedName qualifiedName, QualifiedName? fallbackQualifiedName, Position qualifiedNamePosition,
            List<ActualParam>/*!*/ parameters, List<TypeRef>/*!*/ genericParams)
            : base(position, qualifiedNamePosition, parameters, genericParams)
		{
            this.qualifiedName = qualifiedName;
            this.fallbackQualifiedName = fallbackQualifiedName;
		}
 public void QualifiedNameTestMethod1()
 {
     string name = "Default Binary";
       QualifiedName _qn = new QualifiedName("Default Binary");
       Assert.IsNotNull(_qn);
       //Assert.AreEqual<int>(_qn.NamespaceIndex, 0);
       Assert.IsFalse(_qn.NamespaceIndexSpecified);
       Assert.AreEqual<string>(_qn.Name, name);
 }
 private NamespaceImportDeclaration CreateNamespaceImport() {
   NameDeclaration dummyName = new NameDeclaration(Dummy.Name, SourceDummy.SourceLocation);
   SimpleName microsoft = new SimpleName(this.Compilation.NameTable.GetNameFor("Microsoft"), SourceDummy.SourceLocation, false);
   SimpleName smallBasic = new SimpleName(this.Compilation.NameTable.GetNameFor("SmallBasic"), SourceDummy.SourceLocation, false);
   SimpleName library = new SimpleName(this.Compilation.NameTable.GetNameFor("Library"), SourceDummy.SourceLocation, false);
   QualifiedName microsoftSmallBasic = new QualifiedName(microsoft, smallBasic, SourceDummy.SourceLocation);
   QualifiedName microsoftSmallBasicLibrary = new QualifiedName(microsoftSmallBasic, library, SourceDummy.SourceLocation);
   NamespaceReferenceExpression smallBasicLibrary = new NamespaceReferenceExpression(microsoftSmallBasicLibrary, SourceDummy.SourceLocation);
   return new NamespaceImportDeclaration(dummyName, smallBasicLibrary, SourceDummy.SourceLocation);
 }
Example #8
0
 /// <summary>Creates functions or procedure</summary>
 public Function(QualifiedName name, IList<ParameterDescription> inputs, IList<ParameterDescription> outputs, IList<ParameterDescription> inouts, ParameterDescription returning, AccessModifier visibility = AccessModifier.Private)
 {
     QualifiedName = name;
     Profile = new ParametersProfile();
     Profile.InputParameters  = inputs  ?? new List<ParameterDescription>();
     Profile.OutputParameters = outputs ?? new List<ParameterDescription>();
     Profile.InoutParameters  = inouts  ?? new List<ParameterDescription>();
     Profile.ReturningParameter = returning;
     Visibility = visibility;
 }
        protected ReflectedProviderFactoryDefinitionBase(MethodBase method,
                                                         QualifiedName qname,
                                                         Type outputType)
        {
            this.qname = qname;
            this.outputType = outputType;
            this.method = method;

            this.parameters = new PropertyDefinitionCollection();
            parameters.AddRange(this, qname.NamespaceName, method.GetParameters(), method.IsExtension());
        }
Example #10
0
 private static QualifiedName GetUniqueName(CodeTypeMember member, QualifiedName parentName)
 {
     if (member is CodeTypeDeclaration)
     {
         return new QualifiedName(GetUniqueName((CodeTypeDeclaration)member), null);
     }
     else
     {
         return new QualifiedName(GetUniqueName(member), parentName);
     }
 }
		public override void FixtureInit()
		{
			// Note element path.
			noteElementPath = new XmlElementPath();
			QualifiedName noteQualifiedName = new QualifiedName("note", "http://www.w3schools.com");
			noteElementPath.Elements.Add(noteQualifiedName);
		
			// Text element path.
			textElementPath = new XmlElementPath();
			textElementPath.Elements.Add(noteQualifiedName);
			textElementPath.Elements.Add(new QualifiedName("text", "http://www.w3schools.com"));
		}	
Example #12
0
 /// <summary>
 /// Creates a new instance of the node.
 /// </summary>
 public static MethodSource Construct(
     IServerInternal server, 
     NodeSource      parent, 
     NodeId          referenceTypeId,
     NodeId          nodeId,
     QualifiedName   browseName,
     uint            numericId)
 {
     MethodSource instance = new MethodSource(server, parent);
     instance.Initialize(referenceTypeId, nodeId, browseName, numericId, null);
     return instance;
 }
Example #13
0
 /// <summary>
 /// Creates a new instance of the node.
 /// </summary>
 public static ObjectSource Construct(
     IServerInternal server, 
     NodeSource      parent, 
     NodeId          referenceTypeId,
     NodeId          nodeId,
     QualifiedName   browseName,
     uint            numericId)
 {
     ObjectSource instance = new ObjectSource(server, parent);
     instance.Initialize(referenceTypeId, nodeId, browseName, numericId, ObjectTypes.BaseObjectType);
     return instance;
 }
Example #14
0
 private static void EnumerareCodeMembers(CodeTypeMember member, QualifiedName parentName, Dictionary<string, CodeTypeMember> members)
 {
     QualifiedName memberName = GetUniqueName(member, parentName);
     members[memberName.ToString()] = member;
     CodeTypeDeclaration decl = member as CodeTypeDeclaration;
     if (decl != null)
     {
         foreach (CodeTypeMember subMember in decl.Members)
         {
             EnumerareCodeMembers(subMember, memberName, members);
         }
     }
 }
        public void CreateShouldLogCatchedExceptionAsError()
        {
            using (MockDomain domain = new MockDomain())
              {
            MockAssemblyRepository repository = new MockAssemblyRepository();
            QualifiedName fakeName = new QualifiedName(
              typeof(string).FullName.Replace("mscorlib", "NonExistingAssemblyName"),
              typeof(string).Assembly.FullName.Replace("mscorlib", "NonExistingAssemblyName"));

            IPluginCreator tested = PluginCreator.GetCreator(domain);
            MockLog mocklog = new MockLog((ILogWriter)tested);
            PluginDescriptor descriptor = MockPluginDescriptor.For(fakeName);
            Exception ex = DoAssert.Throws<PluginException>(() => tested.Create(descriptor, repository, null));
            Assert.IsTrue(mocklog.Any(x => x.Level == MockLog.Level.Error && x.Message.Contains(ex.Message)));
              }
        }
        /// <summary>
        /// Constructs a new instance.
        /// </summary>
        public DataChangeMonitoredItem(
            MonitoredNode source,
            uint id,
            uint attributeId,
            NumericRange indexRange,
            QualifiedName dataEncoding,
            DiagnosticsMasks diagnosticsMasks,
            TimestampsToReturn timestampsToReturn,
            MonitoringMode monitoringMode,
            uint clientHandle,
            double samplingInterval,
            uint queueSize,
            bool discardOldest,
            DataChangeFilter filter,
            Range range,
            bool alwaysReportUpdates)
        {
            m_source = source;
            m_id = id;
            m_attributeId = attributeId;
            m_indexRange = indexRange;
            m_dataEncoding = dataEncoding;
            m_timestampsToReturn = timestampsToReturn;
            m_diagnosticsMasks = diagnosticsMasks;
            m_monitoringMode = monitoringMode;
            m_clientHandle = clientHandle;
            m_samplingInterval = samplingInterval;
            m_nextSampleTime = DateTime.UtcNow.Ticks;
            m_readyToPublish = false;
            m_readyToTrigger = false;
            m_queue = null;
            m_filter = filter;
            m_range = 0;
            m_alwaysReportUpdates = alwaysReportUpdates;
        
            if (range != null)
            {
                m_range = range.High  - range.Low;
            }

            if (queueSize > 1)
            {
                m_queue = new MonitoredItemQueue();
                m_queue.SetQueueSize(queueSize, discardOldest, diagnosticsMasks);
                m_queue.SetSamplingInterval(samplingInterval);
            }
        }
        public PropertyDefinition FindProperty(PropertyTreeDefinition definition,
                                               Type componentType,
                                               QualifiedName qn,
                                               IEnumerable<PropertyTreeDefinition> ancestors)
        {
            // Allow any namespace contained in the definition base classes
            var result = definition
                .EnumerateProperties()
                .FirstOrDefault(t => Compare(t, qn, definition));

            if (result != null)
                return result;

            int dot = qn.LocalName.IndexOf('.');
            if (dot > 0) {
                // TODO Index whether the PTD has extenders so we can skip some ancestors (perf)
                string prefix = qn.LocalName.Substring(0, dot);

                foreach (var currentDef in ancestors) {
                    if (currentDef.Name == prefix) {
                        // TODO Local name could be different
                        var prop = currentDef.GetProperty(qn);
                        if (prop != null) {
                            return prop;
                        }
                    }
                }

            } else {

                foreach (var curDefinition in ancestors) {
                    var prop = curDefinition.GetProperty(qn);
                    if (IsValidExtender(prop, componentType))
                        return prop;

                    var qn2 = qn.ChangeLocalName(curDefinition.Name + "." + qn.LocalName);
                    prop = curDefinition.GetProperty(qn2);
                    if (IsValidExtender(prop, componentType))
                        return prop;

                }
            }

            return null;
        }
        public void DefineProvider(QualifiedName name,
                                   Type providerType,
                                   Type providerInstanceType,
                                   object metadata = null)
        {
            if (providerType == null)
                throw new ArgumentNullException("providerType");
            if (providerInstanceType == null)
                throw new ArgumentNullException("providerInstanceType");
            if (providerInstanceType.IsAbstract || !providerType.IsAssignableFrom(providerInstanceType))
                throw RuntimeFailure.InvalidProviderInstanceType("providerInstanceType");

            var qn = GetName(name, providerInstanceType, providerInstanceType.Name);

            var tr = new ProviderType(providerInstanceType, providerType, qn);
            tr.Metadata = ProviderMetadataWrapper.Create(metadata);
            tr.Metadata.Source = tr;
            result.Add(tr);
        }
        public void DefineProvider(QualifiedName name,
                                   Type providerType,
                                   FieldInfo field,
                                   object metadata = null)
        {
            if (providerType == null)
                throw new ArgumentNullException("providerType");
            if (field == null)
                throw new ArgumentNullException("field");
            if (!field.IsStatic
                || !providerType.IsAssignableFrom(field.FieldType)) {
                throw RuntimeFailure.InvalidProviderFieldOrMethod("field");
            }

            var qn = GetName(name, field.DeclaringType, field.Name);

            var fieldResult = new ProviderField(field, providerType, qn);
            fieldResult.Metadata = ProviderMetadataWrapper.Create(metadata);
            fieldResult.Metadata.Source = fieldResult;
            result.Add(fieldResult);
        }
Example #20
0
        /// <summary>
        /// Begins a transition.
        /// </summary>
        protected virtual Transition BeginTransitionToState(OperationContext context, QualifiedName toState)
        {
            if (m_currentState == null || m_currentStateName == null)
            {
                GotoInitialState();
            }

            foreach (Transition transition in m_transitions)
            {
                if (transition.FromState == m_currentStateName && transition.ToState.BrowseName == toState)
                {        
                    return transition;
                }
            }

            throw ServiceResultException.Create(
                StatusCodes.BadMethodInvalid,
                "Cannot move to {0} State while in the {1} State.",
                toState.Name,
                CurrentStateName);
        }
 private void AddErrorAlreadyParameter([NotNull] Node node, [NotNull] QualifiedName name)
 {
     DiagnosticUtils.AddError(node, name.Head + " is already a parameter.");
 }
Example #22
0
        public ServiceResult Property_NodeValueEventHandler(ISystemContext context, NodeState node, NumericRange indexRange, QualifiedName dataEncoding, ref object value, ref StatusCode statusCode, ref DateTime timestamp)
        {
            ServiceResult result = new ServiceResult(statusCode);

            //var manager = new TargetsManager();
            //manager.SetTargetValue(node.NodeId.Identifier.ToString(), value);

            return(result);
        }
Example #23
0
        /// <summary>
        /// Monitoring for an event source starts if it is required.
        /// </summary>
        public async Task MonitorEventsAsync(CancellationToken ct)
        {
            bool sessionLocked = false;

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

                    // if the session is not connected or shutdown in progress, return
                    if (!sessionLocked || ct.IsCancellationRequested || State != SessionState.Connected)
                    {
                        return;
                    }
                }
                catch (Exception)
                {
                    throw;
                }

                // ensure all nodes in all subscriptions of this session are monitored.
                foreach (var opcEventSubscription in OpcEventSubscriptions)
                {
                    // create the subscription, if it is not yet there.
                    if (opcEventSubscription.OpcUaClientSubscription == null)
                    {
                        opcEventSubscription.OpcUaClientSubscription = CreateSubscription(opcEventSubscription.RequestedPublishingInterval, out int revisedPublishingInterval);
                        opcEventSubscription.PublishingInterval      = revisedPublishingInterval;
                        Logger.Information($"Create Event subscription on endpoint '{EndpointUrl}' requested OPC publishing interval is {opcEventSubscription.RequestedPublishingInterval} ms. (revised: {revisedPublishingInterval} ms)");
                    }

                    // process all unmonitored events.
                    var  unmonitoredEvents = opcEventSubscription.OpcMonitoredItems.Where(i => (i.State == OpcMonitoredItemState.Unmonitored || i.State == OpcMonitoredItemState.UnmonitoredNamespaceUpdateRequested));
                    int  additionalMonitoredEventsCount = 0;
                    int  monitoredEventsCount           = 0;
                    bool haveUnmonitoredEvents          = false;
                    if (unmonitoredEvents.Count() != 0)
                    {
                        haveUnmonitoredEvents = true;
                        monitoredEventsCount  = opcEventSubscription.OpcMonitoredItems.Count(i => (i.State == OpcMonitoredItemState.Monitored));
                        Logger.Information($"Start monitoring events on endpoint '{EndpointUrl}'. Currently monitoring {monitoredEventsCount} events.");
                    }

                    // init perf data
                    Stopwatch stopWatch = new Stopwatch();
                    stopWatch.Start();
                    foreach (var unmonitoredEvent in unmonitoredEvents)
                    {
                        // if the session is not connected or a shutdown is in progress, we stop trying and wait for the next cycle
                        if (ct.IsCancellationRequested || State != SessionState.Connected)
                        {
                            break;
                        }

                        NodeId currentNodeId = null;
                        try
                        {
                            // update the namespace of the node if requested. there are two cases where this is requested:
                            // 1) publishing requests via the OPC server method are raised using a NodeId format. for those
                            //    the NodeId format is converted into an ExpandedNodeId format
                            // 2) ExpandedNodeId configuration file entries do not have at parsing time a session to get
                            //    the namespace index. this is set now.
                            if (unmonitoredEvent.State == OpcMonitoredItemState.UnmonitoredNamespaceUpdateRequested)
                            {
                                if (unmonitoredEvent.ConfigType == OpcMonitoredItemConfigurationType.ExpandedNodeId)
                                {
                                    ExpandedNodeId expandedNodeId = ExpandedNodeId.Parse(unmonitoredEvent.Id);
                                    int            namespaceIndex = _namespaceTable.GetIndex(expandedNodeId.NamespaceUri);
                                    if (namespaceIndex < 0)
                                    {
                                        Logger.Information($"The namespace URI of node '{expandedNodeId.ToString()}' can be not mapped to a namespace index.");
                                    }
                                    else
                                    {
                                        unmonitoredEvent.IdAsExpandedNodeId = expandedNodeId;
                                    }
                                }
                                if (unmonitoredEvent.ConfigType == OpcMonitoredItemConfigurationType.NodeId)
                                {
                                    NodeId nodeId       = NodeId.Parse(unmonitoredEvent.Id);
                                    string namespaceUri = _namespaceTable.ToArray().ElementAtOrDefault(nodeId.NamespaceIndex);
                                    if (string.IsNullOrEmpty(namespaceUri))
                                    {
                                        Logger.Information($"The namespace index of node '{nodeId.ToString()}' is invalid and the node format can not be updated.");
                                    }
                                    else
                                    {
                                        unmonitoredEvent.IdAsExpandedNodeId = new ExpandedNodeId(nodeId.Identifier, nodeId.NamespaceIndex, namespaceUri, 0);
                                        unmonitoredEvent.ConfigType         = OpcMonitoredItemConfigurationType.ExpandedNodeId;
                                    }
                                }
                                unmonitoredEvent.State = OpcMonitoredItemState.Unmonitored;
                            }

                            // lookup namespace index if ExpandedNodeId format has been used and build NodeId identifier.
                            if (unmonitoredEvent.ConfigType == OpcMonitoredItemConfigurationType.ExpandedNodeId)
                            {
                                ExpandedNodeId expandedNodeId = ExpandedNodeId.Parse(unmonitoredEvent.Id);
                                int            namespaceIndex = _namespaceTable.GetIndex(expandedNodeId.NamespaceUri);
                                if (namespaceIndex < 0)
                                {
                                    Logger.Warning($"Syntax or namespace URI of ExpandedNodeId '{expandedNodeId.ToString()}' is invalid and will be ignored.");
                                    continue;
                                }
                                unmonitoredEvent.IdAsNodeId = new NodeId(expandedNodeId.Identifier, expandedNodeId.NamespaceIndex);
                                currentNodeId = unmonitoredEvent.IdAsNodeId;
                            }
                            else
                            {
                                NodeId nodeId       = NodeId.Parse(unmonitoredEvent.Id);
                                string namespaceUri = _namespaceTable.ToArray().ElementAtOrDefault(nodeId.NamespaceIndex);
                                if (string.IsNullOrEmpty(namespaceUri))
                                {
                                    Logger.Information($"The namespace index of node '{nodeId.ToString()}' is invalid and the node format can not be updated.");
                                }
                                else
                                {
                                    unmonitoredEvent.IdAsExpandedNodeId = new ExpandedNodeId(nodeId.Identifier, nodeId.NamespaceIndex, namespaceUri, 0);
                                    currentNodeId = nodeId;
                                }
                            }

                            // if configured, get the key for the node, otherwise use the nodeId
                            Node node;
                            if (string.IsNullOrEmpty(unmonitoredEvent.Key))
                            {
                                if (FetchOpcNodeDisplayName == true)
                                {
                                    node = OpcUaClientSession.ReadNode(currentNodeId);
                                    unmonitoredEvent.Key = node.DisplayName.Text ?? currentNodeId.ToString();
                                }
                                else
                                {
                                    unmonitoredEvent.Key = currentNodeId.ToString();
                                }
                            }

                            // resolve all node and namespace references in the select and where clauses
                            EventFilter eventFilter = new EventFilter();
                            foreach (var selectClause in unmonitoredEvent.EventConfiguration.SelectClauses)
                            {
                                SimpleAttributeOperand simpleAttributeOperand = new SimpleAttributeOperand();
                                simpleAttributeOperand.AttributeId = selectClause.AttributeId.ResolveAttributeId();
                                simpleAttributeOperand.IndexRange  = selectClause.IndexRange;
                                NodeId typeId = selectClause.TypeId.ToNodeId(_namespaceTable);
                                simpleAttributeOperand.TypeDefinitionId = new NodeId(typeId);
                                QualifiedNameCollection browsePaths = new QualifiedNameCollection();
                                foreach (var browsePath in selectClause.BrowsePaths)
                                {
                                    browsePaths.Add(QualifiedName.Parse(browsePath));
                                }
                                simpleAttributeOperand.BrowsePath = browsePaths;
                                eventFilter.SelectClauses.Add(simpleAttributeOperand);
                            }
                            foreach (var whereClauseElement in unmonitoredEvent.EventConfiguration.WhereClause)
                            {
                                ContentFilterElement contentFilterElement = new ContentFilterElement();
                                contentFilterElement.FilterOperator = whereClauseElement.Operator.ResolveFilterOperator();
                                switch (contentFilterElement.FilterOperator)
                                {
                                case FilterOperator.OfType:
                                case FilterOperator.InView:
                                    if (whereClauseElement.Operands.Count != 1)
                                    {
                                        Logger.Error($"The where clause element '{whereClauseElement.ToString()}' must contain 1 operands.");
                                        continue;
                                    }
                                    FilterOperand[] filterOperands = new FilterOperand[1];
                                    TypeInfo        typeInfo       = new TypeInfo(BuiltInType.NodeId, ValueRanks.Scalar);
                                    filterOperands[0] = whereClauseElement.Operands[0].GetOperand(typeInfo);
                                    eventFilter.WhereClause.Push(contentFilterElement.FilterOperator, filterOperands);
                                    break;

                                case FilterOperator.Equals:
                                case FilterOperator.IsNull:
                                case FilterOperator.GreaterThan:
                                case FilterOperator.LessThan:
                                case FilterOperator.GreaterThanOrEqual:
                                case FilterOperator.LessThanOrEqual:
                                case FilterOperator.Like:
                                case FilterOperator.Not:
                                case FilterOperator.Between:
                                case FilterOperator.InList:
                                case FilterOperator.And:
                                case FilterOperator.Or:
                                case FilterOperator.Cast:
                                case FilterOperator.BitwiseAnd:
                                case FilterOperator.BitwiseOr:
                                case FilterOperator.RelatedTo:
                                default:
                                    Logger.Error($"The operator '{contentFilterElement.FilterOperator.ToString()}' is not supported.");
                                    break;
                                }
                            }

                            // add the new monitored event.
                            IOpcUaMonitoredItem monitoredItem = new OpcUaMonitoredItem()
                            {
                                StartNodeId      = currentNodeId,
                                AttributeId      = Attributes.EventNotifier,
                                DisplayName      = unmonitoredEvent.Key,
                                MonitoringMode   = unmonitoredEvent.MonitoringMode,
                                SamplingInterval = 0,
                                QueueSize        = unmonitoredEvent.QueueSize,
                                DiscardOldest    = unmonitoredEvent.DiscardOldest,
                                Filter           = eventFilter
                            };

                            monitoredItem.Notification += unmonitoredEvent.NotificationEventHandler;
                            opcEventSubscription.OpcUaClientSubscription.AddItem(monitoredItem);
                            unmonitoredEvent.OpcUaClientMonitoredItem = monitoredItem;
                            unmonitoredEvent.State       = OpcMonitoredItemState.Monitored;
                            unmonitoredEvent.EndpointUrl = EndpointUrl;
                            Logger.Verbose($"Created monitored event for node '{currentNodeId.ToString()}' in subscription with id '{opcEventSubscription.OpcUaClientSubscription.Id}' on endpoint '{EndpointUrl}' (version: {NodeConfigVersion:X8})");
                            if (unmonitoredEvent.RequestedSamplingInterval != monitoredItem.SamplingInterval)
                            {
                                Logger.Information($"Sampling interval: requested: {unmonitoredEvent.RequestedSamplingInterval}; revised: {monitoredItem.SamplingInterval}");
                                unmonitoredEvent.SamplingInterval = monitoredItem.SamplingInterval;
                            }
                            if (additionalMonitoredEventsCount % 10000 == 0)
                            {
                                Logger.Information($"Now monitoring {monitoredEventsCount + additionalMonitoredEventsCount} events in subscription with id '{opcEventSubscription.OpcUaClientSubscription.Id}'");
                            }
                        }
                        catch (Exception e) when(e.GetType() == typeof(ServiceResultException))
                        {
                            ServiceResultException sre = (ServiceResultException)e;

                            switch ((uint)sre.Result.StatusCode)
                            {
                            case StatusCodes.BadSessionIdInvalid:
                            {
                                Logger.Information($"Session with Id {OpcUaClientSession.SessionId} is no longer available on endpoint '{EndpointUrl}'. Cleaning up.");
                                // clean up the session
                                InternalDisconnect();
                                break;
                            }

                            case StatusCodes.BadNodeIdInvalid:
                            case StatusCodes.BadNodeIdUnknown:
                            {
                                Logger.Error($"Failed to monitor node '{currentNodeId}' on endpoint '{EndpointUrl}'.");
                                Logger.Error($"OPC UA ServiceResultException is '{sre.Result}'. Please check your publisher configuration for this node.");
                                break;
                            }

                            default:
                            {
                                Logger.Error($"Unhandled OPC UA ServiceResultException '{sre.Result}' when monitoring node '{currentNodeId}' on endpoint '{EndpointUrl}'. Continue.");
                                break;
                            }
                            }
                        }
                        catch (Exception e)
                        {
                            Logger.Error(e, $"Failed to monitor node '{currentNodeId}' on endpoint '{EndpointUrl}'");
                        }
                    }
                    opcEventSubscription.OpcUaClientSubscription.SetPublishingMode(true);
                    opcEventSubscription.OpcUaClientSubscription.ApplyChanges();
                    stopWatch.Stop();
                    if (haveUnmonitoredEvents == true)
                    {
                        monitoredEventsCount = opcEventSubscription.OpcMonitoredItems.Count(i => (i.State == OpcMonitoredItemState.Monitored));
                        Logger.Information($"Done processing unmonitored events on endpoint '{EndpointUrl}' took {stopWatch.ElapsedMilliseconds} msec. Now monitoring {monitoredEventsCount} events in subscription with id '{opcEventSubscription.OpcUaClientSubscription.Id}'.");
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Error(e, "Exception");
            }
            finally
            {
                if (sessionLocked)
                {
                    ReleaseSession();
                }
            }
        }
Example #24
0
 /// <summary>
 /// Creates an audit event for the cause.
 /// </summary>
 protected virtual AuditUpdateStateEvent CreateAuditEvent(
     OperationContext context, 
     Transition       transition, 
     QualifiedName    cause, 
     Exception        exception)
 {
     return AuditUpdateStateEvent.Construct(Server);
 }
Example #25
0
        /// <summary>
        /// Reports an effect which is an effect of a transition.
        /// </summary>
        protected virtual void ReportEffect(
            OperationContext context, 
            Transition       transition, 
            QualifiedName    cause,
            NodeId           effectId)
        {
            if (effectId == ObjectTypes.TransitionEventType)
            {
                TransitionEvent e = TransitionEvent.Construct(Server);

                e.InitializeNewEvent();
                
                e.Message.Value       = Utils.Format("StateMachine has moved to the {0} state.", transition.ToState.DisplayName);
                e.SourceNode.Value    = NodeId;
                e.SourceName.Value    = BrowseName.Name;
                e.Severity.Value      = 10;
                e.ReceiveTime.Value   = DateTime.UtcNow;
                e.FromState.Value     = transition.FromState.DisplayName;
                e.ToState.Value       = transition.ToState.DisplayName;

                ReportEvent(e);
            }
        }
Example #26
0
        /// <summary>
        /// Does any processing after a transition occurs.
        /// </summary>
        protected virtual void OnAfterTransition(OperationContext context, Transition transition, QualifiedName cause)
        {
            // raise a notification that a transition has occurred.
            if (m_TransitionCompleted != null)
            {
                StateMachineTransitionEventArgs args = new StateMachineTransitionEventArgs(
                    transition.FromState.BrowseName, 
                    transition.ToState.BrowseName, 
                    cause);

                m_TransitionCompleted(context, this, args);
            }
        }
        /// <summary>
        /// Creates a new set of monitored items for a set of variables.
        /// </summary>
        /// <remarks>
        /// This method only handles data change subscriptions. Event subscriptions are created by the SDK.
        /// </remarks>
        protected override ServiceResult CreateMonitoredItem(
            ISystemContext context,
            NodeState source,
            uint subscriptionId,
            double publishingInterval,
            DiagnosticsMasks diagnosticsMasks,
            TimestampsToReturn timestampsToReturn,
            MonitoredItemCreateRequest itemToCreate,
            ref long globalIdCounter,
            out MonitoringFilterResult filterError,
            out IMonitoredItem monitoredItem)
        {
            filterError   = null;
            monitoredItem = null;

            MemoryTagState tag = source as MemoryTagState;

            // use default behavoir for non-tag sources.
            if (tag == null)
            {
                return(base.CreateMonitoredItem(
                           context,
                           source,
                           subscriptionId,
                           publishingInterval,
                           diagnosticsMasks,
                           timestampsToReturn,
                           itemToCreate,
                           ref globalIdCounter,
                           out filterError,
                           out monitoredItem));
            }

            // validate parameters.
            MonitoringParameters parameters = itemToCreate.RequestedParameters;

            // no filters supported at this time.
            MonitoringFilter filter = (MonitoringFilter)ExtensionObject.ToEncodeable(parameters.Filter);

            if (filter != null)
            {
                return(StatusCodes.BadFilterNotAllowed);
            }

            // index range not supported.
            if (itemToCreate.ItemToMonitor.ParsedIndexRange != NumericRange.Empty)
            {
                return(StatusCodes.BadIndexRangeInvalid);
            }

            // data encoding not supported.
            if (!QualifiedName.IsNull(itemToCreate.ItemToMonitor.DataEncoding))
            {
                return(StatusCodes.BadDataEncodingInvalid);
            }

            // read initial value.
            DataValue initialValue = new DataValue();

            initialValue.Value           = null;
            initialValue.ServerTimestamp = DateTime.UtcNow;
            initialValue.SourceTimestamp = DateTime.MinValue;
            initialValue.StatusCode      = StatusCodes.Good;

            ServiceResult error = source.ReadAttribute(
                context,
                itemToCreate.ItemToMonitor.AttributeId,
                itemToCreate.ItemToMonitor.ParsedIndexRange,
                itemToCreate.ItemToMonitor.DataEncoding,
                initialValue);

            if (ServiceResult.IsBad(error))
            {
                return(error);
            }

            // get the monitored node for the containing buffer.
            MemoryBufferState buffer = tag.Parent as MemoryBufferState;

            if (buffer == null)
            {
                return(StatusCodes.BadInternalError);
            }

            // create a globally unique identifier.
            uint monitoredItemId = Utils.IncrementIdentifier(ref globalIdCounter);

            // determine the sampling interval.
            double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval;

            if (samplingInterval < 0)
            {
                samplingInterval = publishingInterval;
            }

            // create the item.
            MemoryBufferMonitoredItem datachangeItem = buffer.CreateDataChangeItem(
                context as ServerSystemContext,
                tag,
                subscriptionId,
                monitoredItemId,
                itemToCreate.ItemToMonitor,
                diagnosticsMasks,
                timestampsToReturn,
                itemToCreate.MonitoringMode,
                itemToCreate.RequestedParameters.ClientHandle,
                samplingInterval);

            /*
             * // create the item.
             * MemoryBufferMonitoredItem datachangeItem = buffer.CreateDataChangeItem(
             *  context,
             *  tag,
             *  monitoredItemId,
             *  itemToCreate.ItemToMonitor.AttributeId,
             *  diagnosticsMasks,
             *  timestampsToReturn,
             *  itemToCreate.MonitoringMode,
             *  itemToCreate.RequestedParameters.ClientHandle,
             *  samplingInterval);
             */

            // report the initial value.
            datachangeItem.QueueValue(initialValue, null);

            // update monitored item list.
            monitoredItem = datachangeItem;

            return(ServiceResult.Good);
        }
        public void ProductAutogenuuidAttributeType()
        {
            QualifiedName attributeName = schema.GetAttributeType("Product", "Id");

            Assert.AreEqual("AutogenGuid", attributeName.Name);
        }
Example #29
0
        /// <summary>
        /// Returns the next child.
        /// </summary>
        private IReference NextChild()
        {
            UnderlyingSystem system = (UnderlyingSystem)this.SystemContext.SystemHandle;

            NodeId targetId = null;

            // check if a specific browse name is requested.
            if (!QualifiedName.IsNull(base.BrowseName))
            {
                // browse name must be qualified by the correct namespace.
                if (m_parent.BrowseName.NamespaceIndex != base.BrowseName.NamespaceIndex)
                {
                    return(null);
                }

                // parse the browse name.
                int index = 0;

                for (int ii = 0; ii < base.BrowseName.Name.Length; ii++)
                {
                    char ch = base.BrowseName.Name[ii];

                    if (!Char.IsDigit(ch))
                    {
                        return(null);
                    }

                    index *= 10;
                    index += Convert.ToInt32(ch - '0');
                }

                // check for valid browse name.
                if (index < 0 || index > m_parent.Register.Size)
                {
                    return(null);
                }

                // return target.
                targetId = ModelUtils.GetRegisterVariableId(m_parent.Register, index, m_parent.NodeId.NamespaceIndex);
            }

            // return the child at the next position.
            else
            {
                // look for next segment.
                if (m_position >= m_parent.Register.Size)
                {
                    return(null);
                }

                // return target.
                targetId = ModelUtils.GetRegisterVariableId(m_parent.Register, m_position, m_parent.NodeId.NamespaceIndex);
                m_position++;
            }

            // create reference.
            if (targetId != null)
            {
                return(new NodeStateReference(ReferenceTypeIds.Organizes, false, targetId));
            }

            return(null);
        }
 public bool IsAssignableFrom(QualifiedName qname, INamedTypeSymbol from)
 {
     throw new NotImplementedException();
 }
	public FunctionDeclarationHeader(QualifiedName Name, AccessModifier Visibility)
		: base(CodeElementType.FunctionDeclarationHeader) {
		this.Name = Name;
		this.Visibility = Visibility;
		this.Profile = new ParametersProfile();
	}
Example #32
0
        /// <summary>
        /// Finds the child with the specified browse name.
        /// </summary>
        protected override BaseInstanceState FindChild(
            ISystemContext context,
            QualifiedName browseName,
            bool createOrReplace,
            BaseInstanceState replacement)
        {
            if (QualifiedName.IsNull(browseName))
            {
                return(null);
            }

            BaseInstanceState instance = null;

            switch (browseName.Name)
            {
            case AggregationModel.BrowseNames.EndpointUrl:
            {
                if (createOrReplace)
                {
                    if (EndpointUrl == null)
                    {
                        if (replacement == null)
                        {
                            EndpointUrl = new PropertyState <string>(this);
                        }
                        else
                        {
                            EndpointUrl = (PropertyState <string>)replacement;
                        }
                    }
                }

                instance = EndpointUrl;
                break;
            }

            case AggregationModel.BrowseNames.Status:
            {
                if (createOrReplace)
                {
                    if (Status == null)
                    {
                        if (replacement == null)
                        {
                            Status = new PropertyState <StatusCode>(this);
                        }
                        else
                        {
                            Status = (PropertyState <StatusCode>)replacement;
                        }
                    }
                }

                instance = Status;
                break;
            }

            case AggregationModel.BrowseNames.ConnectTime:
            {
                if (createOrReplace)
                {
                    if (ConnectTime == null)
                    {
                        if (replacement == null)
                        {
                            ConnectTime = new PropertyState <DateTime>(this);
                        }
                        else
                        {
                            ConnectTime = (PropertyState <DateTime>)replacement;
                        }
                    }
                }

                instance = ConnectTime;
                break;
            }
            }

            if (instance != null)
            {
                return(instance);
            }

            return(base.FindChild(context, browseName, createOrReplace, replacement));
        }
Example #33
0
        /// <summary>
        /// Begins a transition.
        /// </summary>
        protected virtual Transition BeginTransitionForCause(OperationContext context, QualifiedName causeName)
        {
            foreach (Transition transition in m_transitions)
            {
                if (transition.FromState == m_currentStateName)
                {        
                    foreach (MethodSource cause in transition.Causes)
                    {
                        if (cause.BrowseName == causeName)
                        {
                            return transition;
                        }
                    }
                }
            }

            throw ServiceResultException.Create(
                StatusCodes.BadMethodInvalid,
                "Method {0} cannot be used while in the {1} State.",
                causeName.Name,
                m_currentStateName.DisplayName);
        }
 public PropertyState(NodeState parent, QualifiedName browseName) : base(parent, browseName)
 {
 }
Example #35
0
        /// <summary>
        /// Does any processing before a transition occurs.
        /// </summary>
        protected virtual void OnBeforeTransition(OperationContext context, Transition transition, QualifiedName cause)
        {
            // raise a notification that a transition is about to occur.
            if (m_TransitionInitiated != null)
            {
                StateMachineTransitionEventArgs args = new StateMachineTransitionEventArgs(transition.FromState.BrowseName, transition.ToState.BrowseName, cause);
                
                m_TransitionInitiated(context, this, args);

                if (args.Cancel)
                {
                    throw ServiceResultException.Create(StatusCodes.Bad, "Transition to State '{0}' was cancelled because: '{1}'.", transition.ToState.DisplayName, args.CancelReason);
                }
            }
        }
Example #36
0
 /// <summary>
 /// Creates an empty assembly with a particular name.
 /// </summary>
 /// <param name="fullName">The assembly's name.</param>
 public DescribedAssembly(QualifiedName fullName)
     : base(fullName)
 {
     this.definedTypes = new List <IType>();
 }
Example #37
0
        /// <summary>
        /// Ends a transition (reports events for all effects).
        /// </summary>
        protected virtual void EndTransition(OperationContext context, Transition transition, QualifiedName cause)
        {
            if (transition != null)
            {
                foreach (NodeId effectId in transition.Effects)
                {
                    // check if the effects are being surpressed.
                    if (m_suppressEffects)
                    {
                        m_unreportedEffect = true;
                        return;
                    }

                    ReportEffect(context, transition, cause, effectId);
                }
            }
        }
Example #38
0
        /// <summary>
        /// Handles a write operation for an individual tag.
        /// </summary>
        public ServiceResult WriteTagValue(
            ISystemContext context,
            NodeState node,
            NumericRange indexRange,
            QualifiedName dataEncoding,
            ref object value,
            ref StatusCode statusCode,
            ref DateTime timestamp)
        {
            MemoryTagState tag = node as MemoryTagState;

            if (tag == null)
            {
                return(StatusCodes.BadNodeIdUnknown);
            }

            if (NumericRange.Empty != indexRange)
            {
                return(StatusCodes.BadIndexRangeInvalid);
            }

            if (!QualifiedName.IsNull(dataEncoding))
            {
                return(StatusCodes.BadDataEncodingInvalid);
            }

            if (statusCode != StatusCodes.Good)
            {
                return(StatusCodes.BadWriteNotSupported);
            }

            if (timestamp != DateTime.MinValue)
            {
                return(StatusCodes.BadWriteNotSupported);
            }

            bool changed = false;
            int  offset  = (int)tag.Offset;

            lock (m_dataLock)
            {
                if (offset < 0 || offset >= m_buffer.Length)
                {
                    return(StatusCodes.BadNodeIdUnknown);
                }

                if (m_buffer == null)
                {
                    return(StatusCodes.BadOutOfService);
                }

                byte[] bytes = null;

                switch (m_elementType)
                {
                case BuiltInType.UInt32:
                {
                    uint?valueToWrite = value as uint?;

                    if (valueToWrite == null)
                    {
                        return(StatusCodes.BadTypeMismatch);
                    }

                    bytes = BitConverter.GetBytes(valueToWrite.Value);
                    break;
                }

                case BuiltInType.Double:
                {
                    double?valueToWrite = value as double?;

                    if (valueToWrite == null)
                    {
                        return(StatusCodes.BadTypeMismatch);
                    }

                    bytes = BitConverter.GetBytes(valueToWrite.Value);
                    break;
                }

                default:
                {
                    return(StatusCodes.BadNodeIdUnknown);
                }
                }

                for (int ii = 0; ii < bytes.Length; ii++)
                {
                    if (!changed)
                    {
                        if (m_buffer[offset + ii] != bytes[ii])
                        {
                            changed = true;
                        }
                    }

                    m_buffer[offset + ii] = bytes[ii];
                }
            }

            if (changed)
            {
                OnBufferChanged(offset);
            }

            return(ServiceResult.Good);
        }
Example #39
0
        /// <summary>
        /// Reports an audit event for the cause.
        /// </summary>
        protected virtual void ReportAuditEvent(OperationContext context, Transition transition, QualifiedName cause, Exception exception)
        {
            AuditUpdateStateEvent e = CreateAuditEvent(context, transition, cause, exception);
                        
            e.InitializeNewEvent();
            
            e.Message.Value            = Utils.Format("Method {0} was called.", cause);
            e.SourceNode.Value         = NodeId;
            e.SourceName.Value         = "Method/Call";
            e.Severity.Value           = 1;
            e.ReceiveTime.Value        = DateTime.UtcNow;
            e.ActionTimeStamp.Value    = DateTime.UtcNow;
            e.OldStateId.Value         = m_currentStateName.StateNumber;
            e.NewStateId.Value         = m_currentStateName.StateNumber;  

            if (context != null)
            {
                e.ClientAuditEntryId.Value = context.AuditEntryId;
                e.ClientUserId.Value       = context.Session.Identity.DisplayName;
            }

            if (transition != null)
            {
                e.OldStateId.Value = transition.FromState.StateNumber;
                e.NewStateId.Value = transition.ToState.StateNumber;
            }

            ReportEvent(e);
        }
Example #40
0
        /// <summary>
        /// Returns the next child.
        /// </summary>
        private IReference NextChild()
        {
            MemoryTagState tag = null;

            // check if a specific browse name is requested.
            if (!QualifiedName.IsNull(BrowseName))
            {
                // check if match found previously.
                if (_position == uint.MaxValue)
                {
                    return(null);
                }

                // browse name must be qualified by the correct namespace.
                if (_buffer.TypeDefinitionId.NamespaceIndex != BrowseName.NamespaceIndex)
                {
                    return(null);
                }

                var name = BrowseName.Name;

                for (var ii = 0; ii < name.Length; ii++)
                {
                    if ("0123456789ABCDEF".IndexOf(name[ii]) == -1)
                    {
                        return(null);
                    }
                }

                _position = Convert.ToUInt32(name, 16);

                // check for memory overflow.
                if (_position >= _buffer.SizeInBytes.Value)
                {
                    return(null);
                }

                tag       = new MemoryTagState(_buffer, _position);
                _position = uint.MaxValue;
            }

            // return the child at the next position.
            else
            {
                if (_position >= _buffer.SizeInBytes.Value)
                {
                    return(null);
                }

                tag        = new MemoryTagState(_buffer, _position);
                _position += _buffer.ElementSize;

                // check for memory overflow.
                if (_position >= _buffer.SizeInBytes.Value)
                {
                    return(null);
                }
            }

            return(new NodeStateReference(ReferenceTypeIds.HasComponent, false, tag));
        }
Example #41
0
 /// <summary>
 /// Creates a new instance.
 /// </summary>
 internal StateMachineTransitionEventArgs(QualifiedName fromState, QualifiedName toState, QualifiedName cause)
 {
     m_fromState = fromState;
     m_toState = toState;
     m_cause = cause;
 }
Example #42
0
 public GlobalConstUse(Position position, QualifiedName name, QualifiedName?fallbackName)
     : base(position)
 {
     this.name         = name;
     this.fallbackName = fallbackName;
 }
Example #43
0
        /// <summary>
        /// Provides a mechanism to assemble a fully qualified Area name in a hierarchical space.
        /// </summary>
        /// <param name="szAreaName">The name of an Area at the current level, obtained from the string enumerator returned by BrowseOPCAreas with a BrowseFilterType of OPC_AREA</param>
        /// <param name="pszQualifiedAreaName">Where to return the resulting fully qualified area name.</param>
        public void GetQualifiedAreaName(string szAreaName, out string pszQualifiedAreaName)
        {
            pszQualifiedAreaName = String.Empty;

            try
            {
                pszQualifiedAreaName = szAreaName;
                // Make sure the stack is not null
                INode parent = m_browseStack.Peek();
                if (parent == null)
                {
                    throw ComUtils.CreateComException(ResultIds.E_FAIL);
                }

                // And make sure this is avalid Area name at the level
                INode child = FindChildByName(parent.NodeId, szAreaName);
                if (child == null)
                {
                    throw ComUtils.CreateComException(ResultIds.E_INVALIDARG);
                }
                pszQualifiedAreaName = "";
                INode[] stack = m_browseStack.ToArray();
                for (int i = stack.Length - 2; i >= 0; i--)
                {
                    // Translate the server namespace index in browsename to the corresponding client namespace index
                    QualifiedName QName = stack[i].BrowseName;
                    QualifiedName translatedName = new QualifiedName(QName.Name, (ushort)m_server.ServerMappingTable[QName.NamespaceIndex]);
                    if (pszQualifiedAreaName.Length != 0)
                        pszQualifiedAreaName = pszQualifiedAreaName + "/" + translatedName.ToString();
                    else
                        pszQualifiedAreaName = translatedName.ToString();
                }
                //Also translate the areaname
                QualifiedName QualifiedAreaName =  QualifiedName.Parse(szAreaName);
                QualifiedName TranslatedAreaName = new QualifiedName(QualifiedAreaName.Name, (ushort)m_server.ServerMappingTable[QualifiedAreaName.NamespaceIndex]);
                pszQualifiedAreaName = pszQualifiedAreaName + "/" + TranslatedAreaName.ToString();

            }
            catch (COMException e)
            {
                throw ComUtils.CreateComException(e);
            }
            catch (Exception e)
            {
                Utils.Trace(e, "Unexpected error in GetQualifiedAreaName");
                throw ComUtils.CreateComException(e);
            }
        }
Example #44
0
        private void FireToken(TokenType tokenType, QualifiedName name, StringSegment value = default(StringSegment))
        {
            var token = new HtmlToken(tokenType, content, name, value);

            tokens[tokenCount++] = token;
        }