Ejemplo n.º 1
0
        private static IEnumerable <MethodInfo> GetEventMethods(EventSource eventSource)
        {
#if WINRT || WINDOWS_UWP
            IEnumerable <MethodInfo> methods = eventSource.GetType().GetRuntimeMethods();
#else
            MethodInfo[] methods = eventSource.GetType().GetMethods();
#endif

            return(methods.Where(m => m.GetCustomAttributes(typeof(EventAttribute), false).Any()));
        }
Ejemplo n.º 2
0
            /// <summary>
            /// Parses the <see cref="EventSource"/> class and returns the <see cref="EventSourceInfo"/> object
            /// </summary>
            /// <param name="eventSource">Event source to be parsed</param>
            /// <param name="friendlyName">Friendly name of the event source</param>
            /// <returns>event source info</returns>
            public static EventSourceInfo Parse(EventSource eventSource, string friendlyName)
            {
                if (string.IsNullOrEmpty(friendlyName))
                {
                    friendlyName = eventSource.Name;
                }

                var info = new EventSourceInfo {
                    FriendlyName = friendlyName,
                };

                foreach (var method in eventSource.GetType().GetMethods())
                {
                    var eventAttribute = method.GetCustomAttribute <EventAttribute>();
                    if (eventAttribute == null)
                    {
                        continue;
                    }

                    var id         = eventAttribute.EventId;
                    var name       = method.Name;
                    var parameters = method.GetParameters().Select(p => p.Name).ToArray();

                    info.events.Add(id, Tuple.Create(name, parameters));
                }

                return(info);
            }
Ejemplo n.º 3
0
            public void DoesNotLeakWithActionsDefinedInDisplayClass()
            {
                var source = new EventSource();

                var counter = 0;

                Action action = () =>
                {
                    counter++;
                };

                var weakEventListener = WeakEventListener.SubscribeToWeakEvent(this, source, "PublicEvent", action);

                Assert.AreEqual(0, counter);

                source.RaisePublicEvent();

                Assert.AreEqual(1, counter);

                // Some dummy code to make sure the previous listener is removed
                GC.Collect();

                //Assert.IsTrue(weakEventListener.IsSourceAlive);
                //Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 4
0
        /// <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));

#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);
        }
Ejemplo n.º 5
0
        public EventSourceVersion GetLastCommittedVersion(EventSource eventSource, Guid eventSourceId)
        {
            var eventSourceParam = new OracleParameter(EventParameters.EVENTSOURCE, OracleDbType.NVarchar2, 512);

            eventSourceParam.Value = eventSource.GetType().AssemblyQualifiedName;

            var eventSourceIdParam = new OracleParameter(EventParameters.EVENTSOURCEID, OracleDbType.Raw, 16);

            eventSourceIdParam.Value = eventSourceId.ToByteArray();

            var version = EventSourceVersion.Zero;

            try
            {
                OpenConnection();
                using (var command = _connection.CreateCommand())
                {
                    command.CommandText = LAST_VERSION_STATEMENT;
                    command.Parameters.Add(eventSourceIdParam);
                    command.Parameters.Add(eventSourceParam);
                    command.BindByName = true;
                    var reader = command.ExecuteReader(CommandBehavior.SingleResult);
                    if (reader.Read())
                    {
                        version = EventSourceVersion.FromCombined(Convert.ToDouble(reader.GetDecimal(0)));
                    }
                }
            }
            finally
            {
                EnsureConnectionClosed(_connection);
            }

            return(version);
        }
 /// <summary>
 /// Enable receiving events
 /// </summary>
 protected override void OnEventSourceCreated(EventSource eventSource)
 {
     if (eventSource != null && eventSource.Name == SqlEventSourceName && eventSource.GetType().FullName == EventSourceTypeName)
     {
         EnableEvents(eventSource, EventLevel.Informational, (EventKeywords)1);
     }
     base.OnEventSourceCreated(eventSource);
 }
