jonwagner / EventSourceProxy

EventSourceProxy (ESP) is the easiest way to add scalable Event Tracing for Windows (ETW) logging to your .NET program
Other
97 stars 20 forks source link

Validating String-Format against Method-Parameters #37

Closed Danielku15 closed 9 years ago

Danielku15 commented 9 years ago

The EventSourceProxy has the pattern that it passes all method parameters as String-Format Parameters to the EventSource.

It would be very useful if there would be a validator that checks if the String-Format Arguments match the Method Parameters.

public interface IMyLog {
    [Event(0x01, Message = "Invalid: {0}, {1}, {2}")]
    void Sample(string a, string b);
}

Using the Sample Event will fail because it has an invalid {2} Format argument. The default EventSourceAnalyzer does not handle this cases. It would be great to have an EventSourceProxy Unit-Test-Class which handles this.

EDIT: I added this little code to my unit test. But it would be nice to have it (in a more clean fashion) as part of the EventSourceProxy:

        private void InspectAll(EventSource eventSource)
        {
            var methods = eventSource.GetType().GetMethods(BindingFlags.Public | BindingFlags.Instance);
            foreach (var method in methods)
            {
                var attribute = method.GetCustomAttributes(typeof(EventAttribute), true).OfType<EventAttribute>().FirstOrDefault();
                if (attribute != null)
                {
                    ValidateLogMethod(method, attribute);
                }
            }
        }

        private void ValidateLogMethod(MethodInfo method, EventAttribute attribute)
        {
            var format = attribute.Message;
            ParameterInfo[] parameters = method.GetParameters();
            object[] defaultValues = parameters.Select(p => Default(p.ParameterType)).ToArray();
            try
            {
                string.Format(format, defaultValues);
            }
            catch (FormatException e)
            {
                Assert.Fail("Invalid string format in Log Method {0}\r\n {1}", method.Name, e);
            }
        }

        public static object Default(Type type)
        {
            if (type == typeof(string))
            {
                return string.Empty;
            }

            return Activator.CreateInstance(type);
        }
jonwagner commented 9 years ago

Nice. I'll add that to the code when it generates an interface.

jonwagner commented 9 years ago

This will be in the next build (hopefully this weekend)