Assert Failure at application start: ReflectionTypeLoad_LoadFailed - catel

When I start the application, sometimes (mostly first time after compiling), the following error is displayed.
A restart of the application solves the problem most times.
How can I find out the root cause?
Besides the error message and the stack trace I have no other informations about the cause.
Visual Studio tells me the source informations for debugging are not available.
From the threads info window I cann see the main thread is in Catel.Reflection.ReflectionExtensions.GetTypesEx().
ApplicationName.vshost.exe - Assert Failure
Expression: [mscorlib recursive resource lookup bug]
Description: Infinite recursion during resource lookup within mscorlib.
This may be a bug in mscorlib, or potentially in certain extensibility points such as assembly resolve events or CultureInfo names.
Resource name: ReflectionTypeLoad_LoadFailed
The complete stack trace is available in my onedrive.
Here are the first few lines:
Stack Trace:
at System.Environment.ResourceHelper.GetResourceStringCode(Object userDataln)
at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Environment.ResourceHelper.GetResourceString(String key, CultureInfo culture)
at System.Environment.ResourceHelper.GetResourceString(String key)
at System.Environment.GetResourceStringLocal(String key)
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.ReflectionAssembly.GetTypes()
at Catel.Reflection.ReflectionExtensions.GetTypesEx(Assembly assembly) in c:\CIWSMA1596\Source\Catel\sraCatel.Core\Catel.CoreShareaReflection\Extensions\ReflectionExtensions.assembly.cs:line 33
at Catel.Reflection.AssemblyHelper.GetAllTypesSafely(Assembly assembly, Boolean logLoaderExceptions) in cACI_WS\WA1596\Source\Catel sraCatel.Core\Catel.Core.ShareaReflection\Helpers `, AssemblyHelper.cs:line 192
at Catel.Reflection.TypeCachelnitializeAssemblies(lEnumerablel assemblies) in cACI_WSWW\1596\Source\Catel\src\Catel.CoreKatel.Core.ShareaReflection\TypeCache.cs:line 583
at Catel.Reflection.TypeCachelnitializeTypes(Boolean forceFulllnitialization, Assembly assembly) in cACI_WSNWs\1596\Source\cateNsraCatel.Core\Catel.Core.ShareaReflection\TypeCache.cs:line 553
at Catel.Reflection.TypeCache.OnAssemblyLoaded(Object sender, AssemblyLoadEventArgs args) in c:\CI_WSNWs\1596\SourceKateNsraCatel.Core\Catel.Core.ShareaReflection\TypeCache.cs:line 131
at System.AssemblyLoadEventHandlerinvoke(Object sender, AssemblyLoadEventArgs args)
at SystemAppDomain.OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at Catel.Reflection.ReflectionExtensions.GetTypesEx(Assembly assembly) in c:\CIWS\Ws\1596\Source\Catel\src\Catel.Core\Catel.Core.Shared\Reflection\Extensions\ReflectionExtensions.assembly.cs:line 33
at Catel.ReflectionAssemblyHelper.GetAllTypesSafely(Assembly assembly, Boolean logLoaderExceptions) in c:\CI_WSNWs\1596\Source\catel\sraCatel.Core\Catel.Core.ShareaReflection\Helpers‘AssemblyHelper.cs:line 192
at Catel.Reflection.TypeCachelnitializeAssemblies(lEnumerablel assemblies) in cACI_WSNWs\1596\SourceKatel\src\Catel.Core\Catel.Core.ShareaReflection TypeCache.cs:line 583
at Catel.Reflection.TypeCachelnitializeTypes(Boolean forceFulllnitialization, Assembly assembly) in c:\CIWS\Ws\1596\Source\Catel\sraCatel.Core\Catel.Core.ShareaReflection\TypeCache.cs:line 553
at Catel.Reflection.TypeCache.OnAssemblyLoaded(Object sender, AssemblyLoadEventArgs args) in c:\CI__WS\WA1596\Source\Catel\sraCatel.Core\Catel.Core.ShareaReflection\TypeCache.cs:line 131
at System.AssemblyLoadEventHandlerinvoke(Object sender, AssemblyLoadEventArgs args)
at System.AppDomain.OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
at System.Reflection.RuntimeModule.GetTypes()
at System.Reflection.Assembly.GetTypes()
at Catel.Reflection.ReflectionExtensions.GetTypesEx(Assembly assembly) in c: CIWSNWs\1596\Source\Catel\src Catel.Core\Catel.Core.ShareaReflection Extensions\ReflectionExtensions.assembly.cs:line 33
at Catel.Reflection.AssemblyHelper.GetAllTypesSafely(Assembly assembly, Boolean logLoaderExceptions) in c:\CI_WSNWs\1596\Source\Catel sraCatel.Core\Catel.Core.ShareaReflection\Helpers\AssemblyHelper.cs:line 192
at Catel.Reflection.TypeCacheinitializeAssemblies(lEnumerablel assemblies) in cACI_WS\WA1596\Source\Catel\src\Catel.CoreKatel.Core.ShareaReflection\TypeCache.cs:line 583
at Catel.Reflection.TypeCacheinitializeTypes(Boolean forceFulllnitialization, Assembly assembly) in cACIWS\WA1596\Source\Catel\sraCatel.Core\Catel.Core.ShareaReflection‘TypeCache.cs:line 553
at Catel.Reflection.TypeCache.OnAssemblyLoaded(Object sender, AssemblyLoadEventArgs args) in c:\CI__WS\Ws\1596\Source\Catel\sraCatel.Core\Catel.Core.ShareaReflection‘TypeCache.cs:line 131
at System.AssemblyLoadEventHandlerinvoke(Object sender, AssemblyLoadEventArgs args)
at System.AppDomain.OnAssemblyLoadEvent(RuntimeAssembly LoadedAssembly)

The AssemblyHelper in Catel creates a cache to make reflection as fast as possible. This means that it sometimes tries to load types / assemblies that cannot be loaded, but these are first-chance exceptions so can be safely ignored.

Related

Azure Durable Function fails to start after going idle (Intermittent)

Every so often, we're faced with the intermittent issue of a Durable Function not starting up after going idle (Consumption plan).
Looking at the logs we see that it refers to a DI issue and/or failing to start in the:
ScriptStartupTypeLocator.cs
Not so happy developer here, we're struggling to diagnose the issue! No detail in any MS documentation, or many reports of the problem.
Full trace below:
System.IO.FileLoadException : Assembly with same name is already loaded
at System.Runtime.Loader.AssemblyLoadContext.LoadFromPath(IntPtr ptrNativeAssemblyLoadContext,String ilPath,String niPath,ObjectHandleOnStack retAssembly)
at System.Runtime.Loader.AssemblyLoadContext.LoadFromAssemblyPath(String assemblyPath)
at Microsoft.Azure.WebJobs.Script.DependencyInjection.ScriptStartupTypeLocator.<>c__DisplayClass9_1.b__0(AssemblyName assemblyName) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\DependencyInjection\ScriptStartupTypeLocator.cs : 116
at System.TypeNameParser.ResolveAssembly(String asmName,Func`2 assemblyResolver,Boolean throwOnError,StackCrawlMark& stackMark)
at System.TypeNameParser.ConstructType(Func`2 assemblyResolver,Func`4 typeResolver,Boolean throwOnError,Boolean ignoreCase,StackCrawlMark& stackMark)
at System.TypeNameParser.GetType(String typeName,Func`2 assemblyResolver,Func`4 typeResolver,Boolean throwOnError,Boolean ignoreCase,StackCrawlMark& stackMark)
at System.Type.GetType(String typeName,Func`2 assemblyResolver,Func`4 typeResolver,Boolean throwOnError,Boolean ignoreCase)
at async Microsoft.Azure.WebJobs.Script.DependencyInjection.ScriptStartupTypeLocator.GetExtensionsStartupTypesAsync() at C:\azure-webjobs-sdk-script\src\WebJobs.Script\DependencyInjection\ScriptStartupTypeLocator.cs : 113
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Azure.WebJobs.Script.DependencyInjection.ScriptStartupTypeLocator.GetStartupTypes() at C:\azure-webjobs-sdk-script\src\WebJobs.Script\DependencyInjection\ScriptStartupTypeLocator.cs : 55
at Microsoft.Azure.WebJobs.WebJobsBuilderExtensions.UseExternalStartup(IWebJobsBuilder builder,IWebJobsStartupTypeLocator startupTypeLocator,ILoggerFactory loggerFactory) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsBuilderExtensions.cs : 167
at Microsoft.Azure.WebJobs.Script.ScriptHostBuilderExtensions.UseScriptExternalStartup(IWebJobsBuilder builder,ScriptApplicationHostOptions applicationHostOptions,ILoggerFactory loggerFactory,IExtensionBundleManager extensionBundleManager,IMetricsLogger metricsLogger) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\ScriptHostBuilderExtensions.cs : 237
at Microsoft.Azure.WebJobs.Script.ScriptHostBuilderExtensions.<>c__DisplayClass3_0.b__0(HostBuilderContext context,IWebJobsBuilder webJobsBuilder) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\ScriptHostBuilderExtensions.cs : 114
at Microsoft.Extensions.Hosting.WebJobsHostBuilderExtensions.<>c__DisplayClass4_0.b__1(HostBuilderContext context,IServiceCollection services) at C:\projects\azure-webjobs-sdk-rqm4t\src\Microsoft.Azure.WebJobs.Host\Hosting\WebJobsHostBuilderExtensions.cs : 47
at Microsoft.Extensions.Hosting.HostBuilder.CreateServiceProvider()
at Microsoft.Extensions.Hosting.HostBuilder.Build()
at Microsoft.Azure.WebJobs.Script.WebHost.DefaultScriptHostBuilder.BuildHost(Boolean skipHostStartup,Boolean skipHostConfigurationParsing) at C:\azure-webjobs-sdk-script\src\WebJobs.Script.WebHost\DefaultScriptHostBuilder.cs : 59
at async Microsoft.Azure.WebJobs.Script.WebHost.WebJobsScriptHostService.UnsynchronizedStartHostAsync(ScriptHostStartupOperation activeOperation,Int32 attemptCount,JobHostStartupMode startupMode) at C:\azure-webjobs-sdk-script\src\WebJobs.Script.WebHost\WebJobsScriptHostService.cs : 234
Any help will be super helpful.
//Further Investigation
Finally managed to find further details using app insights:
Message:
Method not found: 'Void DurableTask.AzureStorage.AzureStorageOrchestrationServiceSettings.set_FetchLargeMessageDataEnabled(Boolean)'.
Failed method:
DryIoc.Microsoft.DependencyInjection.DryIocAdapter+<>c__DisplayClass3_0.<RegisterDescriptor>b__0
With the above in mind, it appears that an in-built IoC container is failing to register?

