public CoralModuleException(ReflectionTypeLoadException exception) : base(exception.Message, exception) { Exceptions = exception.LoaderExceptions; Message = Exceptions.Aggregate(exception.Message, (r, s) => r + s.Message); HResult = 10102; }
public void loadAssemblyFile(string file) { string item = environment.addBs(Path.GetDirectoryName(file)); if (environment.directories.IndexOf(item) < 0) { environment.directories.Add(item); } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); try { Assembly assembly = Assembly.LoadFile(file); this.fileAssemblies[assembly.FullName] = assembly; this.fileAssemblies[fileNameWithoutExtension] = assembly; this.@add(assembly); } catch (ReflectionTypeLoadException reflectionTypeLoadException) { ReflectionTypeLoadException ex = reflectionTypeLoadException; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Se encontró los siguientes errores al cargar el ensamblado:"); Exception[] loaderExceptions = ex.LoaderExceptions; for (int i = 0; i < (int)loaderExceptions.Length; i++) { stringBuilder.AppendLine(loaderExceptions[i].ToString()); } throw new Exception(stringBuilder.ToString()); } }
private static void LogAssemblyLoaderException(string reason, ReflectionTypeLoadException ex, ILogger logger) { var sb = new System.Text.StringBuilder(reason + ": "); sb.AppendLine(ex.ToString()); if (ex.LoaderExceptions != null) { sb.AppendFormat("LoaderExceptions ({0} items): ", ex.LoaderExceptions.Length); foreach (var loaderException in ex.LoaderExceptions) { sb.AppendLine(loaderException.Message); } } var message = sb.ToString(); if (logger != null) { logger.Error(message); } else { Console.WriteLine(message); } sb.Clear(); }
public void Exceptions_always_get_properties_formatters() { var exception = new ReflectionTypeLoadException( new[] { typeof(FileStyleUriParser), typeof(AssemblyKeyFileAttribute) }, new Exception[] { new EventLogInvalidDataException() }); var formatter = new FormatterSet(); var message = formatter.Format(exception); Assert.That(message, Contains.Substring("ReflectionTypeLoadException")); Assert.That(message, Contains.Substring("FileStyleUriParser")); Assert.That(message, Contains.Substring("AssemblyKeyFileAttribute")); Assert.That(message, Contains.Substring("EventLogInvalidDataException")); }
public static void AssemblyGetForwardedTypesLoadFailure() { Assembly a = typeof(TypeInForwardedAssembly).Assembly; ReflectionTypeLoadException rle = Assert.Throws <ReflectionTypeLoadException>(() => a.GetForwardedTypes()); Assert.Equal(2, rle.Types.Length); Assert.Equal(2, rle.LoaderExceptions.Length); bool foundSystemObject = false; bool foundBifException = false; for (int i = 0; i < rle.Types.Length; i++) { Type type = rle.Types[i]; Exception exception = rle.LoaderExceptions[i]; if (type == typeof(object) && exception == null) { foundSystemObject = true; } if (type == null && exception is BadImageFormatException) { foundBifException = true; } } Assert.True(foundSystemObject); Assert.True(foundBifException); }
public override string Check(int tenantId) { try { using (var service = new TextIndexServiceClient()) { return(service.CheckState() ? HealthCheckResource.FullTextIndexServiceWorksCorrectMsg : HealthCheckResource.FullTextIndexServiceWorksIncorrectMsg); } } catch (Exception ex) { log.ErrorFormat("TextIndexer is failed! {0}, innerException = {1}", ex, ex.InnerException != null ? ex.InnerException.Message : string.Empty); ReflectionTypeLoadException reflectionTypeLoadException = ex as ReflectionTypeLoadException; if (reflectionTypeLoadException != null) { foreach (var loaderException in reflectionTypeLoadException.LoaderExceptions) { log.ErrorFormat("loaderException = {0}", loaderException.ToString()); } } return(HealthCheckResource.FullTextIndexServiceWorksIncorrectMsg); } }
private void DisplayLoaderExceptionsOnConsole(ReflectionTypeLoadException e) { foreach (var loaderException in e.LoaderExceptions) { Console.WriteLine(loaderException.ToString()); } }
static void DescribeError(Exception ex, StringBuilder sb) { // Attempt to gather this info. Skip anything that you can't read for whatever reason try { sb.AppendLine("Type: " + ex.GetType().Name); } catch { } try { sb.AppendLine("Source: " + ex.Source); } catch { } try { sb.AppendLine("Message: " + ex.Message); } catch { } try { sb.AppendLine("Target: " + ex.TargetSite.Name); } catch { } try { sb.AppendLine("Trace: " + ex.StackTrace); } catch { } // For errors with loading plugins (e.g. missing dependancy) you get a // Message: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. // which is pretty useless by itself, so specifically handle this case try { ReflectionTypeLoadException refEx = ex as ReflectionTypeLoadException; if (refEx == null) { return; } sb.AppendLine("## Loader exceptions ##"); foreach (Exception loadEx in refEx.LoaderExceptions) { DescribeError(loadEx, sb); } } catch { } }
private static IList <Exception> GetInnerExceptions(Exception exception) { AggregateException ae = exception as AggregateException; if (ae != null) { return(ae.InnerExceptions); } ReflectionTypeLoadException rtle = exception as ReflectionTypeLoadException; if (rtle != null) { int index = 0; foreach (Exception e in rtle.LoaderExceptions) { try { e.Data["Type"] = rtle.Types[index]; } catch { } index++; } return(rtle.LoaderExceptions.ToList()); } return(null); }
static void AddReflectionTypeLoadExceptionDetails(ReflectionTypeLoadException rtle, StringBuilder sb) { if (rtle.LoaderExceptions == null) { return; } foreach (var loaderException in rtle.LoaderExceptions) { if (loaderException == null) { continue; } sb.AppendLine(); sb.AppendLine("--Loader Exception--"); PrettyPrint(sb, loaderException, true); #if !NETSTANDARD1_0 var fusionLog = (loaderException as FileNotFoundException)?.FusionLog; if (!string.IsNullOrEmpty(fusionLog)) { sb.Append("Fusion log: ").AppendLine(fusionLog); } #endif } }
static void DescribeError(Exception ex, StringBuilder sb) { // Attempt to gather this info. Skip anything that you can't read for whatever reason try { sb.AppendLine("Type: " + ex.GetType().Name); } catch { } try { sb.AppendLine("Source: " + ex.Source); } catch { } try { sb.AppendLine("Message: " + ex.Message); } catch { } try { sb.AppendLine("Trace: " + ex.StackTrace); } catch { } // Exception-specific extra details try { ReflectionTypeLoadException refEx = ex as ReflectionTypeLoadException; if (refEx != null) { LogLoaderErrors(refEx, sb); } } catch { } try { SocketException sockEx = ex as SocketException; if (sockEx != null) { LogSocketErrors(sockEx, sb); } } catch { } }
/// <summary> /// <B>True</B> is a type load failed, <B>false</B> if an assembly load failed. /// </summary> private static void LogLoadException(Exception e, bool typeLoad, string failedName) { string message; // extract LoaderExceptions if available ReflectionTypeLoadException rtle = e as ReflectionTypeLoadException; if (rtle != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < rtle.LoaderExceptions.Length; i++) { if (sb.Length > 0) { sb.Append(' '); } sb.Append(rtle.LoaderExceptions[i].Message); } message = sb.ToString(); } else { message = e.Message; } if (typeLoad) { ConsoleErrors.ERROR_UnableToLoadType.PrintTo(logPrinter, failedName, message); } else { ConsoleErrors.ERROR_UnableToLoadAssembly.PrintTo(logPrinter, failedName, message); } }
/// <summary> /// Effectue le rendu de l'exception /// </summary> /// <param name="ex">L'exception.</param> /// <param name="sb">Le StringBuilder sur lequel effectuer le rendu.</param> /// <param name="indentation">L'indentation.</param> private void RenderReflectionTypeLoadException(ReflectionTypeLoadException ex, StringBuilder sb, int indentation) { sb.Append(' ', indentation * 2); sb.Append(ex.GetType().FullName); sb.Append(": "); sb.Append(ex.Message); sb.Append(Environment.NewLine); sb.Append(' ', indentation * 2); sb.Append(ex.StackTrace); sb.Append(Environment.NewLine); sb.Append("LoaderExceptions:"); sb.Append(Environment.NewLine); foreach (var loaderEx in ex.LoaderExceptions) { var subLoaderEx = loaderEx as ReflectionTypeLoadException; if (subLoaderEx != null) { RenderReflectionTypeLoadException(subLoaderEx, sb, indentation + 1); } else { sb.Append(' ', (indentation + 1) * 2); sb.Append(loaderEx.ToString()); sb.Append(Environment.NewLine); } } sb.Append(Environment.NewLine); }
static string ReflectionTypeLoadExceptionDetails(ReflectionTypeLoadException exception) { var problems = new List <string>(); foreach (var subException in exception.LoaderExceptions) { var problem = subException.Message; if (subException is FileNotFoundException fileNotFoundException) { if (!string.IsNullOrEmpty(fileNotFoundException.FusionLog)) { problem += $"Fusion Log:{NewLine}{fileNotFoundException.FusionLog}"; } } problems.Add(problem); } var uniqueProblems = problems.Distinct(); if (uniqueProblems.Any()) { return($"Details from Loader exceptions:{NewLine}{string.Join(NewLine, uniqueProblems)}"); } else { return(""); } }
/// <summary> /// Gets all inner exceptions provided by the given exception object. /// </summary> /// <param name="ex">The exception to be analyzed.</param> public IEnumerable <Exception> GetInnerExceptions(Exception ex) { // Return default inenr exception yield return(ex.InnerException); // Query over all inner exceptions of an aggregate exception AggregateException aggregateException = ex as AggregateException; if (aggregateException != null) { foreach (Exception actInnerException in aggregateException.InnerExceptions) { yield return(actInnerException); } } // Query over all loader exceptions on a ReflectionTypeLoadException ReflectionTypeLoadException typeLoadException = ex as ReflectionTypeLoadException; if ((typeLoadException != null) && (typeLoadException.LoaderExceptions != null)) { foreach (Exception actInner in typeLoadException.LoaderExceptions) { yield return(actInner); } } }
/// <summary> /// Writes all ReflectionTypeLoadException exception content to Log /// </summary> /// <param name="ex"></param> /// <param name="log"></param> public static void LogLoaderExceptions(this ReflectionTypeLoadException ex, Action <Exception, Exception> log) { foreach (var le in ex.LoaderExceptions) { log(ex, le); } }
/// <summary> /// Processes a <see cref="ReflectionTypeLoadException"/> in order to makes sure /// type information is included and all <see cref="ReflectionTypeLoadException.LoaderExceptions"/> /// are recursively parsed. /// </summary> internal static void ProcessTypeLoadException(ExceptionData exceptionData, ReflectionTypeLoadException typeLoadException, StringBuilder builder, int indent) { AppendFormat(builder, indent, "ReflectionTypeLoadException (possibility: MEF composition error): {0}", typeLoadException.Message); builder.AppendLine(); Append(builder, indent, "- Types: "); IEnumerable <string> typeNames = typeLoadException.Types.Select(t => t == null ? "[null]" : t.Name); builder.AppendLine(String.Join(",", typeNames)); AppendLine(builder, indent, "- Loader exceptions:"); //keep that line above the if statement below, even if there were no Errors if (typeLoadException.LoaderExceptions != null) { foreach (Exception loaderException in typeLoadException.LoaderExceptions) { //the loader exceptions array may contain null references! if (loaderException == null) { continue; } //store hidden exception and recurse exceptionData.HiddenExceptions.Add(loaderException); Parse(exceptionData, loaderException, builder, indent + 1); } } }
private void WriteException(StreamWriter writer, Exception exception) { if (exception.Source != null && exception.Source.Length > 0) { writer.WriteLine("Exception Source:" + exception.Source); } writer.WriteLine("Exception Message:" + exception.Message); writer.WriteLine("Stack Trace:"); writer.WriteLine(exception.StackTrace); ReflectionTypeLoadException le = exception as ReflectionTypeLoadException; if (le != null) { foreach (Exception e2 in le.LoaderExceptions) { WriteException(writer, e2); } } if (exception.InnerException != null) { writer.WriteLine(); WriteException(writer, exception.InnerException); } }
static void UnhandledException(Exception exception) { Debug.WriteLine(exception.ToString()); for (Exception ex = exception; ex != null; ex = ex.InnerException) { ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; if (rtle != null && rtle.LoaderExceptions.Length > 0) { exception = rtle.LoaderExceptions[0]; Debug.WriteLine(exception.ToString()); break; } } if (showingError) { // Ignore re-entrant calls // We run the risk of opening an infinite number of exception dialogs. return; } showingError = true; try { MessageBox.Show(exception.ToString(), "Sorry, we crashed"); } finally { showingError = false; } }
public void AssemblyExtensions_TryGetTypes_GetTypesThrows_TwoLoaderExceptions_RethrowTrue() { // Arrange var types = new Type[] { typeof(string), typeof(int) }; var exception1 = new Exception("Message1"); var exception2 = new Exception("Message2"); var loaderExceptions = new[] { exception1, exception2 }; var reflectionTypeLoadException = new ReflectionTypeLoadException(types, loaderExceptions); _MockAssembly.Setup(m => m.GetTypes()).Throws(reflectionTypeLoadException); _MockPluginLoaderLogger.Setup(m => m.Log(exception1)); _MockPluginLoaderLogger.Setup(m => m.Log(exception2)); IAssembly assembly = _MockAssembly.Object; bool throwException = true; // Act // Assert Assert.ThrowsException <ReflectionTypeLoadException>(() => { assembly.TryGetTypes(throwException, _MockPluginLoaderLogger.Object); }); _MockRepository.VerifyAll(); }
/// <summary> /// Converts TypeLoadException to a readable string. /// </summary> /// <param name="ex">TypeLoadException</param> /// <returns>Readable representation of the exception</returns> public static string TypeLoadExceptionToString(ReflectionTypeLoadException ex) { var sb = new StringBuilder(); foreach (var exSub in ex.LoaderExceptions) { sb.AppendLine(exSub.Message); if (exSub is FileNotFoundException exFileNotFound) { if (!string.IsNullOrEmpty(exFileNotFound.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exFileNotFound.FusionLog); } } else if (exSub is FileLoadException exLoad) { if (!string.IsNullOrEmpty(exLoad.FusionLog)) { sb.AppendLine("Fusion Log:"); sb.AppendLine(exLoad.FusionLog); } } sb.AppendLine(); } return(sb.ToString()); }
public void AssemblyExtensions_TryGetTypes_GetTypesThrows_TwoLoaderExceptions() { // Arrange var types = new Type[] { typeof(string), typeof(int) }; var exception1 = new Exception("Message1"); var exception2 = new Exception("Message2"); var loaderExceptions = new[] { exception1, exception2 }; var reflectionTypeLoadException = new ReflectionTypeLoadException(types, loaderExceptions); _MockAssembly.Setup(m => m.GetTypes()).Throws(reflectionTypeLoadException); _MockPluginLoaderLogger.Setup(m => m.Log(exception1)); _MockPluginLoaderLogger.Setup(m => m.Log(exception2)); IAssembly assembly = _MockAssembly.Object; bool throwException = false; // Act var result = assembly.TryGetTypes(throwException, _MockPluginLoaderLogger.Object); // Assert CollectionAssert.AreEqual(types, result.ToArray()); _MockRepository.VerifyAll(); }
/// <summary> /// Standard implementation of <see cref="Assembly.GetExportedTypes()"/> /// with autorecovery and logging of common error conditions. /// </summary> /// <param name="assembly">The assembly whose exported types are needed</param> /// <param name="logger">Optional logger to use to report problems.</param> /// <returns>The collection of types. It may be empty but it will not be null.</returns> internal static IEnumerable <Type> GetExportedTypes(Assembly assembly, ILogger logger) { Type[] types = null; try { types = assembly.GetExportedTypes(); } catch (Exception ex) { if (ex.IsFatal()) { throw; } // Some common exceptions log a warning and return an empty collection if (ex is TypeLoadException || ex is FileNotFoundException || ex is FileLoadException || ex is BadImageFormatException) { // We log only if we have a logger and this is not MSCORLIB // MSCORLIB.GetExportedTypes will throw TypeLoadException when used // in a Reflection-Only load. Yet that is not fatal because the // real MSCORLIB is loaded and the user would be distracted by // any warnings of this nature. if (logger != null && !IsAssemblyMsCorlib(assembly.GetName())) { logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Assembly_Load_Type_Error, assembly.FullName, ex.Message)); } return(new Type[0]); } // This particular exception may have loaded at least some types. Capture what we can. ReflectionTypeLoadException rtle = ex as ReflectionTypeLoadException; if (rtle != null) { // They tell us the types they loaded -- but the array could have nulls where they failed types = rtle.Types; // Show a warning message so user knows we have an issue if (logger != null) { StringBuilder sb = new StringBuilder(); Exception[] loadExceptions = rtle.LoaderExceptions; foreach (Exception e in loadExceptions) { sb.AppendLine(e.Message); } logger.LogMessage(string.Format(CultureInfo.CurrentCulture, Resource.ClientCodeGen_Failed_To_Load, assembly.FullName, sb.ToString())); } // Return collection without nulls return(types.Where(t => t != null)); } // All other exceptions rethrow throw; } // Successful return return(types); }
/// <summary> /// Format a message with the whole exception list. /// </summary> /// <param name="e">Exception.</param> /// <returns>Exception message.</returns> public static string GetFullMessage(Exception e) { StringBuilder message = new StringBuilder(); for (Exception current = e; current != null; current = current.InnerException) { if (current is TargetInvocationException) { continue; } if (message.Length != 0) { message.Append("\r\n"); } message.Append(current.Message); ReflectionTypeLoadException typeLoadExecption = current as ReflectionTypeLoadException; if (typeLoadExecption != null) { foreach (Exception ex in typeLoadExecption.LoaderExceptions) { message.Append("\r\n"); message.Append(ex.Message); } } } return(message.ToString()); }
private static string GetReflectionTypeLoadExceptionMessage(ReflectionTypeLoadException exception) { StringBuilder builder = new StringBuilder(); // lookup table for duplicate messages List <string> messages = new List <string>(); builder.AppendLine(exception.Message); builder.AppendLine(Properties.Resources.LoaderExceptionMessages); foreach (Exception error in exception.LoaderExceptions) { if (!messages.Contains(error.Message)) { builder.AppendLine(error.Message); messages.Add(error.Message); } } builder.AppendLine(Properties.Resources.LoaderExceptionTypeMessages); foreach (Type type in exception.Types) { if (type != null && !messages.Contains(type.FullName)) { builder.AppendLine(type.FullName); messages.Add(type.FullName); } } return(builder.ToString()); }
private void LogLoaderExceptions(ReflectionTypeLoadException e) { foreach (var loaderException in e.LoaderExceptions) { this.EventLog.WriteEntry(loaderException.ToString(), EventLogEntryType.Error); } }
/// <summary> /// Print the exception to the console, including extended loading / reflection data useful for mods. /// </summary> public static void LogDetailed(this Exception e, string tag = null) { if (tag == null) { Console.WriteLine("--------------------------------"); Console.WriteLine("Detailed exception log:"); } for (Exception e_ = e; e_ != null; e_ = e_.InnerException) { Console.WriteLine("--------------------------------"); Console.WriteLine(e_.GetType().FullName + ": " + e_.Message + "\n" + e_.StackTrace); if (e_ is ReflectionTypeLoadException) { ReflectionTypeLoadException rtle = (ReflectionTypeLoadException)e_; for (int i = 0; i < rtle.Types.Length; i++) { Console.WriteLine("ReflectionTypeLoadException.Types[" + i + "]: " + rtle.Types[i]); } for (int i = 0; i < rtle.LoaderExceptions.Length; i++) { LogDetailed(rtle.LoaderExceptions[i], tag + (tag == null ? "" : ", ") + "rtle:" + i); } } if (e_ is TypeLoadException) { Console.WriteLine("TypeLoadException.TypeName: " + ((TypeLoadException)e_).TypeName); } if (e_ is BadImageFormatException) { Console.WriteLine("BadImageFormatException.FileName: " + ((BadImageFormatException)e_).FileName); } } }
/// <summary> /// Specialized formatter for <see cref="ReflectionTypeLoadException"/>. /// </summary> /// <param name="text">The <see cref="StringBuilder"/> that receives the text.</param> /// <param name="rtle">A reference to the specialized exception. Can be null.</param> private static void BuildReflectionTypeLoadExceptionText(StringBuilder text, ReflectionTypeLoadException rtle) { if (rtle != null) { if (rtle.LoaderExceptions != null) { foreach (Exception le in rtle.LoaderExceptions) { text.AppendLine("Loader Exception -----------------------"); BuildExceptionText(text, le); } } if (rtle.Types != null && rtle.Types.Length > 0) { text.AppendLine("Loaded Types ----------------------------"); foreach (Type loadedType in rtle.Types) { if (loadedType != null) { text.Append("\t"); text.AppendLine(loadedType.FullName); } } } } }
/// <summary> /// Formats load exception as multi-line string, each line contains load error message. /// </summary> /// <param name="ex">The exception.</param> /// <returns>Returns loader exceptions as a multi-line string.</returns> internal string GetLoadExceptionDetails(ReflectionTypeLoadException ex) { Debug.Assert(ex != null, "exception should not be null."); var map = new Dictionary <string, object>(StringComparer.OrdinalIgnoreCase); // Exception -> null. var errorDetails = new StringBuilder(); if (ex.LoaderExceptions != null) { // Loader exceptions can contain duplicates, leave only unique exceptions. foreach (var loaderException in ex.LoaderExceptions) { Debug.Assert(loaderException != null, "loader exception should not be null."); var line = string.Format(CultureInfo.CurrentCulture, Resource.EnumeratorLoadTypeErrorFormat, loaderException.GetType(), loaderException.Message); if (!map.ContainsKey(line)) { map.Add(line, null); errorDetails.AppendLine(line); } } } else { errorDetails.AppendLine(ex.Message); } return(errorDetails.ToString()); }
private static void DumpTypeLoadError(ReflectionTypeLoadException exc, StringBuilder sb) { try { if (exc == null) { return; } sb.Append("LoaderExceptions:").AppendLine("<br />"); foreach (var e in exc.LoaderExceptions) { sb.Append("-- "); sb.Append(e.GetType().FullName); sb.Append(": "); sb.Append(e.Message).AppendLine("<br />"); var fileNotFoundException = e as System.IO.FileNotFoundException; if (fileNotFoundException != null) { sb.Append("FUSION LOG:").AppendLine("<br />"); sb.Append(fileNotFoundException.FusionLog).AppendLine("<br />"); } } } catch (Exception e) { WriteError("DumpTypeLoadError", e); throw; } }