Opening Office Application Error: Microsoft.Office.Interop.Excel / Microsoft.Office.Interop.Word - excel

I am hoping that someone can give a little insight and/or instance.
I am experiencing an error trying to create an instance of an Excel or Word application. The application I am working on is using interop assemblies to manipulate Excel and Word. In both cases, I have been successful in doing so in the past, the problems/errors began only recently. I've noticed multiple posts about similar error messages and have looked through them, but none addressed a similar issue or provided relevant insights.
In attempting to create an instance of Excel, the resulting error is similar to the following:
{System.Runtime.InteropServices.COMException (0x80080005): Retrieving
the COM class factory for component with CLSID
{00024500-0000-0000-C000-000000000046} failed due to the following
error: 80080005 Server execution failed (Exception from HRESULT:
0x80080005 (CO_E_SERVER_EXEC_FAILURE)). at
System.Runtime.Remoting.RemotingServices.AllocateUninitializedObject(RuntimeType
objectType) at
System.Runtime.Remoting.Activation.ActivationServices.CreateInstance(RuntimeType
serverType) at
System.Runtime.Remoting.Activation.ActivationServices.IsCurrentContextOK(RuntimeType
serverType, Object[] props, Boolean bNewObj) at
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean
publicOnly, Boolean noCheck, Boolean& canBeCached,
RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) at
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean
skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) at
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly,
Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, Boolean nonPublic) at
System.Activator.CreateInstance(Type type)
I am encountering a similar error when trying to create an instance of Word. Again, my code has been doing this with no problem, until recently.
I'm thinking this may have started with possibly with recent upgrades to the Office instance on my development machine.
The references for both Interop assemblies (Microsoft.Office.Interop.Excel and Microsoft.Office.Interop.Word) associated with my project have Embed Interop Types set to TRUE)
If I am interpreting the error text correctly, the code is looking for the typelib/class id (i.e., {00024500-0000-0000-C000-000000000046}) to be in the current machine's registry and cannot find it. I did search the \HKEY_CLASSES_ROOT\TypeLib folder in the registry and did not see it. My question would be, why is it looking for that particular id? Of course, I may be completely out in left field on this line of reasoning.
Since I am seeing similar effects in both contexts, I have to believe that the issue's cause here is on the Office level, rather than either application. To the best of my knowledge, no change was made to the code or the Interop assembly references in the project.
Any insights and/or suggestions would, of course, be greatly appreciated.
I am using VS 2017 (64-bit) on Windows 10.

Related

WindowsIdentity.Impersonate throws ''Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))' after April 2018 (1803) update

