Ninject ASP.NET extension throwing TypeLoadException - asp.net

I'm trying to use Ninject 3 in an ASP.NET webforms application. We've been using it without the Ninject.Web extension for a while by creating a new injection kernel everywhere we needed one. It didn't occur to me until now that that's not the right way to do things. I wrote a little test application that is successfully using Ninject.Web, but when I tried to do the same thing in our real application, I'm receiving a TypeLoadException as soon as the page loads. It doesn't even make it into my code where I can set a breakpoint. Here's the exception and stack trace:
Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.
Description: An unhandled exception occurred during the execution of
the current web request. Please review the stack trace for more
information about the error and where it originated in the code.
Exception Details: System.TypeLoadException: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.
Source Error:
An unhandled exception was generated during the execution of the
current web request. Information regarding the origin and location of
the exception can be identified using the exception stack trace below.
Stack Trace:
[TypeLoadException: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'.]
System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken,
IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs,
Int32 methodInstCount, ObjectHandleOnStack type) +0
System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module,
Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext,
RuntimeTypeHandle[] methodInstantiationContext) +525
System.ModuleHandle.ResolveTypeHandle(Int32 typeToken,
RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[]
methodInstantiationContext) +19
System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken,
Type[] genericTypeArguments, Type[] genericMethodArguments) +315
System.Reflection.CustomAttribute.FilterCustomAttributeRecord(CustomAttributeRecord
caRecord, MetadataImport scope, Assembly& lastAptcaOkAssembly,
RuntimeModule decoratedModule, MetadataToken decoratedToken,
RuntimeType attributeFilterType, Boolean mustBeInheritable, Object[]
attributes, IList derivedAttributes, RuntimeType& attributeType,
IRuntimeMethodInfo& ctor, Boolean& ctorHasParameters, Boolean&
isVarArg) +208
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule
decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount,
RuntimeType attributeFilterType, Boolean mustBeInheritable, IList
derivedAttributes, Boolean isDecoratedTargetSecurityTransparent) +1171
System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly
assembly, RuntimeType caType) +146
WebActivator.AssemblyExtensions.GetActivationAttributes(Assembly
assembly) +114
WebActivator.ActivationManager.RunActivationMethods() +286
WebActivator.ActivationManager.RunPreStartMethods() +38
WebActivator.ActivationManager.Run() +56
[InvalidOperationException: The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1
methods) +11567502
System.Web.Compilation.BuildManager.CallPreStartInitMethods() +465
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager
appManager, IApplicationHost appHost, IConfigMapPathFactory
configMapPathFactory, HostingEnvironmentParameters hostingParameters,
PolicyLevel policyLevel, Exception appDomainCreationException) +1167
[HttpException (0x80004005): The pre-application start initialization
method Run on type WebActivator.ActivationManager threw an exception
with the following error message: Could not load type
'System.Runtime.CompilerServices.ExtensionAttribute' from assembly
'mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089'..]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
+141 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
wr, HttpContext context) +4813333
None of my searching has turned up anything terribly helpful, but the main avenue I've explored is a potential conflict between the version of .NET that Ninject was built against and the version that I'm actually running. I've never installed .NET 4.5 on my system, so I'm certain that I'm building against 4.0. I then built the most recent version of Ninject (3.0.2) and the extensions from source to be sure that it's using 4.0 as well. I also tried adding all the libraries that I'm using in the real app to my test app to see if there's a conflict but that didn't turn up anything. (However, I didn't go so far as to put in code that exercises them. I don't know if that would change anything.)
Has anyone seen this kind of problem before or have any ideas that I can try? Is there more info I can provide that would be helpful?
Alternatively, is there some other way I can use Ninject in an ASP.NET application instead of the ninject.web extension? Would wrapping the Ninject kernel up in a singleton work just as well?

Related

Having a hard time tracking down a process that is crashing my app pool