Ejemplo n.º 7
0
        private ICollection <EventSchema> GetEventSchemas(EventSource eventSource)
        {
            if (eventSource == null)
            {
                throw  new ArgumentNullException("eventSource");
            }

            try
            {
                var manifest = EventSource.GenerateManifest(
                    eventSource.GetType(),
                    Assembly.GetAssembly(eventSource.GetType()).Location
                    );
                this.CheckForBadFormedManifest(manifest);
                return(new EventSourceSchemaReader().GetSchema(manifest).Values);
            }
            catch (EventSourceAnalyzerException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (eventSource.ConstructionException != null)
                {
                    throw new EventSourceAnalyzerException(
                              e.Message,
                              eventSource.ConstructionException
                              );
                }

                throw new EventSourceAnalyzerException(
                          string.Format(
                              CultureInfo.CurrentCulture,
                              Resources.EventSourceAnalyzerManifestGenerationError,
                              e.Message,
                              EventSource.GenerateManifest(
                                  eventSource.GetType(),
                                  null
                                  )));
            }
        }
Ejemplo n.º 8
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var eventSourceType = eventSource.GetType();
            var query           = Query.And(
                Query.EQ("EventSourceId", eventSourceId),
                Query.EQ("EventSource", eventSourceType.AssemblyQualifiedName)
                );

            var cursor    = _collection.FindAs <BsonDocument>(query);
            var documents = cursor.ToArray();
            var events    = ToEvents(documents);
            var stream    = new CommittedEventStream(eventSourceId);

            stream.Append(events);
            return(stream);
        }
Ejemplo n.º 9
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            using (var session = _documentStore.OpenSession())
            {
                var eventSourceType = eventSource.GetType();

                var events = session.Query <IEvent>()
                             .Where(
                    e => e.EventSourceId == eventSourceId &&
                    e.EventSource == eventSourceType.AssemblyQualifiedName
                    ).ToArray();

                var stream = new CommittedEventStream(eventSourceId);
                stream.Append(events);
                return(stream);
            }
        }
Ejemplo n.º 10
0
 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, Resources.EventSourceAnalyzerManifestGenerationError, e.Message, EventSource.GenerateManifest(eventSource.GetType(), null)));
     }
 }
Ejemplo n.º 11
0
        public CommittedEventStream GetForEventSource(EventSource eventSource, Guid eventSourceId)
        {
            var committedEventStream = new CommittedEventStream(eventSourceId);

            var eventSourceParam = new OracleParameter(EventParameters.EVENTSOURCE, OracleDbType.NVarchar2, 512);

            eventSourceParam.Value = eventSource.GetType().AssemblyQualifiedName;

            var eventSourceIdParam = new OracleParameter(EventParameters.EVENTSOURCEID, OracleDbType.Raw, 16);

            eventSourceIdParam.Value = eventSourceId.ToByteArray();

            var eventDtos = new List <EventDto>();

            try
            {
                OpenConnection();
                using (var command = _connection.CreateCommand())
                {
                    command.CommandText = READ_STATEMENT_FOR_EVENTS_BY_AGGREGATE_ROOT;
                    command.Parameters.Add(eventSourceIdParam);
                    command.Parameters.Add(eventSourceParam);
                    command.BindByName = true;
                    var reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        eventDtos.Add(MapReaderToEventDto(reader));
                    }
                }
            }
            finally
            {
                EnsureConnectionClosed(_connection);
            }

            var retrievedEvents = eventDtos.Select(BuildEventInstanceFromDto)
                                  .Select(@event => _eventMigratorManager.Migrate(@event))
                                  .ToList();

            if (retrievedEvents.Any())
            {
                committedEventStream.Append(retrievedEvents);
            }

            return(committedEventStream);
        }
Ejemplo n.º 12
0
            public void DoesNotLeakWithoutAnyInvocation()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = WeakEventListener <EventListener, EventSource, ViewModelClosedEventArgs> .SubscribeToWeakGenericEvent(listener, source, "PublicEvent", listener.OnPublicEvent);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
 public static void Write(this EventSource log, int eventCode, object context)
 {
     try
     {
         var type   = context.GetType();
         var method =
             log.GetType().GetMethods().FirstOrDefault(x => x.GetCustomAttributes(typeof(EventAttribute), true).Any() && ((EventAttribute)x.GetCustomAttributes(typeof(EventAttribute), true).First()).EventId == eventCode);
         if (method != null)
         {
             var parameters = new List <object>();
             method.GetParameters().ToList().ForEach(value => parameters.Add(type.GetProperty(value.Name).GetValue(context)));
             method.Invoke(log, parameters.ToArray());
         }
     }
     catch (Exception)
     {
         //try log error
     }
 }
