示例#1
0
        public void TestEveryTypeWithDefaultConstructor()
        {
            var types = LoadAllTypes();

            var sut = new ObjectToContextCollectionConverter();

            foreach (var type in types)
            {
                if (type.IsAbstract || type.IsGenericType)
                {
                    continue;
                }
                if (type.Namespace == "System.Threading.Tasks.Task")
                {
                    continue;
                }

                var constructor = type.GetConstructor(new Type[0]);
                if (constructor != null)
                {
                    try
                    {
                        var e = Activator.CreateInstance(type, null);
                        var t = sut.Convert(e);
                    }
                    catch { }
                }
            }
        }
示例#2
0
        public ContextCollectionDTO Collect(IErrorReporterContext context)
        {
            if (!(context is NServiceBusContext ctx))
            {
                return(null);
            }

            if (ctx.Body != null)
            {
                var converter  = new ObjectToContextCollectionConverter();
                var properties = converter.ConvertToDictionary("Body", ctx.Body);
                properties.Add("MessageType", ctx.Body.GetType().FullName);
                return(new ContextCollectionDTO(Name, properties));
            }

            var body  = ctx.RawBody?.Length < 50000 ? string.Join(", ", ctx.RawBody) : "[Too large message]";
            var props = new Dictionary <string, string> {
                { "Bytes", body }
            };

            if (ctx.MessageType != null)
            {
                props.Add("MessageType", ctx.MessageType.FullName);
            }
            return(new ContextCollectionDTO(Name, props));
        }
示例#3
0
        public void should_be_able_to_serialize_all_types_of_exceptions()
        {
            string[] ignoredExceptions = new string[]
            {
                /*"UpaException", "EventLogException", "EventLogNotFoundException", "PrivilegeNotHeldException",
                 * "ContractExceptionUnknown", "ContractExceptionUnknown"*/
            };


            var sut = new ObjectToContextCollectionConverter();

            var inner          = new Exception("hello");
            var exceptionTypes =
                AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(assembly => assembly.GetTypes().Where(y => typeof(Exception).IsAssignableFrom(y)));

            foreach (var exceptionType in exceptionTypes)
            {
                if (exceptionType.Namespace == null)
                {
                    continue;
                }
                if (exceptionType.Namespace.StartsWith("Xunit") || ignoredExceptions.Contains(exceptionType.Name))
                {
                    continue;
                }

                var constructor = exceptionType.GetConstructor(new[] { typeof(string), typeof(Exception) });
                if (constructor != null)
                {
                    Exception thrownException = null;
                    try
                    {
                        TestOne(() =>
                        {
                            thrownException = (Exception)Activator.CreateInstance(exceptionType, new object[] { "Hello world", inner });
                            throw thrownException;
                        });
                    }
                    catch (Exception ex)
                    {
                        var item = sut.Convert(ex);
                        if (item.Properties.ContainsKey("Error"))
                        {
                            Console.WriteLine(ex.GetType().FullName + ": " + item.Properties["Error"]);
                        }
                        else if (item.Properties["Message"] != thrownException.Message)
                        {
                            Console.WriteLine(exceptionType.FullName + ": Failed to check " + item.Properties["Message"]);
                            throw new AssertException("Failed to serialize message for " + thrownException);
                        }
                    }
                }
                else
                {
                    Console.WriteLine(exceptionType + ": Unknown constructor ");
                }
            }
        }