So I have an app that keeps crashing out and it's not leaving any application logs. When I finally went and looked in the event viewer for that server (a server 2003 box), I found this error (The even source was ASP.NET 4.0.30319.0)
An unhandled exception occurred and the process was terminated.
Application ID: /LM/W3SVC/2053196604/Root
Process ID: 24428
Exception: System.IO.FileLoadException
Message: Could not load file or assembly
'Microsoft.Practices.EnterpriseLibrary.Validation, Version=5.0.505.0,
Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its
dependencies. The located assembly's manifest definition does not
match the assembly reference. (Exception from HRESULT: 0x80131040)
StackTrace: Server stack trace: at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMarkHandle stackMark, Boolean loadTypeFromPartialName,
ObjectHandleOnStack type) at
System.RuntimeTypeHandle.GetTypeByName(String name, Boolean
throwOnError, Boolean ignoreCase, Boolean reflectionOnly,
StackCrawlMark& stackMark, Boolean loadTypeFromPartialName) at
System.RuntimeType.GetType(String typeName, Boolean throwOnError,
Boolean ignoreCase, Boolean reflectionOnly, StackCrawlMark& stackMark)
at System.Type.GetType(String typeName) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.AddValidationExtension()
at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator..ctor(IUnityContainer
container) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.CreateDefaultContainer(IConfigurationSource
configurationSource) at
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer.SetCurrentContainerIfNotSet()
at Microsoft.Practices.EnterpriseLibrary.Logging.Logger.get_Writer()
at Apriva.WebApi.Shared.Logging.DefaultLogWriter.Log(Object message,
TraceEventType severity, LogEntry& entry, String category, HttpContext
context) at
Apriva.WebApi.Shared.Logging.DefaultLogWriter.Info(Object message,
String category, HttpContext context) at
System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr
md, Object[] args, Object server, Int32 methodPtr, Boolean
fExecuteInContext, Object[]& outArgs) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink)
Exception rethrown at [0]: at
System.Runtime.Remoting.Proxies.RealProxy.EndInvokeHelper(Message
reqMsg, Boolean bProxyCase) at
System.Runtime.Remoting.Proxies.RemotingProxy.Invoke(Object NotUsed,
MessageData& msgData) at
Apriva.WebApi.Shared.Logging.Logger.LogDelegate.EndInvoke(IAsyncResult
result) at
Apriva.WebApi.Shared.Logging.Logger.LogAsyncComplete(IAsyncResult ar)
at
System.Runtime.Remoting.Messaging.AsyncResult.SyncProcessMessage(IMessage
msg) at
System.Runtime.Remoting.Messaging.StackBuilderSink.AsyncProcessMessage(IMessage
msg, IMessageSink replySink) at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.DoAsyncCall()
at
System.Runtime.Remoting.Proxies.AgileAsyncWorkerItem.ThreadPoolCallBack(Object
o) at
System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object
state) at System.Threading.ExecutionContext.Run(ExecutionContext
executionContext, ContextCallback callback, Object state, Boolean
ignoreSyncCtx) at
System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
at System.Threading.ThreadPoolWorkQueue.Dispatch() at
System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
For more information, see Help and Support Center at
When I check the processes in the task manager, this PID isn't present. I figure it's because it is a w3wp process. So I go to command prompt and run iisapp.vbs and it returns a single process with a different PID.
The error seems to imply that there is a config reference to a different version of the enterprise library for validation when the version that was found was v5.0.505.0 and while my projects have plenty of references to the enterprise library, none refer to the validation package.
So my question is -- does anyone have any insight into where I should look next? I was trying to use the PID to at least see which application was causing the error, but that doesn't seem to be getting me anywhere.
Analysis:
From stack trace its clear that reference chain is:
Apriva.WebApi.Shared.Logging.DefaultLogWriter => Microsoft.Practices.EnterpriseLibrary.Logging.Logger => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.EnterpriseLibraryContainer => Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator.
Method "AddValidationExtension" of type Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator needs type from 'Microsoft.Practices.EnterpriseLibrary.Validation assembly with signature
Possible steps find out root cause:
Open solution in visual studio.
Go to Edit Menu-> Find and Replace->Find in Files
Search for Microsoft.Practices.EnterpriseLibrary.Validation with Find options->Look at these file types -> *.csproj You will get list of project referencing this assembly.
Open all those project files in notepad and find out which one has different assembly signature than Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'
Most probably you should get culprit with above steps.
I will also recommend to check assembly cache and check signature of Microsoft.Practices.EnterpriseLibrary.Validation assembly and if it matches Version=5.0.505.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'

Could not load file or assembly for all of my dll

