Loading Providers in Medium Trust Mode using WebConfigurationManager

Problem:

Recently I uploaded a ASP.NET2.0 website with a hosting provider (shared environment), and started getting this error when ever I wanted to load the providers declared on the config file:

[SecurityException: Request for the permission of type
'System.Security.Permissions.FileIOPermission, mscorlib, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089' failed.]
   System.Security.CodeAccessSecurityEngine.Check(Object demand, StackCrawlMark& stackMark, Boolean
isPermSet) +0
   System.Security.CodeAccessPermission.Demand() +59
   System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean
useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs,
String msgPath, Boolean bFromProxy) +678
   System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share) +114
   System.Configuration.Internal.InternalConfigHost.StaticOpenStreamForRead(String streamName) +80
  
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.Op
enStreamForRead(String streamName, Boolean assertPermissions) +115
  
System.Configuration.Internal.InternalConfigHost.System.Configuration.Internal.IInternalConfigHost.Op
enStreamForRead(String streamName) +7
   System.Configuration.Internal.DelegatingConfigHost.OpenStreamForRead(String streamName) +10
   System.Configuration.UpdateConfigHost.OpenStreamForRead(String streamName) +42
   System.Configuration.BaseConfigurationRecord.InitConfigFromFile() +443


Background

To develop this site I used

  • ASP.NET2.0
  • MS Ajax
  • .NetTiers
  • SQL Server 2000

After doing further investigation by looking deep into the code and the internal exceptions:

 
System.Configuration.ConfigurationSchemaErrors.ThrowIfErrors(Boolean
ignoreLocal) at
System.Configuration.BaseConfigurationRecord.ThrowIfParseErrors(ConfigurationSchemaErrors
schemaErrors) at System.Configuration.Configuration..ctor(String
locationSubPath, Type typeConfigHost, Object[]
hostInitConfigurationParams) at
System.Configuration.Internal.InternalConfigConfigurationFactory.System.Configuration.Internal.IInter
nalConfigConfigurationFactory.Create(Type
typeConfigHost, Object[] hostInitConfigurationParams) at
System.Web.Configuration.WebConfigurationHost.OpenConfiguration(WebLevel
webLevel, ConfigurationFileMap fileMap, VirtualPath path, String site,
String locationSubPath, String server, String userName, String
password, IntPtr tokenHandle) at
System.Web.Configuration.WebConfigurationManager.OpenWebConfigurationImpl(WebLevel
webLevel, ConfigurationFileMap fileMap, String path, String site,
String locationSubPath, String server, String userName, String
password, IntPtr userToken) at
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(String
path) at Something.DataAccessLayer.DataRepository.LoadProviders() in
DataRepository.cs:line

I figured out the following line of code is failing in the DataRepository.cs of .NetTiers, where it is trying to load the Configuration Object using the System.Configuration.WebConfigurationManager.

Configuration  config = System.Configuration.WebConfigurationManager.OpenWebConfiguration("~");

In this case .Nettiers DataRepository.cs tries to loads the config and then iterates through the sections and finds the desired section by using the Object Model. Infact it tries to load all the .nettiers related providers by iterating through the config sections.

An example may be ".NetTier config section".

<configSections>
  <section name="netTiersService" type="Something.DataAccessLayer.Bases.NetTiersServiceSection, Something.DataAccessLayer" allowDefinition="MachineToApplication" restartOnExternalChanges="true" />
Microsoft.Practices.EnterpriseLibrary.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null"/>
</configSections>

<netTiersService defaultProvider="SqlNetTiersProvider">
  <providers>
    <add name="SqlNetTiersProvider" type="Something.DataAccessLayer.SqlClient.SqlNetTiersProvider, Something.DataAccessLayer.SqlClient" connectionStringName="SomethingConnectionString" useStoredProcedure="false" providerInvariantName="System.Data.SqlClient"/>
  </providers>
</netTiersService>


Replicating the same error in Development Environment:

After doing a bit of googling I soon realised the above piece of code requires <trust level ="Full"/>

Probably the web hosting provider is running the application in "Medium" trust level and its causing the issue.

To successfully replicate the same error in development environment I added  <trust level="Medium"> in my web.config.
<system.web>
  <trust level="Medium"/>
  ...
</system.web>


This made life easier to solve the issue when I replicated the same error in the dev environment.

Solution

To fix the issue I used WebConfigurationManager.GetSection instead of WebConfigurationManager.OpenWebConfiguration which runs fine in the trust level "Medium". Here is the code.