Our installer app uses the following code to verify service account permissions:
try
{
using (svcIdentity.Impersonate())
{
using (SqlConnection conn = new SqlConnection(builder.ConnectionString)) // <<<
{
conn.Open();
...
Omitted for brevity:
The svcIdentity WindowsIdentity is obtained by using the Win32 LSA LogonUser function in advapi32.dll and LOGON32_LOGON_SERVICE.
builder is a SqlConnectionStringBuilder that builds a connectionstring to a local SQL Server database.
Targeting .Net Framework 4.6.
The app runs elevated (requestedExecutionLevel level='requireAdministrator' in the app.manifest).
This code ran flawless until Windows 10 version 1803 (April 2018 update). Since then, the SqlConnection constructor (marked <<<) throws an exception:
The type initializer for 'System.Data.SqlClient.SqlConnection' threw an exception.
The inner exception provides more insight:
Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
Stack trace:
at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)
at System.Security.Policy.PEFileEvidenceFactory.GenerateLocationEvidence()
at System.Security.Policy.PEFileEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.AssemblyEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.GetHostEvidence(Type type, Boolean markDelayEvaluatedEvidenceUsed)
at System.Security.Policy.AppDomainEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.RawEvidenceEnumerator.MoveNext()
at System.Security.Policy.Evidence.EvidenceEnumerator.MoveNext()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, 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, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Data.SqlClient.SqlConnection..cctor()
The stack trace indicates the SqlConnection constructor fails to open a configuration section. Our app.config does not have a connectionstrings section and machine.config and security.config on the tested computers haven't changed since 2017.
The code works when:
Commenting out using (svcIdentity.Impersonate),
or
when setting a breakpoint on the line immediately above the SqlConnection constructor ({) and stepping through the code (???),
or
when adding our application to the registry key mentioned at the end of KB945701
That KB article about a fix for Internet Explorer 9 seems unrelated, except that GetLocationEvidence on the first line of the stack trace seems to take a SecurityZone into account, which applications listed in the corresponding registry key seem to ignore.
Now my question:
Can anybody help me understand what exactly is going wrong, and if there is a better way to fix this than with an obscure registry key? It seems a 'coincidence' that this registry change works and I'm afraid our code might break again if we don't understand exactly why it fails.
Thx.

WP Silverlight BackgroundTask Communication with Azure

Hello I have a silverlight project for WP8.1 that is a game. I use a backgroundTask to alert the user about when he last played, if he is too slow to comply I would like to make a call to the server from the bagroundTask to resign from the games.
The backgroundTask is made using stackoverflow and this blog, just basic implementations of the backgroundTask.
I then install the NuGet Package Microsoft.Azure.Mobile.Client and everything is fine, I then do a compile, everything succeeds.
The app installs and splashscreen appears, then I get an error in the main project at the initialization of MobileServiceClient in App.xaml.cs
public MobileServiceClient MobileService = new MobileServiceClient(
"https://xxxxx.azurewebsites.net"
);
The exception in the above line states:
An exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code
Additional information: Could not load file or assembly 'System.Runtime.InteropServices, Version=4.0.10.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.
The only change was the install of the NuGet package in the backgroundTask project. The stack trace output for the exception above.
at System.ModuleHandle.ResolveType(RuntimeModule module, Int32 typeToken, IntPtr* typeInstArgs, Int32 typeInstCount, IntPtr* methodInstArgs, Int32 methodInstCount, ObjectHandleOnStack type)
at System.ModuleHandle.ResolveTypeHandleInternal(RuntimeModule module, Int32 typeToken, RuntimeTypeHandle[] typeInstantiationContext, RuntimeTypeHandle[] methodInstantiationContext)
at System.Reflection.RuntimeModule.ResolveType(Int32 metadataToken, Type[] genericTypeArguments, Type[] genericMethodArguments)
at 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)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean mustBeInheritable, IList derivedAttributes, Boolean isDecoratedTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeModule decoratedModule, Int32 decoratedMetadataToken, Int32 pcaCount, RuntimeType attributeFilterType, Boolean isDecoratedTargetSecurityTransparent)
at System.Reflection.CustomAttribute.GetCustomAttributes(RuntimeAssembly assembly, RuntimeType caType)
at System.Reflection.RuntimeAssembly.GetCustomAttributes(Type attributeType, Boolean inherit)
at System.Attribute.GetCustomAttributes(Assembly element, Type attributeType, Boolean inherit)
at Microsoft.WindowsAzure.MobileServices.PlatformInformationExtensions.GetVersionFromAssemblyFileVersion(IPlatformInformation platformInformation)
at Microsoft.WindowsAzure.MobileServices.PlatformInformation.get_Version()
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient.GetUserAgentHeader()
at Microsoft.WindowsAzure.MobileServices.MobileServiceHttpClient..ctor(IEnumerable`1 handlers, Uri applicationUri, String installationId)
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor(Uri mobileAppUri, HttpMessageHandler[] handlers)
at Microsoft.WindowsAzure.MobileServices.MobileServiceClient..ctor(String mobileAppUri, HttpMessageHandler[] handlers)
at BC_Menu.App..ctor()
I have not been able to solve this issue.
Extra
I am able to do normal http calls to the web by using the proposed code, replicated here:
BackgroundTaskDeferral _deferral;
public async void Run(IBackgroundTaskInstance taskInstance)
{
_deferral = taskInstance.GetDeferral();
// your async code
_deferral.Complete();
}
Update based on Adrian Halls Answer
The code works, my front application can communicate with the server and everything. The backgroundTask, can extract information from the device everything is fine, everything compiles and runs.
I then add the NuGet package to the backgroundTask and suddenly the above error appears, when I deploy this solution to the client.
I am running VS2015, Win10, and have v2.0.1 installed of Microsoft.Azure.Mobile.Client. I have seen some odd behaviours with silverlight projects on win10 before.
The error indicates a problem with your .NET setup - the error is in mscorlib (the basic library for .NET). Try to add a reference to the specific library that you need. Also, ensure that you have installed v2.0.1 (or later) or the Microsoft.Azure.Mobile.Client library.

Running Classic ASP on IIS 7.5 in STA

Trying to for a Classic ASP webapp on IIS 7.5 to run in STA mode by enabling AspCompat. This is a hard requirement due to a COM Object being instantiated that is not thread safe.
<%# Page Language="VBScript" AspCompat="true" Debug="false" %>
Although the settings is forced through AspCompat, the behaviour when rendering websites seems not to be consequent.
The expected behaviour:
On every page request, the ComServer.exe starts, does some work and closes.
When another request arrives, processing waits for the first request to finish.
I know this is bad performance whise. However sadly, this is a hard requirement for running the legacy ComServer.
This behaviour is visible when there are multiple parallel requests comming from the same client. When multiple requests come from different clients however, the behaviour changes:
After every batch of requests, the ComServer is closed.
If there is only one request, the ComServer is stopped after the request
If there are multiple requests, they are all processed under the same ComServer
Action 3 causes the ComServer to sometimes fail, causing COMExceptions.
Although the issue is probably caused by bad design of the COMObject, I cannot change this. The only thing I can do is surrounding COMObject access with an Application Lock
Dim oComSvr as object
oComSvr=Server.CreateObject("com_svr.my_svr")
...
Application.Lock
returnValue=oComSvr.selectform(value1, value2, ...)
Application.Unlock
However this prevents most COMExceptions, there are still specific timings that result in a COMException.
What can I do to force constant STA behaviour, also if multiple requests to the same IIS server come from different clients.
Tried to follow this article and implemented Page_Load to prevent the object being created before STA mode. http://technet.microsoft.com/en-ca/zwk9h2kb(v=vs.95).aspx
It still looks like if AspCompat is being ignored.
[COMException (0x800706be): Creating an instance of the COM component with CLSID {B28A581A-6CE3-46E9-871F-B2E129F7D238} from the IClassFactory failed due to the following error: 800706be.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean fillCache) +86
System.RuntimeType.CreateInstanceImpl(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean fillCache) +230
System.Activator.CreateInstance(Type type, Boolean nonPublic) +67
System.Activator.CreateInstance(Type type) +6
System.Web.HttpServerUtility.CreateObject(String progID) +122
ASP.myapp.Page_Load() +1670
System.Web.Util.CalliHelper.ArglessFunctionCaller(IntPtr fp, Object o) +8
System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) +8760147
System.Web.UI.Control.OnLoad(EventArgs e) +99
System.Web.UI.Control.LoadRecursive() +50
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +627
Update:
Read here and here that it is important WHERE the STA object is instantiated. Instantiating the object during construction time will cause this issue.
http://technet.microsoft.com/en-ca/zwk9h2kb(v=vs.95).aspx
http://msdn.microsoft.com/en-us/library/5dws599a(vs.71).aspx
Tried instantiating in Page_Load as in the example. However this does not change the behaviour when accessing the page from another client.
OK we've had this and this is how I've found a solution.. In our case I think it was linked to parent paths but could have been session state too...
Browse to C:\Documents and Settings\$your user name$\My Documents\IIS 7.5\config
Open applicationHost.config
Find the section
Change the section to the following… By default it only had the cache and empty limits bits but feel free to adjust any parameters you don't want.
<asp
enableParentPaths="true"
bufferingOn="true"
errorsToNTLog="true"
appAllowDebugging="true"
appAllowClientDebug="true"
scriptErrorSentToBrowser="true">
<session allowSessionState="true" />
<cache diskTemplateCacheDirectory="%TEMP%\iisexpress\ASP Compiled Templates" />
<limits />
</asp>
Save and restart iis 7.5.
if it is surrounding COMObject access with an Application Lock
However, if you write something like this in a sample format to get an idea.
Application["Counter"] = (int) Application["Counter"] + 1;
then you will need to use Lock and Unlock as follows:
Application.Lock();
Application["Counter"] = (int) Application["Counter"] + 1;
Application.Unlock();
This is because the thread might be interrupted between the read from, and then write to, the Application object, and another thread could therefore alter the value stored for the "Counter".

How do I make my application run in Full Trust mode - .NET 4.0 Console Application

We are having an issue with a command line (batch) application and full/partial trust.
Our previous release (version number 7.13.0.63) works fine, however, when we install the new version (7.13.0.249) we get a “That assembly does not allow partially trusted callers.”
Exception:
Stack Trace (edited):
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance[T]()
at <Company>.Service.<Product>.Proxy.Factories.ControllerProxyFactory.Create[T]()
<Stack Trace that leads to creation of a WCF client> ...
Inner Exception:
An error occurred creating the configuration section handler for system.serviceModel/behaviors: That assembly does not allow partially trusted callers. (C:\Program Files (x86)\InsuranceLine\ListLoader\InsuranceLine.ListLoader.Launcher.exe.Config line 53)
Stack Trace:
at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, FactoryRecord factoryRecord, SectionRecordsectionRecord, Object parentResult)
at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.ServiceModel.Activation.AspNetEnvironment.UnsafeGetSectionFromConfigurationManager(String sectionPath)
at System.ServiceModel.Activation.AspNetEnvironment.UnsafeGetConfigurationSection(String sectionPath)
at System.ServiceModel.Configuration.ConfigurationHelpers.UnsafeGetAssociatedSection(ContextInformation evalContext, String sectionPath)
at System.ServiceModel.Description.ConfigLoader.LookupChannel(ContextInformation configurationContext, String configurationName, ContractDescription contract, EndpointAddress address, Boolean wildcard, Boolean useChannelElementKind, ServiceEndpoint& serviceEndpoint)
at System.ServiceModel.ChannelFactory.InitializeEndpoint(String configurationName, EndpointAddress address)
at System.ServiceModel.ChannelFactory`1..ctor(String endpointConfigurationName, EndpointAddress remoteAddress)
<Stack Trace that determines the correct WCF factory to create>
Inner Exception:
That assembly does not allow partially trusted callers.
Stack Trace:
at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(RuntimeAssembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandleInternal rmh, SecurityAction action, Object demand, IPermission permThatFailed)
at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
at System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache)
at System.Activator.CreateInstance(Type type, Boolean nonPublic)
at System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement`1.CreateNewSection(String name)
at System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement`1.DeserializeElementCore(XmlReader reader)
at System.ServiceModel.Configuration.ServiceModelExtensionCollectionElement`1.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.ConfigurationElementCollection.OnDeserializeUnrecognizedElement(String elementName, XmlReader reader)
at System.Configuration.ConfigurationElement.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.ConfigurationElement.DeserializeElement(XmlReader reader, Boolean serializeCollectionKey)
at System.Configuration.ConfigurationSection.DeserializeSection(XmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
In regards to the process that we use to deploy our product, we use a MSI created through WiX. We perform the following steps:
Uninstall the previous version of the product
Copy the msi from a network share (same share for both versions, different subdirectory based on versions)
Install the msi as an administrator
This installs to C:\Program Files (x86)
The only changes between the 2 versions are:
The inclusion of an extra AppSettings item in the app.config file (myapp.exe.config) to specify a transaction timeout
Changing a “using new TransactionScope()” to “using New TransactionScope(TransactionScopeOption.Required, timeoutValueReadFromAppSettingsAndStoredInLocalVariable)”
The creation of the WCF client is outside of this Transaction Scope.
Additional Information:
The exception does not occur in any of our dev/staging/qa/pre production environments. It only happens on our production application server.
We are in the process of rolling out Windows 7 to our organisation, so it is possible that enterprise policy has changed.
The application targets the .Net Framework 4.0
If we uninstall the new version, and reinstall the old version (including the copy from network share) the old version works fine still
The machine being installed to is Windows Server 2008 R2
The machine is a Virtual Machine that is hosted in a VMWare environment
Ideally I’d like to know a few things:
How to alter the assembly (or set permissions after install) so that it can run in a full trust mode
How to replicate the issue in dev/staging/QA environments
Explicitly "untrusting" the assembly might reproduce it, but I want to reproduce it in the same way as production so that when it is installed it is identified as untrusted, it seems to me that the way to do this would have something to do with “untrusting” the network share I copy the MSI from, or possibly “untrusting” the publisher information in the MSI/assembly.
How to configure the production application server/security policy so that future installs are fully trusted (Answering item 2 will most likely answer this)
Thanks
This is really quite odd given that the .NET 4.0 CLR does not apply CAS security policy by default, so you would actually have to make a some sort of (hopefully) deliberate change to get a locally installed command line application to be partially trusted.
Before trying to dig too deep for potential causes, could you please verify the following:
Does your app.config file contain a NetFx40_LegacySecurityPolicy element?
Is your application actually running under the 4.0 CLR on the problem machine? (If you can't modify the source to output the value of Environment.Version before the exception is thrown, Process Explorer should allow you to determine which CLR version(s) are running in your process.)

SharePoint Could not load file or assembly 'Microsoft.SharePoint.ApplicationPages "Access is Denied"

I get the following error when I access any admin feature in SharePoint 2007 such as "Site Settings" or "Create Page." When I restart the server, the error is temporarily fixed but it comes back again in relatively short time.
I've checked other questions related to this post and none of them have the answer. I assume it's security related but then why is it fixed temporarily when the server is restarted?
Update: I just restarted IIS and the issue is temporarily resolved again... so confusing. Man, I can feel this question getting the tumbleweed badge soon.
Could not load file or assembly
Microsoft.SharePoint.ApplicationPages,
Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c' or
one of its dependencies. Access is
denied. at
System.Reflection.Assembly._nLoad(AssemblyName
fileName, String codeBase, Evidence
assemblySecurity, Assembly
locationHint, StackCrawlMark&
stackMark, Boolean
throwOnFileNotFound, Boolean
forIntrospection) at
System.Reflection.Assembly.InternalLoad(AssemblyName
assemblyRef, Evidence
assemblySecurity, StackCrawlMark&
stackMark, Boolean forIntrospection)
at
System.Reflection.Assembly.InternalLoad(String
assemblyString, Evidence
assemblySecurity, StackCrawlMark&
stackMark, Boolean forIntrospection)
at
System.Reflection.Assembly.Load(String
assemblyString) at
System.Web.Configuration.CompilationSection.LoadAssembly(String
assemblyName, Boolean throwOnFail) at
System.Web.UI.TemplateParser.AddAssemblyDependency(String
assemblyName, Boolean
addDependentAssemblies) at
System.Web.UI.TemplateParser.ProcessDirective(String
directiveName, IDictionary directive)
at
System.Web.UI.TemplateParser.ParseStringInternal(String
text, Encoding fileEncoding)
I got in contact recently with someone that had the same problem. He opened a case with Microsoft and they suggested to put a copy of Microsoft.SharePoint.ApplicationPages.dll in the GAC. It may not be the best solution, but it fixes the issues.

Resources