My asp.net application worked great until 2 days ago when suddenly it show the error below in the run time. It seems Visual Studio can't access any of .dlls. If I have and exclude one of dlls the page shows another error for next dll. what should I do?
Server Error in '/CargoPortal' Application.
Could not load file or assembly 'PersianDateControls 2.0' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IO.FileLoadException: Could not load file or assembly 'PersianDateControls 2.0' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Assembly Load Trace: The following information can be helpful to determine why the assembly 'PersianDateControls 2.0' could not be loaded.
WRN: Assembly binding logging is turned OFF.
To enable assembly bind failure logging, set the registry value [HKLM\Software\Microsoft\Fusion!EnableLog] (DWORD) to 1.
Note: There is some performance penalty associated with assembly bind failure logging.
To turn this feature off, remove the registry value [HKLM\Software\Microsoft\Fusion!EnableLog].
Stack Trace:
[FileLoadException: Could not load file or assembly 'PersianDateControls 2.0' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))]
[FileLoadException: Could not load file or assembly 'PersianDateControls 2.0, Version=2.0.3505.24227, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))]
System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +43
System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +127
System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +142
System.Reflection.Assembly.Load(String assemblyString) +28
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +46
[ConfigurationErrorsException: Could not load file or assembly 'PersianDateControls 2.0, Version=2.0.3505.24227, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +613
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +203
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +105
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +178
System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +54
System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +600
System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +125
System.Web.Compilation.BuildManager.CompileCodeDirectories() +265
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +320
[HttpException (0x80004005): Could not load file or assembly 'PersianDateControls 2.0, Version=2.0.3505.24227, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +58
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +512
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +729
[HttpException (0x80004005): Could not load file or assembly 'PersianDateControls 2.0, Version=2.0.3505.24227, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The parameter is incorrect. (Exception from HRESULT: 0x80070057 (E_INVALIDARG))]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +8995539
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +85
System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +259
Version Information: Microsoft .NET Framework Version:2.0.50727.8000; ASP.NET Version:2.0.50727.8001
Try to clean bin folder and the temp folder at the following location :
C:\Users\your_username\AppData\Local\Temp\Temporary ASP.NET
Do the same for all frameworks , if your application is running under 4.0 you should delete the Temp folder under 4.0
I created a new project from begin and problem solved

How do I debug inside the System.Web.Compilation.BuildManager

How do you debug events inside System.Web.Compilation.BuildManager? And in what stage of the IIS/ASP.net lifecycle is it called?
The problem is I have some code that uses the PreApplicationStartMethodAttribute but does not seem to fire. So I am trying to figure out the best way to attach a debugger to it.
There is some more details about the larger problem here
Why does PreApplicationStartMethodAttribute() not work in SharePoint 2013? but I have broken it into
a smaller problem to try and make some progress.
I've only been able to identify the following call stack so far...
BuildManager.CallPreStartInitMethods ->
BuildManager.​GetPreStartInitMethodsFromAssemblyCollection()
I'm working on a similar (or perhaps the same issue) and can give you the full stack trace. You can generate it yourself btw, just create a simple small MVC app and throw an exception in the method that you call using the PreApplicationStartMethodAttribute. You will get:
[ApplicationException: joe was here]
MvcApplication2.JoeStart.Start() in c:\Users\Joe\Documents\Visual Studio 2012\Projects\MvcApplication2\MvcApplication2\JoeStart.cs:18
[InvalidOperationException: The pre-application start initialization method Start on type MvcApplication2.JoeStart threw an exception with the following error message: joe was here.]
System.Web.Compilation.BuildManager.InvokePreStartInitMethodsCore(ICollection`1 methods, Func`1 setHostingEnvironmentCultures) +550
System.Web.Compilation.BuildManager.InvokePreStartInitMethods(ICollection`1 methods) +132
System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath) +90
System.Web.Compilation.BuildManager.ExecutePreAppStart() +135
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +516
[HttpException (0x80004005): The pre-application start initialization method Start on type MvcApplication2.JoeStart threw an exception with the following error message: joe was here.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9873784
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

PolicyException when using DotNetOpenAuth library

When I drop the DotNetOpenAuth dll into my /bin directory, my app won't run with the following stack trace. Has anyone had any experience with this library? I've gone through their docs and suspect I'm not deploying it correctly. My web app should be running with full trust on my local machine, so it's unclear what permissions it's asking for that can't be acquired.
Thanks!
Tom
[PolicyException: Required permissions cannot be acquired.]
System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Boolean checkExecutionPermission) +10238142
System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Int32& securitySpecialFlags, Boolean checkExecutionPermission) +97
[FileLoadException: Could not load file or assembly 'DotNetOpenAuth, Version=3.3.1.9337, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark& stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) +0
System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +416
System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +166
System.Reflection.Assembly.Load(String assemblyString) +35
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +190
[ConfigurationErrorsException: Could not load file or assembly 'DotNetOpenAuth, Version=3.3.1.9337, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +11207304
System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +388
System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +232
System.Web.Configuration.AssemblyInfo.get_AssemblyInternal() +48
System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +210
System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +76
System.Web.Compilation.CodeDirectoryCompiler.GetCodeDirectoryAssembly(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories, Boolean isDirectoryAllowed) +11196482
System.Web.Compilation.BuildManager.CompileCodeDirectory(VirtualPath virtualDir, CodeDirectoryType dirType, String assemblyName, StringSet excludedSubdirectories) +185
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +551
[HttpException (0x80004005): Could not load file or assembly 'DotNetOpenAuth, Version=3.3.1.9337, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +76
System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +1012
System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +1025
[HttpException (0x80004005): Could not load file or assembly 'DotNetOpenAuth, Version=3.3.1.9337, Culture=neutral, PublicKeyToken=2780ccd10d57b246' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11301302
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +88
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4338644
Oddly, I found the solution was related to this.
The application pool identity has a
property called Load User Profile.
When this value is false, you may
receive the error shown above. To
resolve this, open IIS Manager and
navigate to your application pool
identity. You will find the setting in
the Advanced Settings window. Change
it to true.
I found that when I set it to true, the library began working again. When I flipped it back to false it continued to work even after service restarts and app pool recycles. So, strangely everything seems okay now.
It looks like Code Access Security does not consider DotNetOpenAuth to be loading with full trust. It only needs medium trust, actually, but here is the list of minimum permissions DotNetOpenAuth requests:
[assembly: SecurityPermission(SecurityAction.RequestMinimum, Execution = true)]
[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = #"http://.*")]
[assembly: WebPermission(SecurityAction.RequestMinimum, ConnectPattern = #"https://.*")]
The second couple MAY be missing from some Medium trust configurations, but again if you're running with full trust it should be a non-issue.
Try adding <trust level="Full"/> to your web.config file in its <system.web> section and see if that either helps, or generates an error that will help you narrow down the problem.

System.Drawing: GDI+ is not properly initialized (​internal GDI+ error​)

An ASP.NET Web Site raises randomly this System.Drawing-error:
System.Runtime.InteropServices.ExternalException: System.Drawing.Bitmap..ctor(Stream stream)
System.Drawing.ToolboxBitmapAttribute..cctor()
Exception information:
Exception type: TypeInitializationException
Exception message: The type initializer for 'System.Drawing.ToolboxBitmapAttribute' threw an exception.
Stack trace: at System.Reflection.CustomAttribute._CreateCaObject(Void* pModule, Void* pCtor, Byte** ppBlob, Byte* pEndBlob, Int32* pcNamedArgs)
at System.Reflection.CustomAttribute.CreateCaObject(Module module, RuntimeMethodHandle ctor, IntPtr& blob, IntPtr blobEnd, Int32& namedArgs)
at System.Reflection.CustomAttribute.GetCustomAttributes(Module decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeType type, RuntimeType caType, Boolean inherit)
at System.RuntimeType.GetCustomAttributes(Type attributeType, Boolean inherit)
at System.ComponentModel.ReflectTypeDescriptionProvider.ReflectGetAttributes(Type type)
at System.ComponentModel.ReflectTypeDescriptionProvider.ReflectedTypeData.GetAttributes()
at System.ComponentModel.TypeDescriptor.TypeDescriptionNode.DefaultTypeDescriptor.System.ComponentModel.ICustomTypeDescriptor.GetAttributes()
at System.ComponentModel.TypeDescriptor.GetAttributes(Type componentType)
at System.Web.UI.ThemeableAttribute.IsTypeThemeable(Type type)
at System.Web.UI.Control.ApplySkin(Page page)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Control.InitRecursive(Control namingContainer)
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
Why? I think that this is a .NET Framework error (I'm actually not trying to create any images).
I found a temporary solution: restart IIS and delete Temporary ASP.NET Files ("%WINDIR%\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files").
But when this error happens in the production web-server, temporary is not enough...
By coincidence we've had this on one of our servers today. It's a known issue in ASP.NET, there's a hotfix for it at http://support.microsoft.com/kb/975410.
Changing this setting to true in the web.config fixed it for me:
<validation validateIntegratedModeConfiguration="true" />

Resources