Unknown custom metadata item kind: 6 when using Costura.Fody

I try using Costura.Fody to embed DLL files into exe file. First I install Costura.Fody by run this command in package manager console : install-package Costura.Fody, Then Build the project. But building project was unsuccessful and this is the error of building project:
Severity Code Description Project File Line
Error Fody: An unhandled exception occurred:
Exception:
Unknown custom metadata item kind: 6
StackTrace:
at Microsoft.Cci.Pdb.PdbFunction.ReadCustomMetadata(BitAccess bits)
at Microsoft.Cci.Pdb.PdbFunction..ctor(ManProcSym proc, BitAccess bits)
at Microsoft.Cci.Pdb.PdbFunction.LoadManagedFunctions(BitAccess bits, UInt32 limit, Boolean readStrings)
at Microsoft.Cci.Pdb.PdbFile.LoadFuncsFromDbiModule(BitAccess bits, DbiModuleInfo info, IntHashTable names, ArrayList funcList, Boolean readStrings, MsfDirectory dir, Dictionary`2 nameIndex, PdbReader reader)
at Microsoft.Cci.Pdb.PdbFile.LoadFunctions(Stream read, Dictionary`2& tokenToSourceMapping, String& sourceServerData, Int32& age, Guid& guid)
at Mono.Cecil.Pdb.PdbReader.PopulateFunctions()
at Mono.Cecil.Pdb.PdbReader.ProcessDebugHeader(ImageDebugDirectory directory, Byte[] header)
at Mono.Cecil.ModuleDefinition.ProcessDebugHeader()
at Mono.Cecil.ModuleDefinition.ReadSymbols(ISymbolReader reader)
at Mono.Cecil.ModuleReader.ReadSymbols(ModuleDefinition module, ReaderParameters parameters)
at Mono.Cecil.ModuleReader.CreateModuleFrom(Image image, ReaderParameters parameters)
at Mono.Cecil.ModuleDefinition.ReadModule(Stream stream, ReaderParameters parameters)
at Mono.Cecil.ModuleDefinition.ReadModule(String fileName, ReaderParameters parameters)
at InnerWeaver.ReadModule() in c:\TeamCity\buildAgent\work\7495521761d392b9\FodyIsolated\ModuleReader.cs:line 14
at InnerWeaver.Execute() in c:\TeamCity\buildAgent\work\7495521761d392b9\FodyIsolated\InnerWeaver.cs:line 28
Source:
Mono.Cecil.Pdb
TargetSite:
Void ReadCustomMetadata(Microsoft.Cci.Pdb.BitAccess) WindowsFormsApplication3
Am I missing something?
Update the fody package.
update-package Fody

