public void TestGenericEvents() { var a = new EventSource(); var e = new IncomingEvent<EventArgs> { Channel = "a", DataObject = new EventArgs { Id = 10 }, EventName = "foo" }; (e as IncomingEvent).Data = "{id:10}"; var events = new List<IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.GetEventSubscription<EventArgs>().EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.DataObject.Id, e.DataObject.Id); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 2, "Event should get through twice when you have two subscriptions"); }
public void WhenSourceEventRaised_ThenCollectedSubscriberIsNotNotified() { var source = new EventSource(); var publisher = new EventPublisher(source); var subscriber = new EventSubscriber(); var subscription = publisher.PropertyChanged.Subscribe(subscriber.OnChanged); try { subscriber = null; subscription.Dispose(); GC.Collect(); GC.WaitForFullGCApproach(-1); GC.WaitForFullGCComplete(-1); GC.WaitForPendingFinalizers(); source.RaisePropertyChanged("Foo"); Assert.Equal(0, EventSubscriber.ChangedProperties.Count); } finally { //subscription.Dispose(); } }
public TestEventSource(EventSource r) { if (r != null) source = r; else source = new EventSource(); }
public static TestEventSource BuildSourceFromDataBaseData(string idReferral) { using (NpgsqlConnection connection = Global.GetSqlConnection()) { string findPatient = "SELECT is_referral_review_source_mo, referral_creation_date, planned_date, referral_out_date, referral_review_date_source_mo FROM public.referral WHERE id_referral = '" + idReferral + "'ORDER BY id_referral DESC LIMIT 1"; NpgsqlCommand person = new NpgsqlCommand(findPatient, connection); using (NpgsqlDataReader personFromDataBase = person.ExecuteReader()) { EventSource p = new EventSource(); while (personFromDataBase.Read()) { if (personFromDataBase["is_referral_review_source_mo"] != DBNull.Value) p.IsReferralReviewed = Convert.ToBoolean(personFromDataBase["is_referral_review_source_mo"]); if (personFromDataBase["referral_creation_date"] != DBNull.Value) p.ReferralCreateDate = Convert.ToDateTime(personFromDataBase["referral_creation_date"]); if (personFromDataBase["planned_date"] != DBNull.Value) p.PlannedDate = Convert.ToDateTime(personFromDataBase["planned_date"]); if (personFromDataBase["referral_out_date"] != DBNull.Value) p.ReferralOutDate = Convert.ToDateTime(personFromDataBase["referral_out_date"]); if (personFromDataBase["referral_review_date_source_mo"] != DBNull.Value) p.ReferralReviewDate = Convert.ToDateTime(personFromDataBase["referral_review_date_source_mo"]); TestEventSource pers = new TestEventSource(p); return pers; } } } return null; }
protected override void OnEventSourceCreated(EventSource eventSource) { if (!this.Disabled) { this.EnableEvents(eventSource, EventLevel.LogAlways, (EventKeywords) ~0); } }
protected override void OnEventSourceCreated(EventSource eventSource) { // There is a bug in the EventListener library that causes this override to be called before the object is fully constructed. // So if we are not constructed yet, we will just remember the event source reference. Once the construction is accomplished, // we can decide if we want to handle a given event source or not. // Locking on 'this' is generally a bad practice because someone from outside could put a lock on us, and this is outside of our control. // But in the case of this class it is an unlikely scenario, and because of the bug described above, // we cannot rely on construction to prepare a private lock object for us. lock (this) { if (!this.constructed) { if (this.eventSourcesPresentAtConstruction == null) { this.eventSourcesPresentAtConstruction = new List<EventSource>(); } this.eventSourcesPresentAtConstruction.Add(eventSource); } else if (!this.Disabled) { EnableEventSource(eventSource); } } }
protected override void OnEventSourceCreated(EventSource eventSource) { if (eventSource.Name.StartsWith("Microsoft-ApplicationInsights-", StringComparison.Ordinal)) { this.EnableEvents(eventSource, this.logLevel, (EventKeywords)AllKeyword); } base.OnEventSourceCreated(eventSource); }
public void Log(EventSource eventSource, Exception exception, EventId eventId, EventLogEntryType logEntryType) { if (!EventLog.SourceExists(eventSource.ToString())) { EventLog.CreateEventSource(eventSource.ToString(), "TrainSurfer"); } EventLog log = new EventLog(); log.Source = eventSource.ToString(); log.WriteEntry(FormatException(exception), logEntryType, (int)eventId); }
public void WhenWeakTargetCollected_ThenWeakReferenceNotAlive() { var source = new EventSource(); var weak = new WeakReference(source); source = null; GC.Collect(); Assert.False(weak.IsAlive); }
public static int CreateEvent (EventSource eventSource, EventType eventType, int actingPersonId, int organizationId, int geographyId, int affectedPersonId, int parameterInt, string parameterText) { //TODO: organizationId comes in hardcoded as 1 from a lot of places, should probably be changed based on affected person // to the party for that country if not swedish. return SwarmDb.GetDatabaseForWriting().CreateEvent(eventSource, eventType, actingPersonId, organizationId, geographyId, affectedPersonId, parameterInt, parameterText); }
/// <summary> /// Override this method to get a list of all the eventSources that exist. /// </summary> protected override void OnEventSourceCreated(EventSource eventSource) { // Because we want to turn on every EventSource, we subscribe to a callback that triggers // when new EventSources are created. It is also fired when the EventListner is created // for all pre-existing EventSources. Thus this callback get called once for every // EventSource regardless of the order of EventSource and EventListener creation. // For any EventSource we learn about, turn it on. EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All); }
public void InstallerWillWireUpSubjectToPublicMethodInInternalListenerClass() { InternalListener listener = new InternalListener(); EventSource source = new EventSource(); ReflectionInstrumentationBinder binder = new ReflectionInstrumentationBinder(); binder.Bind(source, listener); source.Fire(); Assert.IsTrue(listener.callbackHappened); }
public static void CreateActivistWithLogging (Geography geo, Person newActivist, string logMessage, EventSource evtSrc, bool isPublic, bool isConfirmed, int orgId) { PWEvents.CreateEvent(evtSrc, EventType.NewActivist, newActivist.Identity, orgId, geo.Identity, newActivist.Identity, 0, string.Empty); newActivist.CreateActivist(isPublic, isConfirmed); PWLog.Write(newActivist, PWLogItem.Person, newActivist.Identity, PWLogAction.ActivistJoin, "New activist joined.", logMessage); }
/// <summary> /// Initializes a new instance of the <see cref="BuildLogger"/> class. /// </summary> /// <param name="logger">The logger used by this instance. Can be <c>null</c>.</param> /// <param name="eventSource">The event source.</param> /// <exception cref="ArgumentNullException"><paramref name="eventSource"/> is <c>null</c>.</exception> internal BuildLogger(ILogger logger, EventSource eventSource) { if (eventSource == null) { throw new ArgumentNullException("eventSource"); } this.eventSource = eventSource; if (logger != null) { Initialize(logger); } }
public static void TerminateActivistWithLogging (Person p, EventSource eventSourceSignupPage) { int orgId = 1; PWEvents.CreateEvent(eventSourceSignupPage, EventType.LostActivist, p.Identity, orgId, p.Geography.Identity, p.Identity, 0, string.Empty); p.TerminateActivist(); PWLog.Write(PWLogItem.Person, p.Identity, PWLogAction.ActivistLost, "Lost as activist", string.Empty); }
/// <summary> /// Install the ETW manifest if needed. /// </summary> /// <param name="eventSource"></param> internal static bool EnsureInstall(EventSource eventSource) { if (IsInstalled(eventSource)) { return true; } if (DoInstall(eventSource)) { return IsInstalled(eventSource); } return false; }
/// <summary> /// Gets the <see cref="EventSchema"/> for the specified eventId and eventSource. /// </summary> /// <param name="eventId">The ID of the event.</param> /// <param name="eventSource">The event source.</param> /// <returns>The EventSchema.</returns> public EventSchema GetSchema(int eventId, EventSource eventSource) { Guard.ArgumentNotNull(eventSource, "eventSource"); IReadOnlyDictionary<int, EventSchema> events; if (!this.schemas.TryGetValue(eventSource.Guid, out events)) { events = new ReadOnlyDictionary<int, EventSchema>(this.schemaReader.GetSchema(eventSource)); this.schemas[eventSource.Guid] = events; } return events[eventId]; }
public void WhenSourceEventRaised_ThenSubscriberIsNotified() { var source = new EventSource(); var publisher = new EventPublisher(source); var subscriber = new EventSubscriber(); publisher.PropertyChanged.Subscribe(subscriber.OnChanged); Assert.Equal(0, EventSubscriber.ChangedProperties.Count); source.RaisePropertyChanged("Foo"); Assert.Equal(1, EventSubscriber.ChangedProperties.Count); Assert.Equal("Foo", EventSubscriber.ChangedProperties[0]); }
public InputManager(Game game) : base(game) { CursorCentered = true; EventsFired = new[] { EventConstants.MousePositionUpdated, EventConstants.LeftMouseDown, EventConstants.LeftMouseUp, EventConstants.RightMouseDown, EventConstants.RightMouseUp, EventConstants.KeyDown, EventConstants.KeyUp }; m_eventSourceImpl = new EventSource(EventsFired, true); }
/// <summary> /// Intercept call to gaether locally items for filtering. /// </summary> protected override void channel_ItemsAddedEvent(EventSource source, EventSourceChannel channel, IEnumerable<EventBase> items) { foreach (RssNewsEvent item in items) { if ((DateTime.Now - item.DateTime) < TimeSpan.FromDays(7) && _latestNewsItemsTitles.ContainsKey(item.Title) == false) {// Gather items from the last 3 days. lock (this) { _latestNewsItemsTitles.Add(item.Title, item); } } } base.channel_ItemsAddedEvent(source, channel, items); }
internal void Enable( byte* scratch, int scratchSize, EventSource.EventData* datas, int dataCount, GCHandle* pins, int pinCount) { this.datasStart = datas; this.scratchEnd = scratch + scratchSize; this.datasEnd = datas + dataCount; this.pinsEnd = pins + pinCount; this.scratch = scratch; this.datas = datas; this.pins = pins; this.writingScalars = false; }
protected void Application_Start(object sender, EventArgs e) { // TEMPORARY!!! var source = new EventSource<SimpleInput>(); ObjectFactory.Initialize(x => { x.For<IServerEventWriter>().Use<ServerEventWriter>(); x.ForSingletonOf<IEventSource<SimpleInput>>().Use(source); x.For<IActivator>().Add(new BandActivator(source)); }); FubuApplication .For<AspNetApplicationFubuRegistry>() .StructureMapObjectFactory() .Bootstrap(); }
public void TestEventsAreTriggered() { var a = new EventSource(); var e = new IncomingEvent {Channel = "a", Data = "{}", EventName = "foo"}; var events = new List<IIncomingEvent>(); a.EventEmitted += (sender, evt) => { Assert.AreEqual(evt.Channel, e.Channel); Assert.AreEqual(evt.Data, e.Data); Assert.AreEqual(evt.EventName, e.EventName); events.Add(evt); }; a.EmitEvent(e); Assert.AreEqual(events.Count, 1); }
public void Given_an_event_source_when_a_object_is_retrieved_and_no_strong_reference_is_held_then_garbage_collection_of_retrieved_object_is_free_to_occur() { var es = new EventSource(new NullPersistenceStrategy()); var finalized = false; var ba = es.OpenOrCreate<BankAccountWithGcNotify>(new Guid("a2d06e1b-a311-45c7-9097-d288d61a8c33")); ba.FinalizeCallback = () => finalized = true; // ReSharper disable RedundantAssignment ba = null; // ReSharper restore RedundantAssignment GC.Collect(); GC.WaitForPendingFinalizers(); // Note: This test will fail in NCrunch with default settings. You must turn off the "Analyse line execution times" // function for this project only under the NCrunch -> Configuration screen. Assert.That(finalized); }
public static void ConnectToEventSource() { EventSource mySource = new EventSource(); mySource.OpenEvent += new OpenEventHandler((object sender, OpenEventArgs e) => { Console.WriteLine("Open Event"); }); mySource.MessageEvent += new MessageEventHandler((object sender, MessageEventArgs e) => { Console.WriteLine(e.Data); }); mySource.ErrorEvent += new ErrorEventHandler((object sender, ErrorEventArgs e) => { Console.WriteLine("Error Event"); }); mySource.Connect("http://localhost:8001/sse"); //mySocket.Disconnect(); // if (SocketCreated && (ws.readyState == 0 || ws.readyState == 1)) { // Web Socket connecting or connected // ws.close(); // } else { // Log("Trying to connect to the server ..."); // try { // ws = new com.kaazing.gateway.client.html5.WebSocket("ws://localhost:8181/test"); // + document.getElementById("Connection").value // SocketCreated = true; // } catch (ex) { // Log(ex, "ERROR"); // return; // } // document.getElementById("ToggleConnection").innerHTML = "Disconnect"; // ws.onopen = WSonOpen; // ws.onmessage = WSonMessage; // ws.onclose = WSonClose; // ws.onerror = WSonError; // } }
/// <summary> /// TODO: Rather than running multiple processes, there might be a slicker way: http://stackoverflow.com/questions/437419/ /// </summary> /// <param name="eventSource"></param> /// <returns></returns> public static bool DoInstall(EventSource eventSource) { try { string sourceFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string destFolder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), eventSource.Name); string manifestName = string.Format("{0}.{1}.etwManifest.man", Assembly.GetExecutingAssembly().GetName().Name, eventSource.Name); string sourceFile = Directory.EnumerateFiles(sourceFolder, manifestName).FirstOrDefault(); string destFile = Directory.Exists(destFolder) ? Directory.EnumerateFiles(destFolder, manifestName).FirstOrDefault() : null; string args; // To be safe, uninstall the manifest already in the target folder. destFile = Directory.Exists(destFolder) ? Directory.EnumerateFiles(destFolder, manifestName).FirstOrDefault() : null; if (destFile != null) { args = string.Format("um {0}", destFile); Process.Start(new ProcessStartInfo("wevtutil.exe", args) { Verb = "runAs" }).WaitForExit(); } // Copy our manifest over to the target. if (!Directory.Exists(destFolder)) { Directory.CreateDirectory(destFolder); } string destPath = Path.Combine(destFolder, Path.GetFileName(sourceFile)); File.Copy(sourceFile, destPath, true); File.Copy(sourceFile.Replace(".man", ".dll"), destPath.Replace(".man", ".dll"), true); // Install the manifest. args = string.Format("im {0} /rf:\"{1}\" /mf:\"{1}\"", destPath, Path.Combine(destFolder, Path.GetFileNameWithoutExtension(destPath) + ".dll")); Process.Start(new ProcessStartInfo("wevtutil.exe", "um" + args.Substring(2)) { Verb = "runAs" }).WaitForExit(); Process.Start(new ProcessStartInfo("wevtutil.exe", args) { Verb = "runAs" }).WaitForExit(); } catch { return false; } return true; }
public Player(Block[] blocks, MappingFunctionVector3 mappingFunction) { FlyingEnabled = true; m_blocks = blocks; m_mappingFunction = mappingFunction; Equipable = new Shovel(); m_eventSinkImpl = new EventSinkImpl(); m_eventSinkImpl.AddHandler<Vector2Args>(EventConstants.MousePositionUpdated, OnMouseUpdated); m_eventSinkImpl.AddHandler<KeyArgs>(EventConstants.KeyDown, OnKeyDown); m_eventSinkImpl.AddHandler<KeyArgs>(EventConstants.KeyUp, OnKeyUp); m_eventSinkImpl.AddHandler<MouseButtonArgs>(EventConstants.LeftMouseDown, OnLeftMouseDown); m_eventSinkImpl.AddHandler<MouseButtonArgs>(EventConstants.LeftMouseUp, OnLeftMouseUp); m_eventSinkImpl.AddHandler<MouseButtonArgs>(EventConstants.RightMouseDown, OnRightMouseDown); m_eventSinkImpl.AddHandler<MouseButtonArgs>(EventConstants.RightMouseUp, OnRightMouseUp); EventsFired = new[] { EventConstants.PlayerPositionUpdated, EventConstants.ViewUpdated }; m_eventSourceImpl = new EventSource(EventsFired, true); }
public void WhenDetached_ThenDoesNotInvokeCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, handler => { sender.Event -= handler.OnEvent; }); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsFalse(invoked); }
public void WhenDetachedWithNullDetachAction_ThenInvokesCallbackOnEvent() { var instance = this; var sender = new EventSource(); var invoked = false; var weakHandler = new WeakEventHandler<WeakEventListenerFixture, object, EventArgs>( instance, (i, s, e) => { invoked = true; }, null); sender.Event += weakHandler.OnEvent; weakHandler.Detach(); sender.FireEvent(new EventArgs()); Assert.IsTrue(invoked); }
#pragma warning disable 1591 // Xml Comments public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId) { var eventPath = GetPathFor(eventSource.GetType().Name, eventSourceId); var files = Directory.GetFiles(eventPath).OrderBy(f => f); var stream = new CommittedEventStream(eventSourceId); var target = new EventHolder { Type = typeof(string), Version = EventSourceVersion.Zero, Event = string.Empty }; foreach (var file in files) { var json = File.ReadAllText(file); _serializer.FromJson(target, json); var @event = _serializer.FromJson(target.Type, json) as IEvent; stream.Append(new[] { @event }); } return stream; }
public void Test_EventSourceCreatedEvents_BeforeListener() { TestUtilities.CheckNoEventSourcesRunning("Start"); EventSource log = null; EventSource log2 = null; EventListenerListener el = null; try { string esName = "EventSourceName_HopefullyUnique"; string esName2 = "EventSourceName_HopefullyUnique2"; bool esNameHit = false; bool esName2Hit = false; log = new EventSource(esName); log2 = new EventSource(esName2); using (var listener = new EventListenerListener()) { List <EventSource> eventSourceNotificationsReceived = new List <EventSource>(); listener.EventSourceCreated += (s, a) => { if (a.EventSource.Name.Equals(esName)) { esNameHit = true; } if (a.EventSource.Name.Equals(esName2)) { esName2Hit = true; } }; Thread.Sleep(1000); Assert.True(esNameHit); Assert.True(esName2Hit); } } finally { if (log != null) { log.Dispose(); } if (log2 != null) { log2.Dispose(); } if (el != null) { el.Dispose(); } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public unsafe void Test_WriteEvent_ArgsBasicTypes() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener(log)) { var sources = EventSource.GetSources(); Assert.Contains(log, sources); Assert.NotNull(EventSource.GenerateManifest(typeof(SimpleEventSource), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); Assert.Null(EventSource.GenerateManifest(typeof(EventSourceTest), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); log.Event0(); Assert.Equal(1, LoudListener.t_lastEvent.EventId); Assert.Equal(0, LoudListener.t_lastEvent.Payload.Count); #region Validate "int" arguments log.EventI(10); Assert.Equal(2, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); log.EventII(10, 11); Assert.Equal(3, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventIII(10, 11, 12); Assert.Equal(4, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "long" arguments log.EventL(10); Assert.Equal(5, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); log.EventLL(10, 11); Assert.Equal(6, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventLLL(10, 11, 12); Assert.Equal(7, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (long)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "string" arguments log.EventS("10"); Assert.Equal(8, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); log.EventSS("10", "11"); Assert.Equal(9, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); log.EventSSS("10", "11", "12"); Assert.Equal(10, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); Assert.Equal("12", (string)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate byte array arguments var rng = new Random(42); byte[] arr = new byte[20]; rng.NextBytes(arr); log.EventWithByteArray(arr); Assert.Equal(52, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(arr, (byte[])LoudListener.t_lastEvent.Payload[0]); log.EventWithByteArray(new byte[0]); Assert.Equal(52, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Same(Array.Empty <byte>(), (byte[])LoudListener.t_lastEvent.Payload[0]); log.EventWithByteArray(null); Assert.Equal(52, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Same(Array.Empty <byte>(), (byte[])LoudListener.t_lastEvent.Payload[0]); arr = new byte[20]; rng.NextBytes(arr); log.EventWithByteArrayCustom(arr); Assert.Equal(53, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(arr, (byte[])LoudListener.t_lastEvent.Payload[0]); log.EventWithByteArrayCustom(new byte[0]); Assert.Equal(53, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Same(Array.Empty <byte>(), (byte[])LoudListener.t_lastEvent.Payload[0]); arr = new byte[20]; rng.NextBytes(arr); fixed(byte *arrPtr = arr) { log.EventWithBytePointer(arrPtr, arr.Length); } Assert.Equal(54, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(arr, (byte[])LoudListener.t_lastEvent.Payload[0]); log.EventWithBytePointer((byte *)IntPtr.Zero, 0); Assert.Equal(54, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Same(Array.Empty <byte>(), (byte[])LoudListener.t_lastEvent.Payload[0]); #endregion #region Validate mixed type arguments log.EventSI("10", 11); Assert.Equal(11, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventSL("10", 11); Assert.Equal(12, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventSII("10", 11, 12); Assert.Equal(13, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate enums/flags log.EventEnum(MyColor.Blue); Assert.Equal(19, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Blue, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventEnum1(MyColor.Green); Assert.Equal(20, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Green, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventFlags(MyFlags.Flag1); Assert.Equal(21, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); log.EventFlags1(MyFlags.Flag1); Assert.Equal(22, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); #endregion #region Validate DateTime Test_WriteEvent_ArgsBasicTypes_Etw_Validate_DateTime(log); #endregion } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
/// <summary> /// Inspects the specified <see cref="EventSource" /> for potential runtime errors. /// </summary> /// <param name="eventSource">The event source instance to inspect.</param> /// <example> /// <code>EventSourceAnalyzer.InspectAll(MyEventSource.Instance);</code> /// <remarks>Where 'Instance' property returns a singleton instance of 'MyEventSource' class like: /// <code>public static MyEventSource Instance = new MyEventSource();</code> /// </remarks> /// </example> /// <exception cref="EventSourceAnalyzerException">Exception thrown if a failure was found in the specified <see cref="System.Diagnostics.Tracing.EventSource" />.</exception> /// <exception cref="ArgumentException">Exception thrown if a failure was found in the specified <see cref="System.Diagnostics.Tracing.EventSource" />.</exception> public static void InspectAll(EventSource eventSource) { var instance = new EventSourceAnalyzer(); instance.Inspect(eventSource); }
/// <summary> /// Create handler for dependency telemetry. /// </summary> private Action <ITelemetry> CreateHandlerForDependencyTelemetry(EventSource eventSource, MethodInfo writeGenericMethod, Type eventSourceOptionsType, PropertyInfo eventSourceOptionsKeywordsProperty) { var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType); var keywords = Keywords.Dependencies; eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords); var dummyDependencyData = new RemoteDependencyData(); var writeMethod = writeGenericMethod.MakeGenericMethod(new { PartA_iKey = this.dummyPartAiKeyValue, PartA_Tags = this.dummyPartATagsValue, PartB_RemoteDependencyData = new { // The properties and layout should be the same as RemoteDependencyData_types.cs dummyDependencyData.ver, dummyDependencyData.name, dummyDependencyData.id, dummyDependencyData.resultCode, dummyDependencyData.duration, dummyDependencyData.success, dummyDependencyData.data, dummyDependencyData.target, dummyDependencyData.type, dummyDependencyData.properties, dummyDependencyData.measurements }, PartA_flags = this.dummyPartAFlagsValue, }.GetType()); return((item) => { if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords)) { item.Sanitize(); var telemetryItem = item as DependencyTelemetry; var data = telemetryItem.InternalData; var extendedData = new { // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod PartA_iKey = telemetryItem.Context.InstrumentationKey, PartA_Tags = telemetryItem.Context.SanitizedTags, PartB_RemoteDependencyData = new { data.ver, data.name, data.id, data.resultCode, data.duration, data.success, data.data, data.target, data.type, data.properties, data.measurements }, PartA_flags = telemetryItem.Context.Flags, }; writeMethod.Invoke(eventSource, new object[] { DependencyTelemetry.TelemetryName, eventSourceOptions, extendedData }); } }); }
private void HandleSSEConnect(EventSource eventSource) { Debug.Log("Successfully connected to " + eventSource); }
private MethodInfo GetMethodFromSchema(EventSource source, EventSchema schema) { return(source.GetType().GetMethods(Bindings).SingleOrDefault(m => this.IsEvent(m, schema.Id)) ?? source.GetType().GetMethod(schema.TaskName, Bindings)); }
public void Deconstruct(out EventSource mask, out Delegate originalHandler, out EventHandler handler) { mask = Mask; originalHandler = Original; handler = Handler; }
/// <summary> /// Create handler for performance counter telemetry. /// </summary> private Action <ITelemetry> CreateHandlerForPerformanceCounterTelemetry(EventSource eventSource, MethodInfo writeGenericMethod, Type eventSourceOptionsType, PropertyInfo eventSourceOptionsKeywordsProperty) { var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType); var keywords = Keywords.Metrics; eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords); var dummyMetricData = new MetricData(); var dummyDataPoint = new DataPoint(); var writeMethod = writeGenericMethod.MakeGenericMethod(new { PartA_iKey = this.dummyPartAiKeyValue, PartA_Tags = this.dummyPartATagsValue, PartB_MetricData = new { // The properties and layout should be the same as MetricData_types.cs dummyMetricData.ver, metrics = new[] { new { // The properties and layout should be the same as DataPoint_types.cs dummyDataPoint.ns, dummyDataPoint.name, dummyDataPoint.kind, dummyDataPoint.value, dummyDataPoint.count, dummyDataPoint.min, dummyDataPoint.max, dummyDataPoint.stdDev } }.AsEnumerable(), dummyMetricData.properties }, PartA_flags = this.dummyPartAFlagsValue, }.GetType()); return((item) => { if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords)) { item.Sanitize(); #pragma warning disable 618 var telemetryItem = (item as PerformanceCounterTelemetry).Data; #pragma warning restore 618 var data = telemetryItem.Data; var extendedData = new { // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod PartA_iKey = telemetryItem.Context.InstrumentationKey, PartA_Tags = telemetryItem.Context.SanitizedTags, PartB_MetricData = new { data.ver, metrics = data.metrics.Select(i => new { i.ns, i.name, i.kind, i.value, i.count, i.min, i.max, i.stdDev }), data.properties }, PartA_flags = telemetryItem.Context.Flags, }; writeMethod.Invoke(eventSource, new object[] { MetricTelemetry.TelemetryName, eventSourceOptions, extendedData }); } }); }
public EventSource SaveEventSource(EventSource es) { es.Event.AddEventSource(es); es.Source.AddEventSource(es); return(this.eventSourceRepo.SaveOrUpdate(es)); }
private ICollection <EventSchema> GetEventSchemas(EventSource eventSource) { try { string manifest = EventSource.GenerateManifest(eventSource.GetType(), null); this.CheckForBadFormedManifest(manifest); return(new EventSourceSchemaReader().GetSchema(manifest).Values); } catch (EventSourceAnalyzerException) { throw; } catch (Exception e) { throw new EventSourceAnalyzerException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.EventSourceAnalyzerManifestGenerationError, e.Message, EventSource.GenerateManifest(eventSource.GetType(), null))); } }
/// <summary> /// Create handler for request telemetry. /// </summary> private Action <ITelemetry> CreateHandlerForRequestTelemetry(EventSource eventSource, MethodInfo writeGenericMethod, Type eventSourceOptionsType, PropertyInfo eventSourceOptionsKeywordsProperty) { var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType); var keywords = Keywords.Requests; eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords); var dummyRequestData = new RequestData(); var writeMethod = writeGenericMethod.MakeGenericMethod(new { PartA_iKey = this.dummyPartAiKeyValue, PartA_Tags = this.dummyPartATagsValue, PartB_RequestData = new { // The properties and layout should be the same as RequestData_types.cs dummyRequestData.ver, dummyRequestData.id, dummyRequestData.source, dummyRequestData.name, dummyRequestData.duration, dummyRequestData.responseCode, dummyRequestData.success, dummyRequestData.url, dummyRequestData.properties, dummyRequestData.measurements, }, PartA_flags = this.dummyPartAFlagsValue, }.GetType()); return((item) => { if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords)) { var telemetryItem = item as RequestTelemetry; // This check avoids accessing the public accessor GlobalProperties // unless needed, to avoid the penality of ConcurrentDictionary instantiation. if (item.Context.GlobalPropertiesValue != null) { Utils.CopyDictionary(item.Context.GlobalProperties, telemetryItem.Properties); } item.Sanitize(); // Sanitize, Copying global properties is to be done before calling .Data here, // as Data returns a singleton instance, which won't be updated with changes made // after .Data is called. var data = telemetryItem.Data; var extendedData = new { // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod PartA_iKey = telemetryItem.Context.InstrumentationKey, PartA_Tags = telemetryItem.Context.SanitizedTags, PartB_RequestData = new { data.ver, data.id, data.source, data.name, data.duration, data.responseCode, data.success, data.url, data.properties, data.measurements, }, PartA_flags = telemetryItem.Context.Flags, }; writeMethod.Invoke(eventSource, new object[] { RequestTelemetry.TelemetryName, eventSourceOptions, extendedData }); } }); }
/// <summary> /// Create handler for unknown telemetry that accepts EventData, InstrumentationKey, tags, flags. /// </summary> private Action <EventData, string, IDictionary <string, string>, long> CreateHandlerForUnknownTelemetry(EventSource eventSource) { var eventSourceType = eventSource.GetType(); // EventSource.Write<T> (String, EventSourceOptions, T) var writeGenericMethod = eventSourceType.GetMethods(BindingFlags.Instance | BindingFlags.Public) .Where(m => m.Name == "Write" && m.IsGenericMethod == true) .Select(m => new { Method = m, Parameters = m.GetParameters() }) .Where(m => m.Parameters.Length == 3 && m.Parameters[0].ParameterType.FullName == "System.String" && m.Parameters[1].ParameterType.FullName == "System.Diagnostics.Tracing.EventSourceOptions" && m.Parameters[2].ParameterType.FullName == null && m.Parameters[2].ParameterType.IsByRef == false) .Select(m => m.Method) .SingleOrDefault(); if (writeGenericMethod == null) { return(null); } var eventSourceOptionsType = eventSourceType.Assembly.GetType("System.Diagnostics.Tracing.EventSourceOptions"); var eventSourceOptionsKeywordsProperty = eventSourceOptionsType.GetProperty("Keywords", BindingFlags.Public | BindingFlags.Instance); var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType); var keywords = Keywords.Events; eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords); var dummyEventData = new EventData(); var writeMethod = writeGenericMethod.MakeGenericMethod(new { PartA_iKey = this.dummyPartAiKeyValue, PartA_Tags = this.dummyPartATagsValue, PartB_EventData = new { // The properties and layout should be the same as EventData_types.cs dummyEventData.ver, dummyEventData.name, dummyEventData.properties, dummyEventData.measurements, }, PartA_flags = this.dummyPartAFlagsValue, }.GetType()); return((data, iKey, tags, flags) => { if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords)) { var extendedData = new { // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod PartA_iKey = iKey, PartA_Tags = tags, PartB_EventData = new { data.ver, data.name, data.properties, data.measurements, }, PartA_flags = flags, }; writeMethod.Invoke(eventSource, new object[] { EventTelemetry.EtwEnvelopeName, eventSourceOptions, extendedData }); } }); }
private void OnEventSourceOpen(EventSource eventSource) { HTTPManager.Logger.Information("Transport - " + this.Name, "OnEventSourceOpen"); }
/// <summary> /// Initializes a new instance of the <see cref="EventModel"/> class from Google event. /// </summary> /// <param name="gmailEvent">Google event.</param> public EventModel(Google.Apis.Calendar.v3.Data.Event gmailEvent) { source = EventSource.Google; gmailEventData = gmailEvent; }
private void AddSubscriber(EventSource source, string name, Action func) { WeakSubscriptionManager.Subscribe(source, name, new Subscriber(func)); }
/// <summary> /// Te /// </summary> /// <param name="listener"></param> private void Test_Write_T(Listener listener) { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var logger = new EventSource("EventSourceName")) { var tests = new List <SubTest>(); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/String", delegate() { logger.Write("Greeting", new { msg = "Hello, world!" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Greeting", evt.EventName); Assert.Equal(evt.PayloadValue(0, "msg"), "Hello, world!"); })); /*************************************************************************/ decimal myMoney = 300; tests.Add(new SubTest("Write/Basic/decimal", delegate() { logger.Write("Decimal", new { money = myMoney }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Decimal", evt.EventName); var eventMoney = evt.PayloadValue(0, "money"); // TOD FIX ME - Fix TraceEvent to return decimal instead of double. //Assert.Equal((decimal)eventMoney, (decimal)300); })); /*************************************************************************/ DateTime now = DateTime.Now; tests.Add(new SubTest("Write/Basic/DateTime", delegate() { logger.Write("DateTime", new { nowTime = now }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("DateTime", evt.EventName); var eventNow = evt.PayloadValue(0, "nowTime"); Assert.Equal(eventNow, now); })); /*************************************************************************/ byte[] byteArray = { 0, 1, 2, 3 }; tests.Add(new SubTest("Write/Basic/byte[]", delegate() { logger.Write("Bytes", new { bytes = byteArray }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Bytes", evt.EventName); var eventArray = evt.PayloadValue(0, "bytes"); Array.Equals(eventArray, byteArray); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBOnly", delegate() { // log just a PartB logger.Write("UserInfo", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "******" } }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("UserInfo", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Someone Else"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Basic/PartBAndC", delegate() { // log a PartB and a PartC logger.Write("Duration", new EventSourceOptions { Keywords = EventKeywords.None }, new { _1 = new PartB_UserInfo { UserName = "******" }, msec = 10 }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("Duration", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Myself"); Assert.Equal(evt.PayloadValue(1, "msec"), 10); })); /*************************************************************************/ /*************************** ENUM TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateEnumTest <Color>(ref tests, logger, Color.Green); GenerateEnumTest <ColorUInt32>(ref tests, logger, ColorUInt32.Green); GenerateEnumTest <ColorByte>(ref tests, logger, ColorByte.Green); GenerateEnumTest <ColorSByte>(ref tests, logger, ColorSByte.Green); GenerateEnumTest <ColorInt16>(ref tests, logger, ColorInt16.Green); GenerateEnumTest <ColorUInt16>(ref tests, logger, ColorUInt16.Green); GenerateEnumTest <ColorInt64>(ref tests, logger, ColorInt64.Green); GenerateEnumTest <ColorUInt64>(ref tests, logger, ColorUInt64.Green); /*************************************************************************/ /*************************** ARRAY TESTING *******************************/ /*************************************************************************/ /*************************************************************************/ GenerateArrayTest <Boolean>(ref tests, logger, new Boolean[] { false, true, false }); GenerateArrayTest <byte>(ref tests, logger, new byte[] { 1, 10, 100 }); GenerateArrayTest <sbyte>(ref tests, logger, new sbyte[] { 1, 10, 100 }); GenerateArrayTest <Int16>(ref tests, logger, new Int16[] { 1, 10, 100 }); GenerateArrayTest <UInt16>(ref tests, logger, new UInt16[] { 1, 10, 100 }); GenerateArrayTest <Int32>(ref tests, logger, new Int32[] { 1, 10, 100 }); GenerateArrayTest <UInt32>(ref tests, logger, new UInt32[] { 1, 10, 100 }); GenerateArrayTest <Int64>(ref tests, logger, new Int64[] { 1, 10, 100 }); GenerateArrayTest <UInt64>(ref tests, logger, new UInt64[] { 1, 10, 100 }); GenerateArrayTest <Char>(ref tests, logger, new Char[] { 'a', 'c', 'b' }); GenerateArrayTest <Double>(ref tests, logger, new Double[] { 1, 10, 100 }); GenerateArrayTest <Single>(ref tests, logger, new Single[] { 1, 10, 100 }); GenerateArrayTest <IntPtr>(ref tests, logger, new IntPtr[] { (IntPtr)1, (IntPtr)10, (IntPtr)100 }); GenerateArrayTest <UIntPtr>(ref tests, logger, new UIntPtr[] { (UIntPtr)1, (UIntPtr)10, (UIntPtr)100 }); GenerateArrayTest <Guid>(ref tests, logger, new Guid[] { Guid.Empty, new Guid("121a11ee-3bcb-49cc-b425-f4906fb14f72") }); /*************************************************************************/ /*********************** DICTIONARY TESTING ******************************/ /*************************************************************************/ var dict = new Dictionary <string, string>() { { "elem1", "10" }, { "elem2", "20" } }; var dictInt = new Dictionary <string, int>() { { "elem1", 10 }, { "elem2", 20 } }; /*************************************************************************/ #if false // TODO: enable when dictionary events are working again. GitHub issue #4867. tests.Add(new SubTest("Write/Dict/EventWithStringDict_C", delegate() { // log a dictionary logger.Write("EventWithStringDict_C", new { myDict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_C", evt.EventName); var keyValues = evt.PayloadValue(0, "myDict"); IDictionary <string, object> vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.Equal(vDict["elem1"], "10"); Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(1, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithStringDict_BC", delegate() { // log a PartB and a dictionary as a PartC logger.Write("EventWithStringDict_BC", new { PartB_UserInfo = new { UserName = "******", LogTime = "Now" }, PartC_Dict = dict, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithStringDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(dict); Assert.Equal(vDict["elem1"], "10"); // string values. Assert.Equal(vDict["elem2"], "20"); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); /*************************************************************************/ tests.Add(new SubTest("Write/Dict/EventWithIntDict_BC", delegate() { // log a Dict<string, int> as a PartC logger.Write("EventWithIntDict_BC", new { PartB_UserInfo = new { UserName = "******", LogTime = "Now" }, PartC_Dict = dictInt, s = "end" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EventWithIntDict_BC", evt.EventName); var structValue = evt.PayloadValue(0, "PartB_UserInfo"); var structValueAsDictionary = structValue as IDictionary <string, object>; Assert.NotNull(structValueAsDictionary); Assert.Equal(structValueAsDictionary["UserName"], "Me"); Assert.Equal(structValueAsDictionary["LogTime"], "Now"); var keyValues = evt.PayloadValue(1, "PartC_Dict"); var vDict = GetDictionaryFromKeyValueArray(keyValues); Assert.NotNull(vDict); Assert.Equal(vDict["elem1"], 10); // Notice they are integers, not strings. Assert.Equal(vDict["elem2"], 20); Assert.Equal(evt.PayloadValue(2, "s"), "end"); })); #endif // false /*************************************************************************/ /**************************** Empty Event TESTING ************************/ /*************************************************************************/ tests.Add(new SubTest("Write/Basic/Message", delegate() { logger.Write("EmptyEvent"); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); /*************************************************************************/ /**************************** EventSourceOptions TESTING *****************/ /*************************************************************************/ EventSourceOptions options = new EventSourceOptions(); options.Level = EventLevel.LogAlways; options.Keywords = EventKeywords.All; options.Opcode = EventOpcode.Info; options.Tags = EventTags.None; tests.Add(new SubTest("Write/Basic/MessageOptions", delegate() { logger.Write("EmptyEvent", options); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("EmptyEvent", evt.EventName); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate() { logger.Write("OptionsEvent", options, new { OptionsEvent = "test options!" }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("OptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithRefOptios", delegate() { var v = new { OptionsEvent = "test ref options!" }; logger.Write("RefOptionsEvent", ref options, ref v); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("RefOptionsEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "OptionsEvent"), "test ref options!"); })); tests.Add(new SubTest("Write/Basic/WriteOfTWithNullString", delegate() { string nullString = null; logger.Write("NullStringEvent", new { a = (string)null, b = nullString }); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("NullStringEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "a"), ""); Assert.Equal(evt.PayloadValue(1, "b"), ""); })); Guid activityId = new Guid("00000000-0000-0000-0000-000000000001"); Guid relActivityId = new Guid("00000000-0000-0000-0000-000000000002"); tests.Add(new SubTest("Write/Basic/WriteOfTWithOptios", delegate() { var v = new { ActivityMsg = "test activity!" }; logger.Write("ActivityEvent", ref options, ref activityId, ref relActivityId, ref v); }, delegate(Event evt) { Assert.Equal(logger.Name, evt.ProviderName); Assert.Equal("ActivityEvent", evt.EventName); Assert.Equal(evt.PayloadValue(0, "ActivityMsg"), "test activity!"); })); // If you only wish to run one or several of the tests you can filter them here by // Uncommenting the following line. // tests = tests.FindAll(test => Regex.IsMatch(test.Name, "Write/Basic/EventII")); // Here is where we actually run tests. First test the ETW path EventTestHarness.RunTests(tests, listener, logger); } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
/// <summary> /// Gets the schema for the specified event source. /// </summary> /// <param name="eventSource">The event source.</param> /// <returns>The event schema.</returns> public IDictionary <int, EventSchema> GetSchema(EventSource eventSource) { Guard.ArgumentNotNull(eventSource, "eventSource"); return(this.GetSchema(EventSource.GenerateManifest(eventSource.GetType(), null))); }
public CalendarService(ICalendarService calendarAPI, EventSource source) { this.calendarAPI = calendarAPI ?? throw new Exception("calendarAPI is null"); }
private void HandleSSEError(EventSource eventSource, string error) { Debug.Log("Error: " + error); }
/// <summary> /// Initializes the telemetry module and starts tracing EventSources specified via <see cref="Sources"/> property. /// </summary> /// <param name="configuration">Module configuration.</param> public void Initialize(TelemetryConfiguration configuration) { if (configuration == null) { throw new ArgumentNullException(nameof(configuration)); } this.client = new TelemetryClient(configuration); this.client.Context.GetInternalContext().SdkVersion = SdkVersionUtils.GetSdkVersion("evl:"); if (this.Sources.Count == 0) { EventSourceListenerEventSource.Log.NoSourcesConfigured(nameof(EventSourceListener.EventSourceTelemetryModule)); // Continue--we need to be prepared for handling disabled sources. } try { if (this.initialized) { // Source listening requests might have changed between initializations. Let's start from a clean slate EventSource enabledEventSource = null; while (this.enabledEventSources.TryDequeue(out enabledEventSource)) { this.DisableEvents(enabledEventSource); } } // Special case: because of .NET bug https://github.com/dotnet/coreclr/issues/14434, using Microsoft-ApplicationInsights-Data will result in infinite loop. // So we will disable it by default, unless there is explicit configuration for this EventSource. bool hasExplicitConfigForAiDataSource = this.Sources.Any(req => req.Name?.StartsWith(AppInsightsDataEventSource, StringComparison.Ordinal) ?? false) || this.DisabledSources.Any(req => req.Name?.StartsWith(AppInsightsDataEventSource, StringComparison.Ordinal) ?? false); if (!hasExplicitConfigForAiDataSource) { this.DisabledSources.Add(new DisableEventSourceRequest { Name = AppInsightsDataEventSource }); } // Set the initialized flag now to ensure that we do not miss any sources that came online as we are executing the initialization // (OnEventSourceCreated() might have been called on a separate thread). Worst case we will attempt to enable the same source twice // (with same settings), but that is OK, as the semantics of EnableEvents() is really "update what is being tracked", so it is fine // to call it multiple times for the same source. this.initialized = true; if (this.appDomainEventSources != null) { // Decide if there is disable event source listening requests if (this.DisabledSources.Any()) { this.enabledOrDisabledEventSourceTestResultCache = new ConcurrentDictionary <string, bool>(); this.eventWrittenHandlerPicker = this.OnEventWrittenIfSourceNotDisabled; } else { this.eventWrittenHandlerPicker = this.onEventWrittenHandler; } // Enumeration over concurrent queue is thread-safe. foreach (EventSource eventSourceToEnable in this.appDomainEventSources) { this.EnableAsNecessary(eventSourceToEnable); } } } finally { // No matter what problems we encounter with enabling EventSources, we should note that we have been initialized. this.initialized = true; } }
/// <summary> /// Create handlers for all AI telemetry types. /// </summary> private Dictionary <Type, Action <ITelemetry> > CreateTelemetryHandlers(EventSource eventSource) { var telemetryHandlers = new Dictionary <Type, Action <ITelemetry> >(); var eventSourceType = eventSource.GetType(); // EventSource.Write<T> (String, EventSourceOptions, T) var writeGenericMethod = eventSourceType.GetMethods(BindingFlags.Instance | BindingFlags.Public) .Where(m => m.Name == "Write" && m.IsGenericMethod == true) .Select(m => new { Method = m, Parameters = m.GetParameters() }) .Where(m => m.Parameters.Length == 3 && m.Parameters[0].ParameterType.FullName == "System.String" && m.Parameters[1].ParameterType.FullName == "System.Diagnostics.Tracing.EventSourceOptions" && m.Parameters[2].ParameterType.FullName == null && m.Parameters[2].ParameterType.IsByRef == false) .Select(m => m.Method) .SingleOrDefault(); if (writeGenericMethod != null) { var eventSourceOptionsType = eventSourceType.Assembly.GetType("System.Diagnostics.Tracing.EventSourceOptions"); var eventSourceOptionsKeywordsProperty = eventSourceOptionsType.GetProperty("Keywords", BindingFlags.Public | BindingFlags.Instance); // Request telemetryHandlers.Add(typeof(RequestTelemetry), this.CreateHandlerForRequestTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // Trace telemetryHandlers.Add(typeof(TraceTelemetry), this.CreateHandlerForTraceTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // Event telemetryHandlers.Add(typeof(EventTelemetry), this.CreateHandlerForEventTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // Dependency telemetryHandlers.Add(typeof(DependencyTelemetry), this.CreateHandlerForDependencyTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // Metric telemetryHandlers.Add(typeof(MetricTelemetry), this.CreateHandlerForMetricTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // Exception telemetryHandlers.Add(typeof(ExceptionTelemetry), this.CreateHandlerForExceptionTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); #pragma warning disable 618 // PerformanceCounter telemetryHandlers.Add(typeof(PerformanceCounterTelemetry), this.CreateHandlerForPerformanceCounterTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); #pragma warning restore 618 // PageView telemetryHandlers.Add(typeof(PageViewTelemetry), this.CreateHandlerForPageViewTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); // PageView telemetryHandlers.Add(typeof(PageViewPerformanceTelemetry), this.CreateHandlerForPageViewPerformanceTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); #pragma warning disable 618 // SessionState telemetryHandlers.Add(typeof(SessionStateTelemetry), this.CreateHandlerForSessionStateTelemetry(eventSource, writeGenericMethod, eventSourceOptionsType, eventSourceOptionsKeywordsProperty)); #pragma warning restore 618 } else { CoreEventSource.Log.LogVerbose("Unable to get method: EventSource.Write<T>(String, EventSourceOptions, T)"); } return(telemetryHandlers); }
internal ActorIdChanged(EventSource readerBackendType, uint actorId) : base(readerBackendType) { EventType = GetType(); ActorId = actorId; }
/// <summary> /// Create handler for exception telemetry. /// </summary> private Action <ITelemetry> CreateHandlerForExceptionTelemetry(EventSource eventSource, MethodInfo writeGenericMethod, Type eventSourceOptionsType, PropertyInfo eventSourceOptionsKeywordsProperty) { var eventSourceOptions = Activator.CreateInstance(eventSourceOptionsType); var keywords = Keywords.Exceptions; eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptions, keywords); var dummyExceptionData = new ExceptionData(); var dummyExceptionDetails = new ExceptionDetails(); var dummyStackFrame = new External.StackFrame(); var writeMethod = writeGenericMethod.MakeGenericMethod(new { PartA_iKey = this.dummyPartAiKeyValue, PartA_Tags = this.dummyPartATagsValue, PartB_ExceptionData = new { // The properties and layout should be the same as ExceptionData_types.cs dummyExceptionData.ver, exceptions = new[] { new { // The properties and layout should be the same as ExceptionDetails_types.cs dummyExceptionDetails.id, dummyExceptionDetails.outerId, dummyExceptionDetails.typeName, dummyExceptionDetails.message, dummyExceptionDetails.hasFullStack, dummyExceptionDetails.stack, parsedStack = new[] { new { // The properties and layout should be the same as StackFrame_types.cs dummyStackFrame.level, dummyStackFrame.method, dummyStackFrame.assembly, dummyStackFrame.fileName, dummyStackFrame.line } }.AsEnumerable() } }.AsEnumerable(), dummyExceptionData.severityLevel, dummyExceptionData.problemId, dummyExceptionData.properties, dummyExceptionData.measurements, }, PartA_flags = this.dummyPartAFlagsValue, }.GetType()); return((item) => { if (this.EventSourceInternal.IsEnabled(EventLevel.Verbose, keywords)) { item.Sanitize(); var telemetryItem = item as ExceptionTelemetry; var data = telemetryItem.Data.Data; var extendedData = new { // The properties and layout should be the same as the anonymous type in the above MakeGenericMethod PartA_iKey = telemetryItem.Context.InstrumentationKey, PartA_Tags = telemetryItem.Context.SanitizedTags, PartB_ExceptionData = new { data.ver, exceptions = data.exceptions.Select(i => new { i.id, i.outerId, i.typeName, i.message, i.hasFullStack, i.stack, parsedStack = i.parsedStack.Select(j => new { j.level, j.method, j.assembly, j.fileName, j.line }), }), data.severityLevel, data.problemId, data.properties, data.measurements }, PartA_flags = telemetryItem.Context.Flags, }; writeMethod.Invoke(eventSource, new object[] { ExceptionTelemetry.TelemetryName, eventSourceOptions, extendedData }); } }); }
/// <summary> /// Main Processing routine. /// </summary> public override void Process() { bool stillProcessing = ProcessUidList(); if (CancelPending) { Proxy.Cancel(); return; } if (StopPending) { Proxy.Idle(); return; } if (!stillProcessing) { bool failed = false; bool complete = true; bool filesMissing = false; foreach (WorkItemUid sop in WorkQueueUidList) { if (sop.Failed) { //If any items failed simply because the file doesn't exist, then fail outright. if (!File.Exists(GetFilePath(sop))) { filesMissing = true; } failed = true; break; } if (!sop.Complete) { complete = false; break; } } DateTime now = Platform.Time; if (failed) { var failureType = filesMissing ? WorkItemFailureType.Fatal : WorkItemFailureType.NonFatal; Proxy.Fail(failureType); if (Proxy.Item.Status == WorkItemStatusEnum.Failed) { var auditedInstances = new AuditedInstances(); auditedInstances.AddInstance(Request.Patient.PatientId, Request.Patient.PatientsName, Request.Study.StudyInstanceUid); AuditHelper.LogImportStudies(auditedInstances, string.IsNullOrEmpty(Request.UserName) ? EventSource.CurrentProcess : EventSource.GetUserEventSource(Request.UserName), EventResult.MajorFailure); } } else if (!complete) { Proxy.Idle(); } else if (now > Proxy.Item.ExpirationTime) { if (Study == null) { Study = LoadRelatedStudy(); } var ruleOptions = new RulesEngineOptions { ApplyDeleteActions = true, ApplyRouteActions = true }; RulesEngine.Create().ApplyStudyRules(Study.ToStoreEntry(), ruleOptions); Proxy.Complete(); var auditedInstances = new AuditedInstances(); auditedInstances.AddInstance(Request.Patient.PatientId, Request.Patient.PatientsName, Request.Study.StudyInstanceUid); AuditHelper.LogImportStudies(auditedInstances, string.IsNullOrEmpty(Request.UserName) ? EventSource.CurrentProcess : EventSource.GetUserEventSource(Request.UserName), EventResult.Success); } else { Proxy.Idle(); } } else { Proxy.Idle(); } }
/// <summary> /// Create a handler for <see cref="ProcessOperationStart(OperationTelemetry)"/> and <see cref="ProcessOperationStop(OperationTelemetry)"/> /// </summary> private Action <OperationTelemetry, EventOpcode> CreateOperationStartStopHandler(EventSource eventSource) { var eventSourceType = eventSource.GetType(); // EventSource.Write<T> (String, EventSourceOptions, T) var writeGenericMethod = eventSourceType.GetMethods(BindingFlags.Instance | BindingFlags.Public) .Where(m => m.Name == "Write" && m.IsGenericMethod == true) .Select(m => new { Method = m, Parameters = m.GetParameters() }) .Where(m => m.Parameters.Length == 3 && m.Parameters[0].ParameterType.FullName == "System.String" && m.Parameters[1].ParameterType.FullName == "System.Diagnostics.Tracing.EventSourceOptions" && m.Parameters[2].ParameterType.FullName == null && m.Parameters[2].ParameterType.IsByRef == false) .Select(m => m.Method) .SingleOrDefault(); if (writeGenericMethod == null) { return(null); } var eventSourceOptionsType = eventSourceType.Assembly.GetType("System.Diagnostics.Tracing.EventSourceOptions"); var eventSourceOptionsActivityOptionsProperty = eventSourceOptionsType.GetProperty("ActivityOptions", BindingFlags.Public | BindingFlags.Instance); var eventSourceOptionsKeywordsProperty = eventSourceOptionsType.GetProperty("Keywords", BindingFlags.Public | BindingFlags.Instance); var eventSourceOptionsOpcodeProperty = eventSourceOptionsType.GetProperty("Opcode", BindingFlags.Public | BindingFlags.Instance); var eventSourceOptionsLevelProperty = eventSourceOptionsType.GetProperty("Level", BindingFlags.Public | BindingFlags.Instance); var eventActivityOptionsType = eventSourceType.Assembly.GetType("System.Diagnostics.Tracing.EventActivityOptions"); var eventActivityOptionsRecursive = Enum.Parse(eventActivityOptionsType, "Recursive"); var eventSourceOptionsStart = Activator.CreateInstance(eventSourceOptionsType); eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptionsStart, Keywords.Operations); eventSourceOptionsOpcodeProperty.SetValue(eventSourceOptionsStart, EventOpcode.Start); eventSourceOptionsLevelProperty.SetValue(eventSourceOptionsStart, EventLevel.Informational); var eventSourceOptionsStop = Activator.CreateInstance(eventSourceOptionsType); eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptionsStop, Keywords.Operations); eventSourceOptionsOpcodeProperty.SetValue(eventSourceOptionsStop, EventOpcode.Stop); eventSourceOptionsLevelProperty.SetValue(eventSourceOptionsStop, EventLevel.Informational); var eventSourceOptionsStartRecursive = Activator.CreateInstance(eventSourceOptionsType); eventSourceOptionsActivityOptionsProperty.SetValue(eventSourceOptionsStartRecursive, eventActivityOptionsRecursive); eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptionsStartRecursive, Keywords.Operations); eventSourceOptionsOpcodeProperty.SetValue(eventSourceOptionsStartRecursive, EventOpcode.Start); eventSourceOptionsLevelProperty.SetValue(eventSourceOptionsStartRecursive, EventLevel.Informational); var eventSourceOptionsStopRecursive = Activator.CreateInstance(eventSourceOptionsType); eventSourceOptionsActivityOptionsProperty.SetValue(eventSourceOptionsStartRecursive, eventActivityOptionsRecursive); eventSourceOptionsKeywordsProperty.SetValue(eventSourceOptionsStopRecursive, Keywords.Operations); eventSourceOptionsOpcodeProperty.SetValue(eventSourceOptionsStopRecursive, EventOpcode.Stop); eventSourceOptionsLevelProperty.SetValue(eventSourceOptionsStopRecursive, EventLevel.Informational); var writeMethod = writeGenericMethod.MakeGenericMethod(new { IKey = (string)null, Id = (string)null, Name = (string)null, RootId = (string)null }.GetType()); return((item, opCode) => { bool isRequest = item is RequestTelemetry; object eventSourceOptionsObject; switch (opCode) { case EventOpcode.Start: eventSourceOptionsObject = isRequest ? eventSourceOptionsStart : eventSourceOptionsStartRecursive; break; case EventOpcode.Stop: eventSourceOptionsObject = isRequest ? eventSourceOptionsStop : eventSourceOptionsStopRecursive; break; default: throw new ArgumentException(nameof(opCode)); } var extendedData = new { IKey = item.Context.InstrumentationKey, Id = item.Id, Name = item.Name, RootId = item.Context.Operation.Id }; var parameters = new object[] { isRequest?RequestTelemetry.TelemetryName : OperationTelemetry.TelemetryName, eventSourceOptionsObject, extendedData }; writeMethod.Invoke(this.EventSourceInternal, parameters); }); }
internal PlayerNameChanged(EventSource readerBackendType, string playerName) : base(readerBackendType) { EventType = GetType(); PlayerName = playerName; }
protected override void OnEventSourceCreated(EventSource eventSource) { EnableEvents(eventSource, EventLevel.LogAlways, EventKeywords.All); }
public void Test_WriteEvent_ArgsBasicTypes() { TestUtilities.CheckNoEventSourcesRunning("Start"); using (var log = new EventSourceTest()) { using (var el = new LoudListener(log)) { var sources = EventSource.GetSources(); Assert.True(sources.Contains(log)); Assert.NotNull(EventSource.GenerateManifest(typeof(SimpleEventSource), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); Assert.Null(EventSource.GenerateManifest(typeof(EventSourceTest), string.Empty, EventManifestOptions.OnlyIfNeededForRegistration)); log.Event0(); Assert.Equal(1, LoudListener.t_lastEvent.EventId); Assert.Equal(0, LoudListener.t_lastEvent.Payload.Count); #region Validate "int" arguments log.EventI(10); Assert.Equal(2, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); log.EventII(10, 11); Assert.Equal(3, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventIII(10, 11, 12); Assert.Equal(4, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (int)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "long" arguments log.EventL(10); Assert.Equal(5, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); log.EventLL(10, 11); Assert.Equal(6, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventLLL(10, 11, 12); Assert.Equal(7, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(10, (long)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (long)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate "string" arguments log.EventS("10"); Assert.Equal(8, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); log.EventSS("10", "11"); Assert.Equal(9, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); log.EventSSS("10", "11", "12"); Assert.Equal(10, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal("11", (string)LoudListener.t_lastEvent.Payload[1]); Assert.Equal("12", (string)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate byte array arguments byte[] arr = new byte[20]; log.EventWithByteArray(arr); Assert.Equal(52, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(arr.Length, ((byte[])LoudListener.t_lastEvent.Payload[0]).Length); #endregion #region Validate mixed type arguments log.EventSI("10", 11); Assert.Equal(11, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); log.EventSL("10", 11); Assert.Equal(12, LoudListener.t_lastEvent.EventId); Assert.Equal(2, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (long)LoudListener.t_lastEvent.Payload[1]); log.EventSII("10", 11, 12); Assert.Equal(13, LoudListener.t_lastEvent.EventId); Assert.Equal(3, LoudListener.t_lastEvent.Payload.Count); Assert.Equal("10", (string)LoudListener.t_lastEvent.Payload[0]); Assert.Equal(11, (int)LoudListener.t_lastEvent.Payload[1]); Assert.Equal(12, (int)LoudListener.t_lastEvent.Payload[2]); #endregion #region Validate enums/flags log.EventEnum(MyColor.Blue); Assert.Equal(19, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Blue, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventEnum1(MyColor.Green); Assert.Equal(20, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyColor.Green, (MyColor)LoudListener.t_lastEvent.Payload[0]); log.EventFlags(MyFlags.Flag1); Assert.Equal(21, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); log.EventFlags1(MyFlags.Flag1); Assert.Equal(22, LoudListener.t_lastEvent.EventId); Assert.Equal(1, LoudListener.t_lastEvent.Payload.Count); Assert.Equal(MyFlags.Flag1, (MyFlags)LoudListener.t_lastEvent.Payload[0]); #endregion #if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864. #region Validate DateTime DateTime now = DateTime.Now; log.EventDateTime(now); Assert.Equal(24, LoudListener.LastEvent.EventId); Assert.Equal(1, LoudListener.LastEvent.Payload.Count); Assert.Equal((DateTime)LoudListener.LastEvent.Payload[0], now); #endregion #endif // USE_ETW } } TestUtilities.CheckNoEventSourcesRunning("Stop"); }
public IWeakEventListener SubscribeToPrivateClassEvent(EventSource source) { return(WeakEventListener <EventListener, EventSource, ViewModelClosedEventArgs> .SubscribeToWeakGenericEvent(this, source, "PublicEvent", OnPrivateClassEvent)); }
public void Test_GenerateManifest_InvalidEventSources() { TestUtilities.CheckNoEventSourcesRunning("Start"); // specify AllowEventSourceOverride - this is needed for Sdt event sources and won't make a difference for Sdt ones var strictOptions = EventManifestOptions.Strict | EventManifestOptions.AllowEventSourceOverride; Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty)); Exception e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.UnsealedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_TypeMustBeSealedOrAbstract"), e); // starting with NuGet we allow non-void returning methods as long as they have the [Event] attribute Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty)); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, strictOptions)); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithReturnEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.NegativeEventIdEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_NeedPositiveId", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.OutOfRangeKwdEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalKeywordsValue", "Kwd1", "0x100000000000"), GetResourceString("EventSource_KeywordCollision", "Session3", "Kwd1", "0x100000000000")), e); #if FEATURE_ADVANCED_MANAGED_ETW_CHANNELS e = AssertExtensions.Throws <ArgumentException>(GetResourceString("EventSource_MaxChannelExceeded"), () => EventSource.GenerateManifest(typeof(Sdt.TooManyChannelsEventSource), string.Empty)); #endif if (PlatformDetection.IsWindows) { e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithAdminChannelNoMessageEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventWithAdminChannelMustHaveMessage", "WriteInteger", "Admin"), e); } e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3), GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ReservedOpcodeEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_IllegalOpcodeValue", "Op1", 3), GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EnumKindMismatch", "Op1", "EventKeywords", "Opcodes"), GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EnumKindMismatchEventSource), string.Empty, EventManifestOptions.AllowEventSourceOverride)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_UndefinedKeyword", "0x1", "WriteInteger"), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty)); // These tests require the IL to be present for inspection. e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.MismatchIdEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_MismatchIdToWriteEvent", "WriteInteger", 10, 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"), GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventIdReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_EventIdReused", "WriteInteger2", 1, "WriteInteger1"), GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 1, "WriteInteger1", 1)), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventNameReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventNameReused", "WriteInteger"), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.TaskOpcodePairReusedEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_TaskOpcodePairReused", "WriteInteger2", 2, "WriteInteger1", 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithOpcodeNoTaskEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustHaveTaskIfNonDefaultOpcode", "WriteInteger", 1), e); Assert.NotNull(EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty)); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.EventWithInvalidMessageEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_UnsupportedMessageProperty", "WriteString", "Message = {0,12:G}"), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithKwdTaskOpcodeEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => string.Join(Environment.NewLine, GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Keywords"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Tasks"), GetResourceString("EventSource_AbstractMustNotDeclareKTOC", "Opcodes")), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.AbstractWithEventsEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_AbstractMustNotDeclareEventMethods", "WriteInteger", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e); e = AssertExtensions.Throws <ArgumentException>(null, () => EventSource.GenerateManifest(typeof(Sdt.ImplementsInterfaceEventSource), string.Empty, strictOptions)); AsserExceptionStringsEqual(() => GetResourceString("EventSource_EventMustNotBeExplicitImplementation", "SdtEventSources.ILogging.Error", 1), e); TestUtilities.CheckNoEventSourcesRunning("Stop"); }