Ejemplo n.º 14
0
            public void DoesNotLeakWithStaticEventHandlers()
            {
                var source = new EventSource();

                var weakEventListener = WeakEventListener <EventListener, EventSource, ViewModelClosedEventArgs> .SubscribeToWeakGenericEvent(null, source, "PublicEvent", EventListener.OnEventStaticHandler);

                Assert.AreEqual(0, EventListener.StaticEventHandlerCounter);

                source.RaisePublicEvent();

                Assert.AreEqual(1, EventListener.StaticEventHandlerCounter);

                // Some dummy code to make sure the previous source is removed
                source = new EventSource();
                GC.Collect();
                var type = source.GetType();

                Assert.IsFalse(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);
            }
Ejemplo n.º 15
0
        /// <summary>
        /// Detaches this eventwrapper to be able to GC it later
        /// </summary>
        /// <param name="pathDetach">True if in middle path (just for debugging, doesnt matter which value is passed)</param>
        public void Detach(bool pathDetach = false)
        {
            if (PropertyFilter != null)
            {
                EventSource.PropertyChanged -= SourcePropertyChanged;
            }
            else
            {
                EventSource.PropertyChanged -= PathPropertyChanged;
            }
#if DEBUG
            if (pathDetach)
            {
                Debug.WriteLine("Path detach: " + EventSource.GetType().Name + ":" + EventSource.GetHashCode() + " from " + PropertyFilter);
            }
            else
            {
                Debug.WriteLine("Final detach: " + EventSource.GetType().Name + ":" + EventSource.GetHashCode());
            }
#endif
        }
Ejemplo n.º 16
0
        public EventSourceVersion GetLastCommittedVersion(EventSource eventSource, Guid eventSourceId)
        {
            var eventPath = GetPathFor(eventSource.GetType().Name, eventSourceId);
            var first     = Directory.GetFiles(eventPath).OrderByDescending(f => f).FirstOrDefault();

            if (first == null)
            {
                return(EventSourceVersion.Zero);
            }

            var json   = File.ReadAllText(first);
            var target = new EventHolder
            {
                Type    = typeof(string),
                Version = EventSourceVersion.Zero,
                Event   = string.Empty
            };

            _serializer.FromJson(target, json);

            return(target.Version);
        }
Ejemplo n.º 17
0
            public void DoesNotLeakWithPrivateEventHandlerSubscribedFromClassItself()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = listener.SubscribeToPrivateClassEvent(source);

                Assert.AreEqual(0, listener.PrivateClassEventCount);

                source.RaisePublicEvent();

                Assert.AreEqual(1, listener.PrivateClassEventCount);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 18
0
#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);
        }
Ejemplo n.º 19
0
            public void DoesNotLeakWithPropertyChangedEvent()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = WeakEventListener <EventListener, EventSource, PropertyChangedEventArgs> .SubscribeToWeakPropertyChangedEvent(listener, source, listener.OnPropertyChangedEvent, eventName : "PropertyChanged");

                Assert.AreEqual(0, listener.PropertyChangedEventCount);

                source.RaisePropertyChangedEvent();

                Assert.AreEqual(1, listener.PropertyChangedEventCount);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 20
0
            public void AutomaticallySubscribesToCollectionChangedWhenEventNameIsNotSpecified()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = WeakEventListener <EventListener, EventSource, NotifyCollectionChangedEventArgs> .SubscribeToWeakCollectionChangedEvent(listener, source, listener.OnCollectionChangedEvent);

                Assert.AreEqual(0, listener.CollectionChangedEventCount);

                source.RaiseCollectionChangedEvent();

                Assert.AreEqual(1, listener.CollectionChangedEventCount);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 21
0
            public void DoesNotLeakWithAutomaticDetectionOfAllTypesForCollectionChanged()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = listener.SubscribeToWeakCollectionChangedEvent(source, listener.OnCollectionChangedEvent);

                Assert.AreEqual(0, listener.CollectionChangedEventCount);

                source.RaiseCollectionChangedEvent();

                Assert.AreEqual(1, listener.CollectionChangedEventCount);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 22