MethodAccessException when calling nlog LogManager.GetCurrentClassLogger()

I'm getting an exception when I run a unit test on a controller in web project (ASP.NET web api). The exception is thrown when LogManager.GetCurrentClassLogger() of the controller is executed:
System.MethodAccessException: Attempt by method 'Castle.Proxies.ClaimsPrincipalProxy.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)' to access method 'Castle.DynamicProxy.Internal.TypeUtil.Sort(System.Reflection.MemberInfo[])' failed
It results in TypeInitializationException in LogManager.GetCurrentClassLogger().
here is the call stack:
at Castle.Proxies.ClaimsPrincipalProxy.GetObjectData(SerializationInfo, StreamingContext)
at System.Runtime.Serialization.ObjectCloneHelper.GetObjectData(Object serObj, String& typeName, String& assemName, String[]& fieldNames, Object[]& fieldValues)
at System.AppDomain.get_Evidence()
at System.AppDomain.get_Evidence()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, ref String typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, ref Object result, ref Object resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at NLog.Config.XmlLoggingConfiguration.get_AppConfig()
at NLog.LogFactory.get_Configuration()
at NLog.LogFactory.GetLogger(LoggerCacheKey cacheKey)
at NLog.LogFactory.GetLogger(String name)
at NLog.LogManager.GetCurrentClassLogger()
Update:
The issue happens when the unit test project references NSubstitute. So, it seems like there some dangerous combination of Web API, NSubstitute and NLog.
Update 2:
Found what upsets Nlog in Controller.
Before calling controller method I set mocked principal for Thread.CurrentPrincipal:
var principal = Substitute.For<ClaimsPrincipal>();
principal.Identity.Returns(...);
Thread.CurrentPrincipal = principal;
How could this be fixed?
The Castle assembly may be marked with the AllowPartiallyTrustedCallersAttribute, and that uses the level 2 security transparency model.
Level 2 transparency causes all methods in AllowPartiallyTrustedCallers assemblies to become security transparent by default, which may be the cause of this exception.
Can you try annotating your unit test (and Class) with the following attribute - [SecuritySafeCritical]