ConfigurationSection ntsSection = (ConfigurationSection)WebConfigurationManager.GetSection("netTiersService");


also needed to add the requiredPermission = "false" attribute in web.config files in the section name "netTierService".

<section name="netTiersService" type="Something.DataAccessLayer.Bases.NetTiersServiceSection, Something.DataAccessLayer" allowDefinition="MachineToApplication" restartOnExternalChanges="true" requirePermission="false"/>

Conclusion

Bottom line is if we want to load the providers using the WebConfigurationManager in a medium trust mode, we need to make sure that we use "System.Configuration.WebConfigurationManager.GetSection" Method instead of "System.Configuration.WebConfigurationManager.OpenWebConfiguration" method. And make sure the section node has requiredPermission="false" defined. This should work in Medium Trust Level.

Published Mon, Jul 16 2007 1:17 by shahed

Comments

# re: Loading Providers in Medium Trust Mode using WebConfigurationManager

Wednesday, July 25, 2007 4:21 AM by Pritam Baldota

Dear Shahed,

this is very good article. my problem is similar to this only. I have shared hosting and i want to consume RSS from the other web site. I got the WebPermission error due to medium trust level. my vendor is not changing the trust level.

See this URL-

market.pritambaldota.com/rss.aspx

Plese tell me how to access the outside url data like RSS, CSV, WebRequest and WebResponse.

Thanks Very much in advance.

Pritam

# re: Loading Providers in Medium Trust Mode using WebConfigurationManager

Tuesday, September 18, 2007 10:20 AM by Rajamani

this is what i hunting for days

but i have already my code like

public static NetTiersServiceSection NetTiersSection

{

get

{

// Try to get a reference to the default <netTiersService> section

_section = WebConfigurationManager.GetSection("netTiersService") as NetTiersServiceSection;

if ( _section == null )

{

// otherwise look for section based on the assembly name

_section = WebConfigurationManager.GetSection("myapp.Common.myappData") as NetTiersServiceSection;

}

if ( _section == null )

{

throw new ProviderException("Unable to load NetTiersServiceSection");

}

return _section;

}

}

on seeing your article i also added

requirePermission="false"  on web.config

still i have same error

# re: Loading Providers in Medium Trust Mode using WebConfigurationManager

Wednesday, September 19, 2007 1:07 AM by Bruce L

I am getting the erorr as bellow

Do u have any suggestions?

Server Error in '/' Application.

--------------------------------------------------------------------------------

Required permissions cannot be acquired.

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.Security.Policy.PolicyException: Required permissions cannot be acquired.

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:

[PolicyException: Required permissions cannot be acquired.]

  System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Boolean checkExecutionPermission) +2709488

  System.Security.SecurityManager.ResolvePolicy(Evidence evidence, PermissionSet reqdPset, PermissionSet optPset, PermissionSet denyPset, PermissionSet& denied, Int32& securitySpecialFlags, Boolean checkExecutionPermission) +57

[FileLoadException: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' 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) +211

  System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +141

  System.Reflection.Assembly.Load(String assemblyString) +25

  System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +32

[ConfigurationErrorsException: Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]

  System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +596

  System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +3596761

  System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +46

  System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +177

  System.Web.Compilation.BuildProvidersCompiler..ctor(VirtualPath configPath, Boolean supportLocalization, String outputAssemblyName) +180

  System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean isPrecompiledApp) +3561465

  System.Web.Compilation.BuildManager.CompileGlobalAsax() +51

  System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +462

[HttpException (0x80004005): Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]

  System.Web.Compilation.BuildManager.ReportTopLevelCompilationException() +57

  System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled() +612

  System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters) +521

[HttpException (0x80004005): Could not load file or assembly 'Microsoft.Practices.EnterpriseLibrary.Caching.Cryptography, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. Failed to grant minimum permission requests. (Exception from HRESULT: 0x80131417)]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +3540923

  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +69

  System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +275

--------------------------------------------------------------------------------

Version Information: Microsoft .NET Framework Version:2.0.50727.832; ASP.NET Version:2.0.50727.832

# re: Loading Providers in Medium Trust Mode using WebConfigurationManager

Friday, October 26, 2007 5:20 PM by Dev

Wow!

Thanks Shahed. That helped.

My problem has been resolved. thanks for giving pointers!

Powered by Community Server (Commercial Edition), by Telligent Systems