示例#4
0
        /// <summary>
        ///     Report exception through codeRR
        /// </summary>
        /// <param name="controller">controller used to report exception (used to be able to collect context data)</param>
        /// <param name="exception">exception to report</param>
        /// <param name="contextData">extra context data</param>
        /// <returns>sent report (can be used for instance for <c>Err.LeaveFeedback</c>)</returns>
        public static ErrorReportDTO ReportException(this ControllerBase controller, Exception exception,
                                                     object contextData)
        {
            var converter  = new ObjectToContextCollectionConverter();
            var collection = converter.Convert(contextData);

            return(CoderrFilter.Invoke(controller, controller.ControllerContext, exception, new[] { collection }));
        }
        /// <summary>
        ///     Report exception through codeRR
        /// </summary>
        /// <param name="httpContext">httpContext used to report exception (used to be able to collect context data)</param>
        /// <param name="exception">exception to report</param>
        /// <param name="contextData">extra context data</param>
        /// <returns>sent report (can be used for instance for <c>Err.LeaveFeedback</c>)</returns>
        public static ErrorReportDTO ReportException(this HttpContextBase httpContext, Exception exception,
                                                     object contextData)
        {
            var converter  = new ObjectToContextCollectionConverter();
            var collection = converter.Convert(contextData);

            return(ErrorHttpModule.ExecutePipeline(httpContext, exception, httpContext, collection));
        }
        /// <summary>
        ///     Called when an exception occurs.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnException(ExceptionContext filterContext)
        {
            var converter = new ObjectToContextCollectionConverter();

            var items = new List <ContextCollectionDTO>
            {
                converter.Convert("IsChildAction", filterContext.IsChildAction),
                new ContextCollectionDTO("Controller",
                                         new Dictionary <string, string> {
                    { "FullName", filterContext.Controller.GetType().FullName }
                })
            };

            if (filterContext.HttpContext != null)
            {
                //gave no meaningful keys and a lot of built in stored objects. Filter those out in the future.
                //if (filterContext.HttpContext.Items != null && filterContext.HttpContext.Items.Count > 0)
                //    items.Add(converter.Convert("HttpContext.Items", filterContext.HttpContext.Items));
                if (filterContext.HttpContext.Application != null && filterContext.HttpContext.Application.Count > 0)
                {
                    items.Add(converter.Convert("HttpContext.Application", filterContext.HttpContext.Application));
                }
            }

            if (filterContext.Controller != null)
            {
                if (filterContext.Controller.TempData != null && filterContext.Controller.TempData.Count > 0)
                {
                    items.Add(converter.Convert("TempData", filterContext.Controller.TempData));
                }
                if (filterContext.Controller.ViewBag != null)
                {
                    items.Add(converter.Convert("ViewBag", filterContext.Controller.ViewBag));
                }
                if (filterContext.Controller.ViewData != null && filterContext.Controller.ViewData.Count > 0)
                {
                    items.Add(converter.Convert("ViewData", filterContext.Controller.ViewData));
                }
            }

            if (filterContext.ParentActionViewContext != null)
            {
                items.Add(converter.Convert("ParentActionViewContext", filterContext.ParentActionViewContext));
            }
            if (filterContext.Result != null && !(filterContext.Result is EmptyResult))
            {
                items.Add(converter.Convert("Result", filterContext.Result));
            }
            if (filterContext.RouteData != null)
            {
                items.Add(converter.Convert("RouteData", filterContext.RouteData));
            }

            ErrorHttpModule.ExecutePipeline(this, filterContext.Exception, filterContext.HttpContext, items.ToArray());

            filterContext.ExceptionHandled = true;
            filterContext.Result           = null;
        }
        public void validation_exception_from_dataAnnotations_is_special_so_make_Sure_That_it_can_Be_serialized()
        {
            var ex = new ValidationException("Hello world");

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(ex);

            actual.Properties["Message"].Should().Be("Hello world");
        }
示例#8
0
        /// <summary>
        ///     Collect information
        /// </summary>
        /// <param name="context"></param>
        /// <returns>Collection</returns>
        public ContextCollectionDTO Collect(IErrorReporterContext context)
        {
            if (HttpContext.Current.Session == null || HttpContext.Current.Session.Count == 0)
            {
                return(null);
            }

            var converter = new ObjectToContextCollectionConverter();

            return(converter.Convert("HttpSession", HttpContext.Current.Session));
        }
        public void should_be_able_to_convert_an_ienumerableKeyValuePair_as_a_dictionary()
        {
            var obj = new CustomDictionary();

            obj.Dictionary["Ada"] = "Lovelace";

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(obj);

            actual.Properties["[0].Key"].Should().Be("Ada");
            actual.Properties["[0].Value"].Should().Be("Lovelace");
        }
示例#10
0
        public void Should_be_able_to_convert_an_ienumerableKeyValuePair_as_a_dictionary_when_being_inner_object()
        {
            var obj = new CustomDictionary();

            obj.Dictionary["Ada"] = "Lovelace";

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(new { brainiac = obj });

            actual.Properties["brainiac[0].Key"].Should().Be("Ada");
            actual.Properties["brainiac[0].Value"].Should().Be("Lovelace");
        }
