public EventHandler(GameEventType t, EventAction e) { //todo(seba) don't think these are interned the way you'd hope filter = @v => v.type == t; action = e; timing = EventTiming.Main; }
/// <summary> /// Initializes a new instance of the <see cref="FolderWatcher"/> class. /// </summary> /// <param name="folder">The folder.</param> /// <param name="filter">The filter.</param> public FolderWatcher(string folder, string filter) { this.Folder = folder; this.Filter = filter; this.extensions = new List<IFolderWatcherExtension>(); this.eventFilter = new EventFilter<FileSystemEventArgs>(FilterTimeWindow); this.eventFilter.FilteredEventRaised += this.HandleEventFilterFilteredEventRaised; }
/// <summary> /// Displays the dialog. /// </summary> public EventFilter ShowDialog(Session session, EventFilter filter, bool editWhereClause) { if (session == null) throw new ArgumentNullException("session"); if (filter == null) throw new ArgumentNullException("filter"); m_session = session; m_filter = filter; BrowseCTRL.SetView(m_session, BrowseViewType.EventTypes, null); SelectClauseCTRL.Initialize(session, filter.SelectClauses); ContentFilterCTRL.Initialize(session, filter.WhereClause); FilterOperandsCTRL.Initialize(session, null, -1); MoveBTN_Click((editWhereClause)?NextBTN:BackBTN, null); if (ShowDialog() != DialogResult.OK) { return null; } return m_filter; }
public void FilterMixedEvents() { int count = 0; EventFilter<EventArgs> filter = new EventFilter<EventArgs>(100); AutoResetEvent finished = new AutoResetEvent(false); filter.FilteredEventRaised += delegate { count++; finished.Set(); }; filter.HandleOriginalEvent(this, EventArgs.Empty); filter.HandleOriginalEvent(this, EventArgs.Empty); finished.WaitOne(200, false); filter.HandleOriginalEvent(this, EventArgs.Empty); finished.WaitOne(200, false); Assert.AreEqual(2, count, "There should be 2 filtered events"); }
public void Remoting_must_not_leak_actors() { var actorRef = Sys.ActorOf(EchoActor.Props(this, true), "echo"); var echoPath = new RootActorPath(RARP.For(Sys).Provider.DefaultAddress) / "user" / "echo"; var targets = new[] { "/system/endpointManager", "/system/transports" }.Select(x => { Sys.ActorSelection(x).Tell(new Identify(0)); return(ExpectMsg <ActorIdentity>().Subject); }).ToList(); var initialActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet(); // Clean shutdown case for (var i = 1; i <= 3; i++) { var remoteSystem = ActorSystem.Create("remote", ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0") .WithFallback(Sys.Settings.Config)); try { var probe = CreateTestProbe(remoteSystem); remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref); probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); } finally { remoteSystem.Terminate(); } remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); } // Quarantine an old incarnation case for (var i = 1; i <= 3; i++) { // always use the same address var remoteSystem = ActorSystem.Create("remote", ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 2553") .WithFallback(Sys.Settings.Config)); try { var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress; remoteSystem.ActorOf(Props.Create(() => new StoppableActor()), "stoppable"); // the message from remote to local will cause inbound connection established var probe = CreateTestProbe(remoteSystem); remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref); probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); var beforeQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet(); // it must not quarantine the current connection RARP.For(Sys) .Provider.Transport.Quarantine(remoteAddress, AddressUidExtension.Uid(remoteSystem) + 1); // the message from local to remote should reuse passive inbound connection Sys.ActorSelection(new RootActorPath(remoteAddress) / "user" / "stoppable").Tell(new Identify(1)); ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); var afterQuarantineActors = targets.SelectMany(CollectLiveActors).ToImmutableHashSet(); AssertActors(beforeQuarantineActors, afterQuarantineActors); } finally { remoteSystem.Terminate(); } remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); } // Missing SHUTDOWN case for (var i = 1; i <= 3; i++) { var remoteSystem = ActorSystem.Create("remote", ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0") .WithFallback(Sys.Settings.Config)); var remoteAddress = RARP.For(remoteSystem).Provider.DefaultAddress; try { var probe = CreateTestProbe(remoteSystem); remoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref); probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); // This will make sure that no SHUTDOWN message gets through RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(remoteAddress)) .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue(); } finally { remoteSystem.Terminate(); } EventFilter.Warning(contains: "Association with remote system").ExpectOne(() => { remoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); }); } // Remote idle for too long case var idleRemoteSystem = ActorSystem.Create("remote", ConfigurationFactory.ParseString("akka.remote.dot-netty.tcp.port = 0") .WithFallback(Sys.Settings.Config)); var idleRemoteAddress = RARP.For(idleRemoteSystem).Provider.DefaultAddress; idleRemoteSystem.ActorOf(Props.Create <StoppableActor>(), "stoppable"); try { var probe = CreateTestProbe(idleRemoteSystem); idleRemoteSystem.ActorSelection(echoPath).Tell(new Identify(1), probe.Ref); probe.ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); // Watch a remote actor - this results in system message traffic Sys.ActorSelection(new RootActorPath(idleRemoteAddress) / "user" / "stoppable").Tell(new Identify(1)); var remoteActor = ExpectMsg <ActorIdentity>().Subject; Watch(remoteActor); remoteActor.Tell("stop"); ExpectTerminated(remoteActor); // All system messages have been acked now on this side // This will make sure that no SHUTDOWN message gets through RARP.For(Sys).Provider.Transport.ManagementCommand(new ForceDisassociate(idleRemoteAddress)) .Wait(TimeSpan.FromSeconds(3)).ShouldBeTrue(); } finally { idleRemoteSystem.Terminate(); } EventFilter.Warning(contains: "Association with remote system").ExpectOne(() => { idleRemoteSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)).ShouldBeTrue(); }); /* * Wait for the ReliableDeliverySupervisor to receive its "TooLongIdle" message, * which will throw a HopelessAssociation wrapped around a TimeoutException. */ EventFilter.Exception <TimeoutException>().ExpectOne(() => { }); AwaitAssert(() => { AssertActors(initialActors, targets.SelectMany(CollectLiveActors).ToImmutableHashSet()); }, 10.Seconds()); }
public ActionResult CalendarView(string type, EventFilter filter) { ViewData["UserSalesList"] = usersServices.GetAllSales(CurrenUser, false); var currentFilter = (EventFilter)Session[CALENDAR_SEARCH_MODEL]; if (filter.Month == 0) { filter = currentFilter; } var dateOfMonth = new DateTime(filter.Year, filter.Month, 1); if (!filter.Sales.HasValue) { filter.Sales = 0; } switch (type) { case "prev": dateOfMonth = dateOfMonth.AddMonths(-1); break; case "current": dateOfMonth = DateTime.Now; break; case "next": dateOfMonth = dateOfMonth.AddMonths(1); break; } filter.Month = dateOfMonth.Month; filter.Year = dateOfMonth.Year; var qrEvents = eventService.GetQuery(x => (x.DateBegin.Month == filter.Month && x.DateBegin.Year == filter.Year) && (filter.Sales == 0 || (filter.Sales == x.CreatedById || (x.CRMCustomer.CreatedById == filter.Sales) || (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == filter.Sales)))) && (filter.Status == CRMEventStatus.All || x.Status == (byte)filter.Status) && (string.IsNullOrEmpty(filter.CustomerName) || x.CRMCustomer.CompanyShortName.Contains(filter.CustomerName) || x.CRMCustomer.CompanyName.Contains(filter.CustomerName)) ); if (filter.OfEvent.HasValue) { qrEvents = filter.OfEvent == TypeOfEvent.Events ? qrEvents.Where(x => x.IsEventAction == true) : qrEvents.Where(x => x.IsEventAction == false); } if (!CurrenUser.IsDirecter() && filter.Sales == 0) { if (CurrenUser.IsDepManager()) { qrEvents = qrEvents.Where(x => x.User.DeptId == CurrenUser.DeptId || (x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) || (x.CRMCustomer.CreatedById == CurrenUser.Id) || (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id))); } else { qrEvents = qrEvents.Where(x => x.CreatedById == CurrenUser.Id || (x.CRMCustomer.CRMFollowCusUsers != null && x.CRMCustomer.CRMFollowCusUsers.Any(f => f.UserId == CurrenUser.Id)) || (x.CRMCustomer.CreatedById == CurrenUser.Id) || (x.CRMFollowEventUsers != null && x.CRMFollowEventUsers.Any(ef => ef.UserId == CurrenUser.Id))); } } var list = qrEvents.ToList(); Session[CALENDAR_SEARCH_MODEL] = filter; ViewBag.filter = filter; return(PartialView("_CalendarModelView", list)); }
public static extern void SetEventFilter(EventFilter filter, void *userdata);
public Error SetEventInternal(JvmtiEnvironment environment, JniEnvironment nativeEnvironment, EventKind eventKind, EventFilter filter) { EventRequestModifier locationModifier = default(EventRequestModifier); EventRequestModifier stepModifier = default(EventRequestModifier); switch (eventKind) { case EventKind.Breakpoint: // we're going to need the location modifier to set the breakpoint if (filter.Modifiers.Count == 0 || filter.Modifiers[0].Kind != ModifierKind.LocationFilter) return Error.IllegalArgument; locationModifier = filter.Modifiers[0]; break; case EventKind.SingleStep: // the first modifier contains the step properties if (filter.Modifiers.Count == 0 || filter.Modifiers[0].Kind != ModifierKind.Step) return Error.IllegalArgument; stepModifier = filter.Modifiers[0]; break; case EventKind.FramePop: if (filter.InternalEventKind == EventKind.SingleStep) goto case EventKind.SingleStep; break; default: break; } lock (_eventRequests) { Dictionary<RequestId, EventFilter> requests; if (!_eventRequests.TryGetValue(eventKind, out requests)) { requests = new Dictionary<RequestId, EventFilter>(); _eventRequests.Add(eventKind, requests); } requests.Add(filter.RequestId, filter); if (requests.Count == 1) { JvmEventType? eventToEnable = GetJvmEventType(eventKind); if (eventToEnable != null) { jvmtiError error = Environment.SetEventNotificationMode(JvmEventMode.Enable, eventToEnable.Value); if (error != jvmtiError.None) return GetStandardError(error); } } } switch (eventKind) { case EventKind.Breakpoint: { Contract.Assert(locationModifier.Kind == ModifierKind.LocationFilter); jmethodID methodId = locationModifier.Location.Method; jlocation location = new jlocation((long)locationModifier.Location.Index); jvmtiError error = Environment.SetBreakpoint(methodId, location); if (error != jvmtiError.None) return GetStandardError(error); break; } case EventKind.FramePop: if (filter.InternalEventKind == EventKind.SingleStep) { using (var thread = VirtualMachine.GetLocalReferenceForThread(nativeEnvironment, stepModifier.Thread)) { if (!thread.IsAlive) return Error.InvalidThread; jvmtiError error = environment.RawInterface.NotifyFramePop(environment, thread.Value, 0); if (error != jvmtiError.None) return GetStandardError(error); } } break; default: break; } return Error.None; }
/// <summary> /// Modifies a monitored item. /// </summary> public void ModifyMonitoredItem( OperationContext context, IEventMonitoredItem monitoredItem, TimestampsToReturn timestampsToReturn, MonitoredItemModifyRequest itemToModify, EventFilter filter) { lock (m_lock) { // should never be called with items that it does not own. if (!m_monitoredItems.ContainsKey(monitoredItem.Id)) { return; } // limit the queue size. uint queueSize = itemToModify.RequestedParameters.QueueSize; if (queueSize > m_maxEventQueueSize) { queueSize = m_maxEventQueueSize; } // modify the attributes. monitoredItem.ModifyAttributes( context.DiagnosticsMask, timestampsToReturn, itemToModify.RequestedParameters.ClientHandle, filter, filter, null, itemToModify.RequestedParameters.SamplingInterval, queueSize, itemToModify.RequestedParameters.DiscardOldest); } }
/// <summary> /// Constructs the event filter for the subscription. /// </summary> /// <returns>The event filter.</returns> public EventFilter ConstructFilter(Session session) { EventFilter filter = new EventFilter(); // the select clauses specify the values returned with each event notification. filter.SelectClauses = SelectClauses; // the where clause restricts the events returned by the server. // it works a lot like the WHERE clause in a SQL statement and supports // arbitrary expession trees where the operands are literals or event fields. ContentFilter whereClause = new ContentFilter(); // the code below constructs a filter that looks like this: // (Severity >= X OR LastSeverity >= X) AND (SuppressedOrShelved == False) AND (OfType(A) OR OfType(B)) // add the severity. ContentFilterElement element1 = null; ContentFilterElement element2 = null; if (Severity > EventSeverity.Min) { // select the Severity property of the event. SimpleAttributeOperand operand1 = new SimpleAttributeOperand(); operand1.TypeDefinitionId = ObjectTypeIds.BaseEventType; operand1.BrowsePath.Add(BrowseNames.Severity); operand1.AttributeId = Attributes.Value; // specify the value to compare the Severity property with. LiteralOperand operand2 = new LiteralOperand(); operand2.Value = new Variant((ushort)Severity); // specify that the Severity property must be GreaterThanOrEqual the value specified. element1 = whereClause.Push(FilterOperator.GreaterThanOrEqual, operand1, operand2); } // add the suppressed or shelved. if (!IgnoreSuppressedOrShelved) { // select the SuppressedOrShelved property of the event. SimpleAttributeOperand operand1 = new SimpleAttributeOperand(); operand1.TypeDefinitionId = ObjectTypeIds.BaseEventType; operand1.BrowsePath.Add(BrowseNames.SuppressedOrShelved); operand1.AttributeId = Attributes.Value; // specify the value to compare the Severity property with. LiteralOperand operand2 = new LiteralOperand(); operand2.Value = new Variant(false); // specify that the Severity property must Equal the value specified. element2 = whereClause.Push(FilterOperator.Equals, operand1, operand2); // chain multiple elements together with an AND clause. if (element1 != null) { element1 = whereClause.Push(FilterOperator.And, element1, element2); } else { element1 = element2; } } // add the event types. if (EventTypes != null && EventTypes.Count > 0) { element2 = null; // save the last element. for (int ii = 0; ii < EventTypes.Count; ii++) { // for this example uses the 'OfType' operator to limit events to thoses with specified event type. LiteralOperand operand1 = new LiteralOperand(); operand1.Value = new Variant(EventTypes[ii]); ContentFilterElement element3 = whereClause.Push(FilterOperator.OfType, operand1); // need to chain multiple types together with an OR clause. if (element2 != null) { element2 = whereClause.Push(FilterOperator.Or, element2, element3); } else { element2 = element3; } } // need to link the set of event types with the previous filters. if (element1 != null) { whereClause.Push(FilterOperator.And, element1, element2); } } filter.WhereClause = whereClause; // return filter. return(filter); }
private void MuteSystem(ActorSystem system) { system.EventStream.Publish(EventFilter.Error(start: "AssociationError").Mute()); system.EventStream.Publish(EventFilter.Warning(start: "AssociationError").Mute()); system.EventStream.Publish(EventFilter.Warning(contains: "dead letter").Mute()); }
protected string FindEvents(SearchScope scope, EventFilter searchFilter, DateTime startPoint, DateTime?endPoint, bool includeStartState, int?maxMatches, string keepAliveTime) { return(FindEvents(scope, searchFilter, startPoint, endPoint, includeStartState, maxMatches, keepAliveTime, "Find Events")); }
public async Task <IActionResult> Index(int page = 1, string search = null, int?system = null, int?branch = null, int?location = null, int?program = null, string StartDate = null, string EndDate = null, bool CommunityExperiences = false) { ModelState.Clear(); EventFilter filter = new EventFilter(page) { Search = search, EventType = CommunityExperiences ? 1 : 0 }; // ignore location if branch has value if (branch.HasValue) { filter.BranchIds = new List <int>() { branch.Value }; } else if (system.HasValue) { filter.SystemIds = new List <int>() { system.Value }; } else if (location.HasValue) { filter.LocationIds = new List <int?>() { location.Value }; } if (program.HasValue) { filter.ProgramIds = new List <int?>() { program.Value }; } if (!String.Equals(StartDate, "False", StringComparison.OrdinalIgnoreCase)) { if (!string.IsNullOrWhiteSpace(StartDate)) { DateTime startDate; if (DateTime.TryParse(StartDate, out startDate)) { filter.StartDate = startDate.Date; } } else { filter.StartDate = _dateTimeProvider.Now.Date; } } if (!string.IsNullOrWhiteSpace(EndDate)) { DateTime endDate; if (DateTime.TryParse(EndDate, out endDate)) { filter.EndDate = endDate.Date; } } var eventList = await _eventService.GetPaginatedListAsync(filter); PaginateViewModel paginateModel = new PaginateViewModel() { ItemCount = eventList.Count, CurrentPage = page, ItemsPerPage = filter.Take.Value }; if (paginateModel.MaxPage > 0 && paginateModel.CurrentPage > paginateModel.MaxPage) { return(RedirectToRoute( new { page = paginateModel.LastPage ?? 1 })); } EventsListViewModel viewModel = new EventsListViewModel() { Events = eventList.Data, PaginateModel = paginateModel, Search = search, StartDate = filter.StartDate, EndDate = filter.EndDate, ProgramId = program, SystemList = new SelectList((await _siteService.GetSystemList()), "Id", "Name"), LocationList = new SelectList((await _eventService.GetLocations()), "Id", "Name"), ProgramList = new SelectList((await _siteService.GetProgramList()), "Id", "Name"), CommunityExperiences = CommunityExperiences }; if (branch.HasValue) { var selectedBranch = await _siteService.GetBranchByIdAsync(branch.Value); viewModel.SystemId = selectedBranch.SystemId; viewModel.BranchList = new SelectList( (await _siteService.GetBranches(selectedBranch.SystemId)), "Id", "Name", branch.Value); } else if (system.HasValue) { viewModel.SystemId = system; viewModel.BranchList = new SelectList( (await _siteService.GetBranches(system.Value)), "Id", "Name"); } else { viewModel.BranchList = new SelectList((await _siteService.GetAllBranches()), "Id", "Name"); } if (location.HasValue && !branch.HasValue) { viewModel.LocationId = location.Value; viewModel.UseLocation = true; } return(View("Index", viewModel)); }
/// <summary> /// Получить отфильтрованные события /// </summary> public List <Event> GetFilteredEvents(EventFilter filter) { bool reversed; return(GetFilteredEvents(filter, 0, 0, out reversed)); }
public void CanInterceptMessagesWhenContainsIsSpecified() { EventFilter.ForLogLevel(LogLevel, contains: "ate").ExpectOne(() => LogMessage("whatever")); TestSuccessful = true; }
void CommonForwardBackwardSearchEventsTest(Func <RecordingInformation, SearchRange> defineRange, bool includeStartStateInSearch, bool validateEdges) { string searchToken = string.Empty; SearchState state = SearchState.Completed; RunTest( () => { string keepAlive = string.Format("PT{0}S", _searchKeepAlive); RecordingInformation recording = FindRecordingForTest(); SearchRange range = defineRange(recording); DateTime start = range.Start; DateTime end = range.End; List <FindEventResult> results = new List <FindEventResult>(); Dictionary <FindEventResult, XmlElement> elements1 = new Dictionary <FindEventResult, XmlElement>(); Dictionary <FindEventResult, XmlElement> elements2 = new Dictionary <FindEventResult, XmlElement>(); Dictionary <FindEventResult, XmlElement> elements = elements1; EventFilter filter = new EventFilter(); SearchScope scope = new SearchScope(); scope.IncludedRecordings = new string[] { recording.RecordingToken }; Action <DateTime, DateTime> validateAction = new Action <DateTime, DateTime>( (startTime, endTime) => { state = SearchState.Completed; searchToken = FindEvents(scope, filter, startTime, endTime, includeStartStateInSearch, null, keepAlive); Dictionary <FindEventResult, XmlDocument> rawResults = new Dictionary <FindEventResult, XmlDocument>(); results = GetAllEventsSearchResults(searchToken, null, null, "PT5S", elements, out state); Assert(results != null && results.Count > 0, "No events found", "Check that events list is not empty"); ValidateMessages(results); //GetMessageElements(results, rawResults, elements); ValidateRecordingEvents(recording, results, elements, validateEdges, (startTime < endTime)); ValidateOrder(results, startTime, endTime); }); validateAction(start, end); List <FindEventResult> results1 = new List <FindEventResult>(); results1.AddRange(results); elements = elements2; validateAction(end, start); List <FindEventResult> results2 = new List <FindEventResult>(); results2.AddRange(results); // compare lists CompareLists(results1, results2, elements1, elements2, "list received for StartPoint < EndPoint", "list received for StartPoint > EndPoint"); }, () => { if (state != SearchState.Completed) { ReleaseSearch(searchToken, _searchTimeout); } }); }
public MonitoredItem CreateMonitoredItem( OperationContext context, INodeManager nodeManager, object handle, uint subscriptionId, uint monitoredItemId, TimestampsToReturn timestampsToReturn, MonitoredItemCreateRequest itemToCreate, EventFilter filter) { return CreateMonitoredItem( context, nodeManager, handle, subscriptionId, monitoredItemId, timestampsToReturn, 0, itemToCreate, filter); }
public void A_restarted_quarantined_system_should_not_crash_the_other_system() { Sys.ActorOf <RemoteRestartedQuarantinedMultiNetSpec.Subject>("subject"); EnterBarrier("subject-started"); RunOn(() => { var secondAddress = Node(_config.Second).Address; var uid = _identifyWithUid(_config.Second, "subject").Item1; RARP.For(Sys).Provider.Transport.Quarantine(Node(_config.Second).Address, uid); EnterBarrier("quarantined"); EnterBarrier("still-quarantined"); TestConductor.Shutdown(_config.Second).Wait(); Within(TimeSpan.FromSeconds(30), () => { AwaitAssert(() => { Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject") .Tell(new Identify("subject")); ExpectMsg <ActorIdentity>(i => i.Subject != null, TimeSpan.FromSeconds(1)); }); }); Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject").Tell("shutdown"); }, _config.First); RunOn(() => { var addr = ((ExtendedActorSystem)Sys).Provider.DefaultAddress; var firstAddress = Node(_config.First).Address; Sys.EventStream.Subscribe(TestActor, typeof(ThisActorSystemQuarantinedEvent)); var actorRef = _identifyWithUid(_config.First, "subject").Item2; EnterBarrier("quarantined"); // Check that quarantine is intact Within(TimeSpan.FromSeconds(10), () => { AwaitAssert(() => { EventFilter.Warning(null, null, "The remote system has quarantined this system") .ExpectOne(() => actorRef.Tell("boo!")); }); }); ExpectMsg <ThisActorSystemQuarantinedEvent>(TimeSpan.FromSeconds(10)); EnterBarrier("still-quarantined"); Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(10)); var sb = new StringBuilder() .AppendLine("akka.remote.retry-gate-closed-for = 0.5 s") .AppendLine("akka.remote.dot-netty.tcp {") .AppendLine("hostname = " + addr.Host) .AppendLine("port = " + addr.Port) .AppendLine("}"); var freshSystem = ActorSystem.Create(Sys.Name, ConfigurationFactory.ParseString(sb.ToString()).WithFallback(Sys.Settings.Config)); var probe = CreateTestProbe(freshSystem); freshSystem.ActorSelection(new RootActorPath(firstAddress) / "user" / "subject") .Tell(new Identify("subject"), probe.Ref); // TODO sometimes it takes long time until the new connection is established, // It seems like there must first be a transport failure detector timeout, that triggers // "No response from remote. Handshake timed out or transport failure detector triggered" probe.ExpectMsg <ActorIdentity>(i => i.Subject != null, TimeSpan.FromSeconds(30)); freshSystem.ActorOf <RemoteRestartedQuarantinedMultiNetSpec.Subject>("subject"); freshSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(10)); }, _config.Second); }
/// <summary> /// Creates a new MonitoredItem for events. Applies the standard event filters for condition events /// and adds the filters necessary to obtain event attributes -- properties of event types/subtypes /// </summary> /// <param name="nodeId">The node id.</param> /// <returns></returns> public MonitoredItem CreateMonitoredItemForEvents(NodeId nodeId) { MonitoredItem monitoredItem = new MonitoredItem(m_Subscription.DefaultItem); monitoredItem.AttributeId = Attributes.EventNotifier; monitoredItem.DisplayName = m_Subscription.Session.NodeCache.GetDisplayText((ExpandedNodeId)nodeId); monitoredItem.StartNodeId = nodeId; monitoredItem.NodeClass = NodeClass.Object; //get all attribute values from all events EventFilter filter = new EventFilter(); foreach (EventAttribute attr in m_configFile.Attributes) { if (attr.strEventNodeId != "") { filter.AddSelectClause(new NodeId(attr.strEventNodeId), attr.BrowseName); // Utils.Trace("AddSelectClause ( {0}: {1}, {2} )", i++, attr.strEventNodeId, attr.BrowseName); } } // Add Condition-related attributes to the filter so that we have enough info to determine // Enabled/Disabled, Active/Inactive including time of active transition, Acked/Unacked and active subcondition filter.AddSelectClause(Opc.Ua.ObjectTypes.ConditionType, "/EnabledState/Id", Attributes.Value); filter.AddSelectClause(Opc.Ua.ObjectTypes.ConditionType, "/Quality", Attributes.Value); filter.AddSelectClause(Opc.Ua.ObjectTypes.AcknowledgeableConditionType, "/AckedState/Id", Attributes.Value); filter.AddSelectClause(Opc.Ua.ObjectTypes.AcknowledgeableConditionType, "", Attributes.NodeId); filter.AddSelectClause(Opc.Ua.ObjectTypes.AlarmConditionType, "/ActiveState/Id", Attributes.Value); filter.AddSelectClause(Opc.Ua.ObjectTypes.AlarmConditionType, "/ActiveState/TransitionTime", Attributes.Value); filter.AddSelectClause(Opc.Ua.ObjectTypes.AlarmConditionType, "/ActiveState/EffectiveDisplayName", Attributes.Value); monitoredItem.Filter = filter; monitoredItem.Notification += new MonitoredItemNotificationEventHandler(MonitoredItem_Notification); return monitoredItem; }
public void GivenNewProcess_WhenStartProcessCommand_ShouldLogFinnishCreatingProcess() { EventFilter.Info($"Created process with Id: {processId}.") .ExpectOne(() => manager.Tell(new StartProcessCommand(processId))); }
private void SendSingleStepEvent(JvmtiEnvironment environment, EventFilter filter, ThreadId threadId, Location location) { if (!VirtualMachine.IsAgentThread.Value) { // ignore events before VMInit if (AgentEventDispatcher == null) return; // dispatch this call to an agent thread Action<JvmtiEnvironment, EventFilter, ThreadId, Location> invokeMethod = SendSingleStepEvent; AgentEventDispatcher.Invoke(invokeMethod, environment, filter, threadId, location); return; } JniEnvironment nativeEnvironment; JniErrorHandler.ThrowOnFailure(VirtualMachine.AttachCurrentThreadAsDaemon(environment, out nativeEnvironment, false)); ApplySuspendPolicy(environment, nativeEnvironment, filter.SuspendPolicy, threadId); Callback.SingleStep(filter.SuspendPolicy, filter.RequestId, threadId, location); }
public void MemorySnapshotStore_is_threadsafe() { EventFilter.Error().Expect(0, () => { // get a few persistent actors going in parallel var sa1 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa1", TestActor))); var sa2 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa2", TestActor))); var sa3 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa3", TestActor))); Watch(sa1); Watch(sa2); Watch(sa3); var writeCount = 3000; var sas = new List <IActorRef> { sa1, sa2, sa3 }; // hammer with write requests Parallel.ForEach(Enumerable.Range(0, writeCount), i => { sas[ThreadLocalRandom.Current.Next(0, 3)].Tell(i); }); // spawn more persistence actors while writes are still going(?) var sa4 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa4", TestActor))); var sa5 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa5", TestActor))); var sa6 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa6", TestActor))); ReceiveN(writeCount).All(x => x is SaveSnapshotSuccess).Should().BeTrue("Expected all snapshot store saves to be successful, but some were not"); // kill the existing snapshot stores, then re-create them to force recovery while the new snapshot actors // are still being written to. sa1.Tell(PoisonPill.Instance); ExpectTerminated(sa1); sa2.Tell(PoisonPill.Instance); ExpectTerminated(sa2); sa3.Tell(PoisonPill.Instance); ExpectTerminated(sa3); var sas2 = new List <IActorRef> { sa4, sa5, sa6 }; // hammer with write requests Parallel.ForEach(Enumerable.Range(0, writeCount), i => { sas2[ThreadLocalRandom.Current.Next(0, 3)].Tell(i); }); // recreate the previous entities var sa12 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa1", TestActor))); var sa22 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa2", TestActor))); var sa32 = Sys.ActorOf(Props.Create(() => new SnapshotActor("sa3", TestActor))); var sas12 = new List <IActorRef> { sa12, sa22, sa32 }; // hammer other entities Parallel.ForEach(Enumerable.Range(0, writeCount), i => { sas12[ThreadLocalRandom.Current.Next(0, 3)].Tell(i); }); ReceiveN(writeCount * 2).All(x => x is SaveSnapshotSuccess).Should().BeTrue("Expected all snapshot store saves to be successful, but some were not"); }); }
private void RemoveFilter(EventFilter filter) { _filters.Remove(filter); }
/// <summary> /// Shows all fields for the current condition. /// </summary> public bool ShowDialog(MonitoredItem monitoredItem, EventFieldList eventFields) { // build a sorted list of non-null fields. List <string> fieldNames = new List <string>(); List <Variant> fieldValues = new List <Variant>(); // use the filter from the monitored item to determine what is in each field. EventFilter filter = monitoredItem.Status.Filter as EventFilter; if (filter != null) { if (eventFields.EventFields[0].Value != null) { fieldNames.Add("ConditionId"); fieldValues.Add(eventFields.EventFields[0]); } for (int ii = 1; ii < filter.SelectClauses.Count; ii++) { object fieldValue = eventFields.EventFields[ii].Value; if (fieldValue == null) { continue; } StringBuilder displayName = new StringBuilder(); for (int jj = 0; jj < filter.SelectClauses[ii].BrowsePath.Count; jj++) { if (displayName.Length > 0) { displayName.Append('/'); } displayName.Append(filter.SelectClauses[ii].BrowsePath[jj].Name); } fieldNames.Add(displayName.ToString()); fieldValues.Add(eventFields.EventFields[ii]); } } // populate lists. for (int ii = 0; ii < fieldNames.Count; ii++) { ListViewItem item = new ListViewItem(fieldNames[ii]); item.SubItems.Add(Utils.Format("{0}", fieldValues[ii].Value)); item.SubItems.Add(Utils.Format("{0}", fieldValues[ii].Value.GetType().Name)); FieldsLV.Items.Add(item); } // adjust columns. for (int ii = 0; ii < FieldsLV.Columns.Count; ii++) { FieldsLV.Columns[ii].Width = -2; } // display the dialog. if (ShowDialog() != DialogResult.OK) { return(false); } return(true); }
public static extern void FilterEvents(EventFilter filter, void *userdata);
/// <summary> /// 投遞事件 /// </summary> /// <param name="filter"></param> /// <param name="type"></param> /// <param name="args"></param> internal void PostEvent(EventFilter filter, EventType type, params object[] args) { PostEvent(new Event(filter, type, args)); }
public void BackoffSupervisor_must_support_manual_reset() { Action <IActorRef> assertManualReset = supervisor => { supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance); var c1 = ExpectMsg <BackoffSupervisor.CurrentChild>().Ref; Watch(c1); c1.Tell("boom"); ExpectTerminated(c1); AwaitAssert(() => { supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance); ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(1); }); AwaitAssert(() => { supervisor.Tell(BackoffSupervisor.GetCurrentChild.Instance); // new instance ExpectMsg <BackoffSupervisor.CurrentChild>().Ref.Should().NotBeSameAs(c1); }); // TODO: this Thread.Sleep should be removed Thread.Sleep(500); supervisor.Tell("hello"); ExpectMsg("hello"); // making sure the Reset is handled by supervisor supervisor.Tell("hello"); ExpectMsg("hello"); supervisor.Tell(BackoffSupervisor.GetRestartCount.Instance); ExpectMsg <BackoffSupervisor.RestartCount>().Count.Should().Be(0); }; // TODO: use FilterException EventFilter.Exception <TestException>().Expect(2, () => { var stoppingStrategy = new OneForOneStrategy(ex => { if (ex is TestException) { return(Directive.Stop); } // TODO: should restart be there? return(Directive.Restart); }); var restartingStrategy = new OneForOneStrategy(ex => { if (ex is TestException) { return(Directive.Restart); } // TODO: should restart be there? return(Directive.Restart); }); assertManualReset( Create(OnStopOptions(ManualChild.Props(TestActor)) .WithManualReset() .WithSupervisorStrategy(stoppingStrategy))); assertManualReset( Create(OnFailureOptions(ManualChild.Props(TestActor)) .WithManualReset() .WithSupervisorStrategy(restartingStrategy))); }); }
/// <summary> /// Constructs an event object from a notification. /// </summary> /// <param name="session">The session.</param> /// <param name="monitoredItem">The monitored item that produced the notification.</param> /// <param name="notification">The notification.</param> /// <param name="eventTypeMappings">Mapping between event types and known event types.</param> /// <returns> /// The event object. Null if the notification is not a valid event type. /// </returns> public static BaseEventState ConstructEvent( Session session, MonitoredItem monitoredItem, EventFieldList notification, Dictionary <NodeId, NodeId> eventTypeMappings) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); if (eventTypeId == null) { return(null); } // look up the known event type. NodeId knownTypeId = null; if (!eventTypeMappings.TryGetValue(eventTypeId, out knownTypeId)) { // check for a known type for (int jj = 0; jj < KnownEventTypes.Length; jj++) { if (KnownEventTypes[jj] == eventTypeId) { knownTypeId = eventTypeId; eventTypeMappings.Add(eventTypeId, eventTypeId); break; } } // browse for the supertypes of the event type. if (knownTypeId == null) { ReferenceDescriptionCollection supertypes = FormUtils.BrowseSuperTypes(session, eventTypeId, false); // can't do anything with unknown types. if (supertypes == null) { return(null); } // find the first supertype that matches a known event type. for (int ii = 0; ii < supertypes.Count; ii++) { for (int jj = 0; jj < KnownEventTypes.Length; jj++) { if (KnownEventTypes[jj] == supertypes[ii].NodeId) { knownTypeId = KnownEventTypes[jj]; eventTypeMappings.Add(eventTypeId, knownTypeId); break; } } if (knownTypeId != null) { break; } } } } if (knownTypeId == null) { return(null); } // all of the known event types have a UInt32 as identifier. uint?id = knownTypeId.Identifier as uint?; if (id == null) { return(null); } // construct the event based on the known event type. BaseEventState e = null; switch (id.Value) { case ObjectTypes.ConditionType: { e = new ConditionState(null); break; } case ObjectTypes.DialogConditionType: { e = new DialogConditionState(null); break; } case ObjectTypes.AlarmConditionType: { e = new AlarmConditionState(null); break; } case ObjectTypes.ExclusiveLimitAlarmType: { e = new ExclusiveLimitAlarmState(null); break; } case ObjectTypes.NonExclusiveLimitAlarmType: { e = new NonExclusiveLimitAlarmState(null); break; } case ObjectTypes.AuditEventType: { e = new AuditEventState(null); break; } case ObjectTypes.AuditUpdateMethodEventType: { e = new AuditUpdateMethodEventState(null); break; } default: { e = new BaseEventState(null); break; } } // get the filter which defines the contents of the notification. EventFilter filter = monitoredItem.Status.Filter as EventFilter; // initialize the event with the values in the notification. e.Update(session.SystemContext, filter.SelectClauses, notification); // save the orginal notification. e.Handle = notification; return(e); }
public void RemoteNodeRestart_must_allow_restarted_node_to_pass_through_gate() { Sys.ActorOf(Props.Create(() => new Subject()), "subject"); EnterBarrier("subject-started"); RunOn(() => { var secondAddress = Node(_specConfig.Second).Address; Identify(_specConfig.Second, "subject"); EventFilter.Warning(new Regex("address is now gated")).ExpectOne(() => { RARP.For(Sys).Provider.Transport.ManagementCommand( new ForceDisassociateExplicitly(Node(_specConfig.Second).Address, DisassociateInfo.Unknown)) .Wait(TimeSpan.FromSeconds(3)); }); EnterBarrier("gated"); TestConductor.Shutdown(_specConfig.Second).Wait(); Within(TimeSpan.FromSeconds(10), () => { AwaitAssert( () => { Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject") .Tell(new Identify("subject")); ExpectMsg <ActorIdentity>().Subject.ShouldNotBe(null); }); }); Sys.ActorSelection(new RootActorPath(secondAddress) / "user" / "subject").Tell("shutdown"); }, _specConfig.First); RunOn(() => { var addr = Sys.AsInstanceOf <ExtendedActorSystem>().Provider.DefaultAddress; var firstAddress = Node(_specConfig.First).Address; EnterBarrier("gated"); Sys.WhenTerminated.Wait(TimeSpan.FromSeconds(10)); var sb = new StringBuilder(); sb.AppendLine("akka.remote.retry-gate-closed-for = 0.5s") .AppendLine(" akka.remote.dot-netty.tcp {") .AppendLine("hostname = " + addr.Host) .AppendLine("port =" + addr.Port) .AppendLine("}"); var freshSystem = ActorSystem.Create(Sys.Name, ConfigurationFactory.ParseString(sb.ToString()) .WithFallback(Sys.Settings.Config)); var probe = CreateTestProbe(freshSystem); // Pierce the gate Within(TimeSpan.FromSeconds(30), () => { AwaitAssert(() => { freshSystem.ActorSelection(new RootActorPath(firstAddress) / "user" / "subject") .Tell(new Identify("subject"), probe); probe.ExpectMsg <ActorIdentity>(); }); }); // Now the other system will be able to pass, too freshSystem.ActorOf(Props.Create(() => new Subject()), "subject"); freshSystem.WhenTerminated.Wait(TimeSpan.FromSeconds(30)); }, _specConfig.Second); }
private IQueryable <Model.Event> ApplyFilters(EventFilter filter) { // site id filter var events = DbSet .AsNoTracking() .Where(_ => _.SiteId == filter.SiteId); // active-only filter if (filter.IsActive.HasValue) { events = events.Where(_ => _.IsActive == filter.IsActive); } if (filter.EventType.HasValue) { switch (filter.EventType.Value) { case 0: events = events.Where(_ => _.IsCommunityExperience == false); break; case 1: events = events.Where(_ => _.IsCommunityExperience == true); break; default: break; } } // apply filter // collect branch ids var branchIds = new HashSet <int?>(); if (filter.BranchIds != null) { foreach (var branchId in filter.BranchIds) { if (!branchIds.Contains(branchId)) { branchIds.Add(branchId); } } } if (filter.SystemIds != null) { var branchIdsFromSystem = _context.Branches .AsNoTracking() .Where(_ => filter.SystemIds.Contains(_.SystemId)) .Select(_ => _.Id); foreach (var branchId in branchIdsFromSystem) { if (!branchIds.Contains(branchId)) { branchIds.Add(branchId); } } } // filter by branch ids if (branchIds.Count > 0) { events = events.Where(_ => branchIds.Contains(_.AtBranchId)); } // filter by location ids if (filter.LocationIds != null) { events = events.Where(_ => filter.LocationIds.Contains(_.AtLocationId)); } // filter by program ids if (filter.ProgramIds != null) { events = events.Where(_ => filter.ProgramIds.Any(p => p == _.ProgramId)); } // filter by user ids if (filter.UserIds != null) { events = events.Where(_ => filter.UserIds.Contains(_.CreatedBy)); } // filter by dates if (filter.StartDate != null) { events = events.Where(_ => ((_.AllDay == false || _.EndDate.HasValue == false) && _.StartDate.Date >= filter.StartDate.Value.Date) || _.EndDate.Value.Date >= filter.StartDate.Value.Date); } if (filter.EndDate != null) { events = events.Where(_ => ((_.AllDay == false || _.EndDate.HasValue == false) && _.StartDate.Date <= filter.EndDate.Value.Date) || _.StartDate.Date <= filter.EndDate.Value.Date); } // apply search if (!string.IsNullOrEmpty(filter.Search)) { events = events.Where(_ => _.Name.Contains(filter.Search) || _.Description.Contains(filter.Search)); } return(events.OrderBy(_ => _.StartDate)); }
/// <summary> /// Constructs an event object from a notification. /// </summary> /// <param name="session">The session.</param> /// <param name="monitoredItem">The monitored item that produced the notification.</param> /// <param name="notification">The notification.</param> /// <param name="knownEventTypes">The known event types.</param> /// <param name="eventTypeMappings">Mapping between event types and known event types.</param> /// <returns> /// The event object. Null if the notification is not a valid event type. /// </returns> public static BaseEventState ConstructEvent( Session session, MonitoredItem monitoredItem, EventFieldList notification, Dictionary <NodeId, Type> knownEventTypes, Dictionary <NodeId, NodeId> eventTypeMappings) { // find the event type. NodeId eventTypeId = FindEventType(monitoredItem, notification); if (eventTypeId == null) { return(null); } // look up the known event type. Type knownType = null; NodeId knownTypeId = null; if (eventTypeMappings.TryGetValue(eventTypeId, out knownTypeId)) { knownType = knownEventTypes[knownTypeId]; } // try again. if (knownType == null) { if (knownEventTypes.TryGetValue(eventTypeId, out knownType)) { knownTypeId = eventTypeId; eventTypeMappings.Add(eventTypeId, eventTypeId); } } // try mapping it to a known type. if (knownType == null) { // browse for the supertypes of the event type. ReferenceDescriptionCollection supertypes = ClientUtils.BrowseSuperTypes(session, eventTypeId, false); // can't do anything with unknown types. if (supertypes == null) { return(null); } // find the first supertype that matches a known event type. for (int ii = 0; ii < supertypes.Count; ii++) { NodeId superTypeId = (NodeId)supertypes[ii].NodeId; if (knownEventTypes.TryGetValue(superTypeId, out knownType)) { knownTypeId = superTypeId; eventTypeMappings.Add(eventTypeId, superTypeId); } if (knownTypeId != null) { break; } } // can't do anything with unknown types. if (knownTypeId == null) { return(null); } } // construct the event based on the known event type. BaseEventState e = (BaseEventState)Activator.CreateInstance(knownType, new object[] { (NodeState)null }); // get the filter which defines the contents of the notification. EventFilter filter = monitoredItem.Status.Filter as EventFilter; // initialize the event with the values in the notification. e.Update(session.SystemContext, filter.SelectClauses, notification); // save the orginal notification. e.Handle = notification; return(e); }
public async Task <int> CountAsync(EventFilter filter) { return(await ApplyFilters(filter) .CountAsync()); }
public override string FindEvents(System.DateTime StartPoint, System.DateTime EndPoint, [System.Xml.Serialization.XmlIgnoreAttribute()] bool EndPointSpecified, SearchScope Scope, EventFilter SearchFilter, bool IncludeStartState, int MaxMatches, [System.Xml.Serialization.XmlIgnoreAttribute()] bool MaxMatchesSpecified, [System.Xml.Serialization.XmlElementAttribute(DataType = "duration")] string KeepAliveTime) { TestSuitInit(); string res; int timeOut; SoapException ex; StepType stepType = SearchServiceTest.FindEventsTest(out res, out ex, out timeOut, StartPoint, EndPoint, EndPointSpecified, Scope, SearchFilter, IncludeStartState, MaxMatches, MaxMatchesSpecified, KeepAliveTime); StepTypeProcessing(stepType, ex, timeOut); return(res); }
/// <summary> /// Returns value of the field name containing the event type. /// </summary> public object GetFieldValue( EventFieldList eventFields, NodeId eventTypeId, IList <QualifiedName> browsePath, uint attributeId) { if (eventFields == null) { return(null); } EventFilter filter = m_filter as EventFilter; if (filter == null) { return(null); } for (int ii = 0; ii < filter.SelectClauses.Count; ii++) { if (ii >= eventFields.EventFields.Count) { return(null); } // check for match. SimpleAttributeOperand clause = filter.SelectClauses[ii]; // attribute id if (clause.AttributeId != attributeId) { continue; } // match null browse path. if (browsePath == null || browsePath.Count == 0) { if (clause.BrowsePath != null && clause.BrowsePath.Count > 0) { continue; } // ignore event type id when matching null browse paths. return(eventFields.EventFields[ii].Value); } // match browse path. // event type id. if (clause.TypeDefinitionId != eventTypeId) { continue; } // match element count. if (clause.BrowsePath.Count != browsePath.Count) { continue; } // check each element. bool match = true; for (int jj = 0; jj < clause.BrowsePath.Count; jj++) { if (clause.BrowsePath[jj] != browsePath[jj]) { match = false; break; } } // check of no match. if (!match) { continue; } // return value. return(eventFields.EventFields[ii].Value); } // no event type in event field list. return(null); }
/// <summary> /// Creates a set of monitored items. /// </summary> public MonitoredItem CreateMonitoredItem( OperationContext context, INodeManager nodeManager, object handle, uint subscriptionId, uint monitoredItemId, TimestampsToReturn timestampsToReturn, double publishingInterval, MonitoredItemCreateRequest itemToCreate, EventFilter filter) { lock (m_lock) { // calculate sampling interval. double samplingInterval = itemToCreate.RequestedParameters.SamplingInterval; if (samplingInterval < 0) { samplingInterval = publishingInterval; } // limit the queue size. uint queueSize = itemToCreate.RequestedParameters.QueueSize; if (queueSize > m_maxEventQueueSize) { queueSize = m_maxEventQueueSize; } // create the monitored item. MonitoredItem monitoredItem = new MonitoredItem( m_server, nodeManager, handle, subscriptionId, monitoredItemId, context.Session, itemToCreate.ItemToMonitor, context.DiagnosticsMask, timestampsToReturn, itemToCreate.MonitoringMode, itemToCreate.RequestedParameters.ClientHandle, filter, filter, null, samplingInterval, queueSize, itemToCreate.RequestedParameters.DiscardOldest, MinimumSamplingIntervals.Continuous); // save the monitored item. m_monitoredItems.Add(monitoredItemId, monitoredItem); return monitoredItem; } }
public static extern void SetEventFilter( EventFilter filter, IntPtr userdata );
public static extern void DelEventWatch(EventFilter filter, IntPtr userdata);
public static extern void AddEventWatch( EventFilter filter, IntPtr userdata );
internal void AsyncGetImageFile(object sender, AsyncGetImageEventArgs e) { string strError = ""; if (String.IsNullOrEmpty(e.RecPath) == true) { strError = "e.RecPath 为空,无法获得图像文件"; goto ERROR1; } if (StringUtil.HasHead(e.ObjectPath, "http:") == true) { EventFilter filter = new EventFilter(); // filter.BiblioRegister = biblioRegister; filter.Row = e.Row; filter.BiblioRecPath = e.RecPath; this._imageManager.AsyncGetObjectFile( "", "", e.ObjectPath, e.FileName, filter); } else { string strPath = ""; string strServerName = ""; StringUtil.ParseTwoPart(e.RecPath, "@", out strPath, out strServerName); AccountInfo account = _base.GetAccountInfo(strServerName, false); if (account == null) { strError = "e.RecPath 中 '" + e.RecPath + "' 服务器名 '" + strServerName + "' 没有配置"; goto ERROR1; } string strServerUrl = account.ServerUrl; string strUserName = account.UserName; if (EntityRegisterBase.IsDot(strServerUrl) == true) strServerUrl = this.MainForm.LibraryServerUrl; if (EntityRegisterBase.IsDot(strUserName) == true) strUserName = this.MainForm.DefaultUserName; EventFilter filter = new EventFilter(); // filter.BiblioRegister = biblioRegister; filter.Row = e.Row; filter.BiblioRecPath = e.RecPath; // string strObjectPath = strPath + "/object/" + e.ObjectPath; string strObjectPath = ScriptUtil.MakeObjectUrl(strPath, e.ObjectPath); this._imageManager.AsyncGetObjectFile(strServerUrl, strUserName, strObjectPath, e.FileName, filter); } return; ERROR1: this.AsyncGetImageComplete(e.Row, "", null, strError); }
public static extern void FilterEvents( EventFilter filter, IntPtr userdata );
private void SendClassPrepareEvent(JvmtiEnvironment environment, EventFilter filter, ThreadId threadId, TaggedReferenceTypeId classId, string signature, ClassStatus classStatus, bool preventSuspend) { if (!VirtualMachine.IsAgentThread.Value) { // ignore events before VMInit if (AgentEventDispatcher == null) return; // dispatch this call to an agent thread Action<JvmtiEnvironment, EventFilter, ThreadId, TaggedReferenceTypeId, string, ClassStatus, bool> method = SendClassPrepareEvent; AgentEventDispatcher.Invoke(method, environment, filter, threadId, classId, signature, classStatus, preventSuspend); return; } JniEnvironment nativeEnvironment; JniErrorHandler.ThrowOnFailure(VirtualMachine.AttachCurrentThreadAsDaemon(environment, out nativeEnvironment, true)); SuspendPolicy suspendPolicy = preventSuspend ? SuspendPolicy.None : filter.SuspendPolicy; if (!preventSuspend) ApplySuspendPolicy(environment, nativeEnvironment, filter.SuspendPolicy, threadId); Callback.ClassPrepare(suspendPolicy, filter.RequestId, threadId, classId.TypeTag, classId.TypeId, signature, classStatus); }
static void Main(string[] args) { bool start = false; Injected_Processes_IDsList.Add("0"); Injected_Processes_IDsList.Add("0"); Console.CancelKeyPress += Console_CancelKeyPress; Temp_Thread_InfoDebugMode = new DataTable(); Temp_Thread_InfoDebugMode.Columns.Add("tid", typeof(int)); Temp_Thread_InfoDebugMode.Columns.Add("Time_Negative"); Temp_Thread_InfoDebugMode.Columns.Add("status"); Temp_Thread_InfoDebugMode.Columns.Add("tid_StartAddress_x64"); Temp_Thread_InfoDebugMode.Columns.Add("StartTime"); Temp_Thread_InfoDebugMode.Columns.Add("Proc_Name"); Temp_Thread_InfoDebugMode.Columns.Add("Proc_id"); Temp_Thread_InfoDebugMode.Columns.Add("IsNewProcess"); Temp_Thread_InfoDebugMode.Columns.Add("tid_StartAddress"); Console.ForegroundColor = ConsoleColor.DarkGray; Console.WriteLine(); Console.WriteLine("ETWMonThread 1.0 (x64 only) "); Console.WriteLine("Realtime Scanning/Monitoring Thread Injection for MPD (Meterpreter Payload Detection) by ETW"); Console.ForegroundColor = ConsoleColor.Gray; Console.WriteLine("Published by Damon Mohammadbagher Jan 2018"); if (args.Length == 0) { start = true; } if (args.Length == 1) { if (args[0].ToUpper() == "IPS") { IPS_IDS = true; start = true; } else { IPS_IDS = false; start = true; } if (args[0].ToUpper() == "SHOWALL") { IsShowAllRecrds = true; start = true; } } if (args.Length >= 2) { if (args[0].ToUpper() == "IPS" && args[1].ToUpper() == "DEBUG") { IPS_IDS = true; Is_DebugMode = true; start = true; } if (args[0].ToUpper() == "SHOWALL" && args[1].ToUpper() == "DEBUG") { IsShowAllRecrds = true; Is_DebugMode = true; start = true; } } if (args.Length >= 1) { if (args[0].ToUpper() == "HELP") { start = false; Console.ForegroundColor = ConsoleColor.DarkYellow; Console.WriteLine(); Console.WriteLine("[!] ETWMonThread , Realtime Scanning/Monitoring Thread Injection for MPD (Meterpreter Payload Detection) by ETW"); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[!] Syntax 1: Realtime Scanning/Monitoring IPS Mode (Killing Meterpreter Injected Threads)"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[!] Syntax 1: ETWMonThread.exe \"IPS\" [optional] \"DEBUG\""); Console.WriteLine("[!] Example1: ETWMonThread.exe IPS "); Console.WriteLine("[!] Example2: ETWMonThread.exe IPS DEBUG"); Console.WriteLine(); Console.ForegroundColor = ConsoleColor.DarkCyan; Console.WriteLine("[!] Syntax 2: Realtime Monitoring IDS Mode"); Console.ForegroundColor = ConsoleColor.Cyan; Console.WriteLine("[!] Syntax 2: ETWMonThread.exe [optional] \"SHOWALL\" [optional] \"DEBUG\" "); Console.WriteLine("[!] Example1: ETWMonThread.exe"); Console.WriteLine("[!] Example2: ETWMonThread.exe SHOWALL"); Console.WriteLine("[!] Example3: ETWMonThread.exe SHOWALL DEBUG"); Console.ForegroundColor = ConsoleColor.Gray; } } if (start) { Console.WriteLine(); if (IPS_IDS) { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[!] Realtime Scanning/Monitoring IPS Mode (warning : Killing Threads)"); Console.ForegroundColor = ConsoleColor.Gray; } else { Console.ForegroundColor = ConsoleColor.Yellow; Console.WriteLine("[!] Realtime Monitoring IDS Mode"); Console.ForegroundColor = ConsoleColor.Gray; } /// EventID 3 is for "Thread Created" var ETWEventsFilter = new EventFilter(Filter.EventIdIs(3)); ETWEventsFilter.OnEvent += ETWEventsFilter_OnEvent; P.OnError += P_OnError; P.AddFilter(ETWEventsFilter); T.Enable(P); T.Start(); } }
/// <summary> /// Sets the default event filter. /// </summary> private void UseDefaultEventFilter() { EventFilter filter = filter = new EventFilter(); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventId); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.EventType); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.SourceNode); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.SourceName); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Time); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.ReceiveTime); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.LocalTime); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Message); filter.AddSelectClause(ObjectTypes.BaseEventType, Opc.Ua.BrowseNames.Severity); m_filter = filter; }
public void Setup() { events = new EventFilter <Monitor>(Level.Debug); new EventFilter <TestHandler>(Level.Debug, events.FakeAppender); }
private void AddFilter(EventFilter filter) { _filters.Add(filter); }
public static extern void DelEventWatch(EventFilter filter, void *userdata);
/// <summary> /// Fetches the event fields from the event. /// </summary> private EventFieldList GetEventFields(FilterContext context, EventFilter filter, IFilterTarget instance) { // fetch the event fields. EventFieldList fields = new EventFieldList(); fields.ClientHandle = m_clientHandle; fields.Handle = instance; foreach (SimpleAttributeOperand clause in filter.SelectClauses) { // get the value of the attribute (apply localization). object value = instance.GetAttributeValue( context, clause.TypeDefinitionId, clause.BrowsePath, clause.AttributeId, clause.ParsedIndexRange); // add the value to the list of event fields. if (value != null) { // translate any localized text. LocalizedText text = value as LocalizedText; if (text != null) { value = m_server.ResourceManager.Translate(m_session.PreferredLocales, text); } // add value. fields.EventFields.Add(new Variant(value)); } // add a dummy entry for missing values. else { fields.EventFields.Add(Variant.Null); } } return fields; }
private void OkBTN_Click(object sender, EventArgs e) { try { EventFilter filter = new EventFilter(); filter.SelectClauses.AddRange(SelectClauseCTRL.GetSelectClauses()); filter.WhereClause = ContentFilterCTRL.GetFilter(); EventFilter.Result result = filter.Validate(new FilterContext(m_session.NamespaceUris, m_session.TypeTree)); if (ServiceResult.IsBad(result.Status)) { throw ServiceResultException.Create(StatusCodes.BadEventFilterInvalid, result.GetLongString()); } m_filter = filter; DialogResult = DialogResult.OK; } catch (Exception exception) { GuiUtils.HandleException(this.Text, MethodBase.GetCurrentMethod(), exception); } }