0
            public void DoesNotLeakWithAutomaticDetectionOfAllTypes()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = listener.SubscribeToWeakGenericEvent <ViewModelClosedEventArgs>(source, "PublicEvent", listener.OnPublicEvent);

                Assert.AreEqual(0, listener.PublicEventCounter);

                source.RaisePublicEvent();

                Assert.AreEqual(1, listener.PublicEventCounter);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 23
0
#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;
        }
Ejemplo n.º 24
0
            public void DoesNotLeakWithPublicActions()
            {
                var source   = new EventSource();
                var listener = new EventListener();

                var weakEventListener = WeakEventListener.SubscribeToWeakEvent(listener, source, "PublicEvent", listener.OnPublicAction);

                Assert.AreEqual(0, listener.PublicActionCounter);

                source.RaisePublicEvent();

                Assert.AreEqual(1, listener.PublicActionCounter);

                // Some dummy code to make sure the previous listener is removed
                listener = new EventListener();
                GC.Collect();
                var type = listener.GetType();

                Assert.IsTrue(weakEventListener.IsSourceAlive);
                Assert.IsFalse(weakEventListener.IsTargetAlive);

                // Some dummy code to make sure the source stays in memory
                source.GetType();
            }
Ejemplo n.º 25
0
            private void SendManifestIfNecessary(EventSource eventSource)
            {
                var eventSourceIdx = EventSourceIndex(eventSource);

                if (m_sentManifest.Length <= eventSourceIdx)
                {
                    var newSentManifest = new bool[eventSourceIdx + 4];
                    Array.Copy(m_sentManifest, newSentManifest, m_sentManifest.Length);
                    m_sentManifest = newSentManifest;
                }

                if (m_sentManifest[eventSourceIdx])
                {
                    return;
                }

                m_sentManifest[eventSourceIdx] = true;

                // Get the manifest and send it.
                var manifestStr   = EventSource.GenerateManifest(eventSource.GetType(), eventSource.Name);
                var manifestBytes = System.Text.Encoding.UTF8.GetBytes(manifestStr);

                m_relogger.SendManifest(manifestBytes, eventSource);
            }
        private ICollection<EventSchema> GetEventSchemas(EventSource eventSource)
        {
            if(eventSource == null)
                throw  new ArgumentNullException("eventSource");

            try
            {
                var manifest = EventSource.GenerateManifest(
                    eventSource.GetType(),
                    Assembly.GetAssembly(eventSource.GetType()).Location
                    );
                this.CheckForBadFormedManifest(manifest);
                return new EventSourceSchemaReader().GetSchema(manifest).Values;
            }
            catch (EventSourceAnalyzerException)
            {
                throw;
            }
            catch (Exception e)
            {
                if (eventSource.ConstructionException != null)
                {
                    throw new EventSourceAnalyzerException(
                        e.Message,
                        eventSource.ConstructionException
                        );
                }

                throw new EventSourceAnalyzerException(
                    string.Format(
                        CultureInfo.CurrentCulture,
                        Resources.EventSourceAnalyzerManifestGenerationError,
                        e.Message,
                        EventSource.GenerateManifest(
                            eventSource.GetType(),
                            null
                            )));
            }
        }
Ejemplo n.º 27
0
 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));
 }
Ejemplo n.º 28
0
 protected override void OnEventSourceCreated(EventSource eventSource)
 {
     Console.WriteLine("OnEventSourceCreated: {0}", eventSource.GetType().FullName);
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Return the manifest of a provider for the given type.
        /// </summary>
        /// <param name="type">The provider type.</param>
        /// <returns>The XML manifest content.</returns>
        public static string GenerateManifest(Type type)
        {
            EventSource eventSource = EventSourceImplementer.GetEventSource(type);

            return(EventSource.GenerateManifest(eventSource.GetType(), Assembly.GetAssembly(type).Location));
        }
Ejemplo n.º 30
0
        /// <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.TelemetryName, eventSourceOptions, extendedData });
                }
            });
        }
Ejemplo n.º 31
0
        /// <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($"Unexpected EventOpcode: {opCode}. Expected: Start or Stop.", 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);
            });
        }