示例#11
0
 public void MEdiaPortalArgumentException()
 {
     try
     {
         TestOne(() => { throw new ArgumentNullException("pluginRuntime"); });
     }
     catch (Exception ex)
     {
         var sut  = new ObjectToContextCollectionConverter();
         var item = sut.Convert(ex);
     }
 }
        public void should_be_able_To_convert_dictionaries_using_the_key_as_index()
        {
            var obj = new Dictionary <object, string> {
                { "ada", "hello" }, { 1, "world" }
            };

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(obj);

            actual.Properties["ada"].Should().Be("hello");
            actual.Properties["1"].Should().Be("world");
        }
示例#13
0
        /// <inheritdoc />
        public ContextCollectionDTO Collect(IErrorReporterContext context)
        {
            var aspNetContext = context as AspNetMvcContext;

            if (aspNetContext?.TempData == null || aspNetContext.TempData.Count == 0)
            {
                return(null);
            }

            var converter = new ObjectToContextCollectionConverter();

            return(converter.Convert(Name, aspNetContext.TempData));
        }
示例#14
0
        /// <summary>
        ///     Converts simple objects into context collections
        /// </summary>
        /// <param name="instance">Object to convert</param>
        /// <param name="name">Name to assign to the context collection</param>
        /// <returns>Context information</returns>
        /// <remarks>
        ///     Anonymous types get the collection name "CustomData" while any other class get the class name as collection name.
        /// </remarks>
        public static ContextCollectionDTO ToContextCollection(this object instance, string name)
        {
            if (instance == null)
            {
                throw new ArgumentNullException("instance");
            }

            var converter = new ObjectToContextCollectionConverter
            {
                MaxPropertyCount = Err.Configuration.MaxNumberOfPropertiesPerCollection
            };

            return(converter.Convert(name, instance));
        }
示例#15
0
        public void Should_be_able_to_process_type_with_circular_reference()
        {
            var obj = new GotParentReference {
                Child = new GotParentReferenceChild {
                    Title = "chld"
                }, Name = "prnt"
            };

            obj.Child.Parent = obj;

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(obj);

            actual.Properties.ContainsKey("Child.Parent._error").Should().BeTrue();
        }
示例#16
0
        public void Should_be_able_to_convert_a_dynamic_object()
        {
            var item = new
            {
                Amount  = 20000,
                Expires = DateTime.UtcNow.AddMinutes(5)
            };


            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(item);

            actual.Properties["Amount"].Should().Be("20000");
            actual.Properties["Expires"].Should().StartWith(DateTime.UtcNow.Year.ToString());
        }
示例#17
0
        /// <inheritdoc />
        public ContextCollectionDTO Collect(IErrorReporterContext context)
        {
            var aspNetContext = context as AspNetMvcContext;

            if (aspNetContext?.ViewBag == null)
            {
                return(null);
            }

            var converter  = new ObjectToContextCollectionConverter();
            var collection = converter.Convert(Name, aspNetContext.ViewBag);

            //not beatiful, but we do not want to reflect the object twice
            return(collection.Properties.Count == 0 ? null : collection);
        }
        public void should_be_able_to_handle_nested_inner_exceptions()
        {
            var ex1 = new ArgumentNullException("moot");

            ex1.Data["aa"] = "World";
            var ex2 = new ArgumentException("Ex2", "SomeProperty", ex1);
            var ex3 = new Exception("Ex3", ex2);

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(ex3);

            actual.Properties["Message"].Should().Be("Ex3");
            actual.Properties["InnerException.Message"].Should().Contain("Ex2");
            actual.Properties["InnerException.ParamName"].Should().Be("SomeProperty");
            actual.GetProperty("InnerException.InnerException.Message").Should().Contain("moot");
        }
示例#19
0
        public void Should_be_able_to_convert_a_dictionary_with_a_dynamic_object_as_an_item()
        {
            var item = new
            {
                Amount  = 20000,
                Expires = DateTime.UtcNow.AddMinutes(5)
            };
            var dict = new Dictionary <string, object> {
                ["DemoKey"] = item
            };

            var sut    = new ObjectToContextCollectionConverter();
            var actual = sut.Convert(dict);

            actual.Properties["DemoKey.Amount"].Should().Be("20000");
            actual.Properties["DemoKey.Expires"].Should().StartWith(DateTime.UtcNow.Year.ToString());
        }