Loading assemblies dynamically using the AssemblyResolve Event fails at random

Following the example of the following KB article we have implemented the AssemblyResolve event in order to point .Net to the correct folder to load assemblies from: http://support.microsoft.com/kb/837908
This is our current implementation:
public static class AssemblyLoader
{
/// <summary>
/// A custom AssemblyResolver that will search for missing assemblies in the root and subfolders of the executing assembly
/// </summary>
/// <param name="sender"></param>
/// <param name="args"></param>
/// <returns></returns>
public static System.Reflection.Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
string assemblyPath = string.Empty;
string assemblyFileName = string.Empty;
try
{
// This handler is called only when the common language runtime tries to bind to the assembly and fails.
string rootProbingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
// Loop through the referenced assembly names.
assemblyFileName = args.Name.Substring(0, args.Name.IndexOf(",")) + ".dll";
// Search for the filename in the root and subfolders of the rootProbingPath
string[] matchingAssemblies = Directory.GetFiles(rootProbingPath, assemblyFileName, SearchOption.AllDirectories);
// If a match is found, awesomeness was achieved!
if (matchingAssemblies.Length > 0)
assemblyPath = matchingAssemblies[0];
// Throw a clear exception when the assembly could not be found.
if (string.IsNullOrEmpty(assemblyPath))
throw new FileNotFoundException(string.Format("AssemblyLoader: Could not find assembly '{0}' in '{1}' or its subfolders.", assemblyFileName, rootProbingPath));
Console.WriteLine(string.Format("[" + DateTime.Now.ToString() + "] AssemblyLoader: Assembly '{0}' found at '{1}'", assemblyFileName, assemblyPath));
// Load the assembly from the specified path.
return Assembly.LoadFrom(assemblyPath, AppDomain.CurrentDomain.Evidence);
}
catch (Exception ex)
{
throw new Exception(string.Format("[" + DateTime.Now.ToString() + "] The assemblyloader could not load the assembly '{0}' from path '{1}': " + ex.Message, assemblyFileName, assemblyPath), ex);
}
}
}
We use this in all of our batch procedures which often run in parallel and using mostly the same assemblies.
Periodically a batch will crash leaving the following trail:
[26/04/2013 12:35:01] AssemblyLoader: Assembly
'COMPANY.DistributieOrderFacade.dll' found at
'C:\COMPANY_Batch\MDS\Executables\MDS\FACADE\COMPANY.DistributieOrderFacade.dll'
[26/04/2013 12:35:01] AssemblyLoader: Assembly
'COMPANY.DOCUMENTCENTERDOCS.dll' found at
'C:\COMPANY_Batch\MDS\Executables\MDS\CLIENT\COMPANY.DOCUMENTCENTERDOCS.dll'
26/04/2013 12:35:01: Create COMPANYDocument...in
queue:\rug.adroot\dfsroot\mds\Data\queue_new\ 26/04/2013 12:35:01
Could not load file or assembly 'COMPANY.DistributieOrderBRDA,
Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its
dependencies. General Exception (Exception from HRESULT: 0x80131500)
The assembly in the error is indeed located in one of the folders which the AssemblyLoader searches. And if I run the procedure again, it does succeed.
I've tried to see if the dll's are getting locked by using this assembly loader in two console apps and access the same dll's at the same time, but this did not seem to be a problem.
I should also mention that this is just a log from one of the batches. There are others, and it's rarely the same assembly that is not being loaded.
I don't know where to start looking for a solution next.
It was due to an update script that updated the dll's before each batch was running. When two batches were running at the same and there was a dll that needed updating, locks were occurring on the dll's which was causing the problem.
We've removed this script for a week now and haven't seen any problems yet. So our conclusion is that this was the problem.