Ejemplo n.º 32
0
            /// <summary>
            /// ctor.
            /// </summary>
            /// <param name="source">EventSource object to instantiate from.</param>
            public EventSourceInfo(EventSource source)
            {
                this.Source = source;

                // DOM+XPath parsing for now, manifests should be very small and we shouldn't be doing this too frequently
                string manifestXML = EventSource.GenerateManifest(source.GetType(), "");
                var    manifest    = new XmlDocument();

                manifest.LoadXml(manifestXML);
                var        namespaceMgr = new XmlNamespaceManager(manifest.NameTable);
                XmlElement root         = manifest.DocumentElement; // instrumentationManifest

                namespaceMgr.AddNamespace("win", root.NamespaceURI);

                // keep track of event to template mapping (template name can differ from event name)
                var templateMapping = new Dictionary <string, EventInfo>(StringComparer.OrdinalIgnoreCase);

                // not verifying but we expect a single provider
                XmlNode provider = root.SelectSingleNode("//win:provider", namespaceMgr);

                this.Name = provider.Attributes["name"].Value;
                foreach (XmlNode ev in provider.SelectNodes("//win:events/win:event", namespaceMgr))
                {
                    // EventSource+TraceEvent provide for the following naming scheme:
                    // - Events with neither a task nor opcode will have a task generated for them automatically.
                    // - Events with named tasks and the default opcode have the name of the task. It is possible
                    //   as a result to have many events with the same name. We don't hedge against this today since
                    //   we key on ID.
                    // - Events with opcodes but not task names do not get generated task names, so we simply use
                    //   the event's ID as its name.

                    int eventID    = int.Parse(ev.Attributes["value"].Value);
                    var taskName   = ev.Attributes.GetNamedItem("task");
                    var opCodeName = ev.Attributes.GetNamedItem("opcode");

                    string eventName;
                    if (taskName != null && opCodeName != null)
                    {
                        int opCodeOffset = (opCodeName.Value.StartsWith("win:") ? 4 : 0);
                        eventName = string.Format("{0}/{1}", taskName.Value, opCodeName.Value.Substring(opCodeOffset));
                    }
                    else if (taskName != null)
                    {
                        eventName = taskName.Value;
                    }
                    else
                    {
                        eventName = eventID.ToString(CultureInfo.InvariantCulture);
                    }

                    var eventData = new EventInfo {
                        Name = eventName
                    };
                    this.eventIDs[eventID] = eventData;

                    if (ev.Attributes.GetNamedItem("template") != null)
                    {
                        templateMapping[ev.Attributes["template"].Value] = eventData;
                    }
                }

                // Each template has one or more 'data' tags whose attributes are the name of the argument and its
                // type. Since we only care about the name we ignore the type. For array arguments EventSource emits
                // two entries in the template, first a <foo>.Length entry specifying the length of the array,
                // followed by the actual array data itself (<foo>).  Since we're constructing this data only
                // for handling intra-application EventSource calls we don't need to care about the .Length
                // bit that comes in the manifest since it is specific to decoding ETW events.
                foreach (XmlNode template in provider.SelectNodes("//win:templates/win:template", namespaceMgr))
                {
                    string name = template.Attributes["tid"].Value;
                    // we want to throw right away if we somehow got a template for an unnamed event, that's a big
                    // contract breach.
                    EventInfo   data      = templateMapping[name];
                    XmlNodeList arguments = template.SelectNodes("win:data", namespaceMgr);

                    int numArgs = 0;
                    data.Arguments = new string[arguments.Count];
                    for (int i = 0; i < arguments.Count; ++i)
                    {
                        XmlNode node     = arguments[i];
                        string  dataName = node.Attributes["name"].Value;
                        if (!dataName.EndsWith(ArrayLengthArgumentSuffix, StringComparison.OrdinalIgnoreCase))
                        {
                            data.Arguments[numArgs] = dataName;
                            ++numArgs;
                        }
                    }
                }
            }
Ejemplo n.º 33
0
        public EventSourceVersion GetLastCommittedVersion(EventSource eventSource, Guid eventSourceId)
        {
            var eventPath = GetPathFor(eventSource.GetType().Name, eventSourceId);
            var first = Directory.GetFiles(eventPath).OrderByDescending(f => f).FirstOrDefault();
            if (first == null) return EventSourceVersion.Zero;

            var json = File.ReadAllText(first);
            var target = new EventHolder
            {
                Type = typeof(string),
                Version = EventSourceVersion.Zero,
                Event = string.Empty
            };

            _serializer.FromJson(target, json);

            return target.Version;
        }
        /// <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));
        }
 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)));
     }
 }
 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);
 }