示例#20
0
        /// <summary>
        ///     Called when an exception occurs.
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public void OnException(ExceptionContext filterContext)
        {
            var converter = new ObjectToContextCollectionConverter();

            var items = new List <ContextCollectionDTO>();

            if (filterContext.Result != null && !(filterContext.Result is EmptyResult))
            {
                items.Add(converter.Convert("Result", filterContext.Result));
            }

            Invoke(this, filterContext.Controller.ControllerContext, filterContext.Exception, items);

            if (ErrorHttpModule.DisplayErrorPage)
            {
                filterContext.ExceptionHandled = true;
                filterContext.Result           = null;
            }
        }
示例#21
0
 /// <summary>
 ///     Collect information
 /// </summary>
 /// <param name="context">Context information provided by the class which reported the error.</param>
 /// <returns>
 ///     Collection. Items with multiple values are joined using <c>";;"</c>
 /// </returns>
 public ContextCollectionDTO Collect(IErrorReporterContext context)
 {
     try
     {
         var converter = new ObjectToContextCollectionConverter
         {
             MaxPropertyCount = Err.Configuration.MaxNumberOfPropertiesPerCollection
         };
         var collection = converter.Convert(context.Exception);
         collection.Name = "ExceptionProperties";
         return(collection);
     }
     catch (Exception ex)
     {
         var context2 = new ContextCollectionDTO("ExceptionProperties");
         context2.Properties.Add("ExceptionProperties.Error", ex.ToString());
         return(context2);
     }
 }
示例#22
0
        public void TestEveryTypeWithDefaultConstructor()
        {
            var sut = new ObjectToContextCollectionConverter();

            var inner = new Exception("hello");
            var types =
                AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(assembly => assembly.GetTypes());

            foreach (var type in types)
            {
                if (type.IsAbstract || type.IsGenericType)
                {
                    continue;
                }
                if (type.Namespace == "System.Threading.Tasks.Task")
                {
                    continue;
                }

                var constructor = type.GetConstructor(new Type[0]);
                if (constructor != null)
                {
                    try
                    {
                        var e = Activator.CreateInstance(type, null);

                        //contains temporal coupling
                        if (type == typeof(PartialTrustRunnerAttribute))
                        {
                            continue;
                        }

                        var t = sut.Convert(e);
                        Console.WriteLine(t);
                    }
                    catch { }
                }
            }
        }
示例#23
0
 public OneTrueCollector()
 {
     _converter = new ObjectToContextCollectionConverter();
     Items      = new List <ContextCollectionDTO>();
 }
示例#24
0
        internal static ErrorReportDTO Invoke(object source, ControllerContext filterContext, Exception exception,
                                              IEnumerable <ContextCollectionDTO> extras)
        {
            var context = new AspNetMvcContext(source, exception, filterContext.HttpContext);


            var converter = new ObjectToContextCollectionConverter();

            var items = new List <ContextCollectionDTO>(extras)
            {
                converter.Convert("IsChildAction", filterContext.IsChildAction),
                new ContextCollectionDTO("Controller",
                                         new Dictionary <string, string> {
                    { "FullName", filterContext.Controller.GetType().FullName }
                })
            };

            if (filterContext.Controller == null && source is ControllerBase)
            {
                filterContext.Controller = (ControllerBase)source;
            }

            if (filterContext.Controller != null)
            {
                context.Controller = filterContext.Controller;

                if (filterContext.Controller.TempData != null && filterContext.Controller.TempData.Count > 0)
                {
                    context.TempData = filterContext.Controller.TempData;
                }

                if (filterContext.Controller.ViewBag != null)
                {
                    context.ViewBag = filterContext.Controller.ViewBag;
                }

                if (filterContext.Controller.ViewData != null && filterContext.Controller.ViewData.Count > 0)
                {
                    context.ViewData = filterContext.Controller.ViewData;

                    if (filterContext.Controller.ViewData.ModelState != null)
                    {
                        context.ModelState = filterContext.Controller.ViewData.ModelState;
                    }
                }

                context.Model = filterContext.Controller?.ViewData?.Model;
            }


            if (filterContext.ParentActionViewContext != null)
            {
                items.Add(converter.Convert("ParentActionViewContext", filterContext.ParentActionViewContext));
            }

            if (filterContext.RouteData != null)
            {
                context.RouteData = filterContext.RouteData;
            }

            return(ErrorHttpModule.ExecutePipeline(context, items.ToArray()));
        }