What does method handleAttribute(String name, Object value) inside UIComponent Mojarra is doing?

So let pick a UIComponent like HtmlSelectOneRadio(Please view source here: http://grepcode.com/file/repo1.maven.org/maven2/com.sun.faces/jsf-api/2.1.7/javax/faces/component/html/HtmlSelectOneRadio.java#HtmlSelectOneRadio)
So some of the setters will call method handleAttribute(...), and some does not, for example
public void setDir(java.lang.String dir) {
getStateHelper().put(PropertyKeys.dir, dir);
handleAttribute("dir", dir);
}
public void setDisabled(boolean disabled) {
getStateHelper().put(PropertyKeys.disabled, disabled);
}
and it is very UNCLEAR to me what handleAttribute is doing, can a JSF guru please explain to me what this method try accomplish and why somes attribute call this method while other does not? Thank you so much
It's related to Mojarra-internal rendering optimizations, wherein only the attributes which are been set by the internal handleAttribute() method are been rendered as so-called "pass-thru" attributes instead of that every single attribute of the component will be checked if it has been set or not, which may end up to be more expensive if there are relatively a lot of attributes. A "pass-thru" attribute is a component attribute which can just be outright rendered without any specific pre/postprocessing.
Peek around in Mojarra's RenderKitUtils class, starting at the renderPassThruAttributes() method:
316 if (canBeOptimized(component, behaviors)) {
317 //noinspection unchecked
318 List<String> setAttributes = (List<String>)
319 component.getAttributes().get(ATTRIBUTES_THAT_ARE_SET_KEY);
320 if (setAttributes != null) {
321 renderPassThruAttributesOptimized(context,
322 writer,
323 component,
324 attributes,
325 setAttributes,
326 behaviors);
327 }
328 } else {
329
330 // this block should only be hit by custom components leveraging
331 // the RI's rendering code, or in cases where we have behaviors
332 // attached to multiple events. We make no assumptions and loop
333 // through
334 renderPassThruAttributesUnoptimized(context,
335 writer,
336 component,
337 attributes,
338 behaviors);
339 }
The canBeOptimized() returns true if the component is one of the standard JSF components (actually, if the component's package name starts with javax.faces.component.) and if there is no more than 1 behavior in the behaviors array.
The renderPassThruAttributesOptimized() will only render the attributes which are specified in setAttributes argument.
The renderPassThruAttributesUnoptimized() will loop through every single attribute in the attributes map and check for every single attribute if the associated value is not null/empty and then render it.
As to why some attributes are not been set by handleAttribute(), that's because they require some more specific pre/postprocessing and are already explicitly been rendered by the renderer specific to the component, so they don't need to be rendered as a "pass-thru" attribute.
You don't need to worry about this when writing custom components. You can always introduce your own optimizations similar to this, but it isn't recommend to rely on Mojarra-specific internal optimizations as they may not work at all when you're using MyFaces, for example.

Resources