Data Access Block in medium trust environment...

Topics: Data Access Application Block, General discussion
Jul 1, 2010 at 8:49 PM
Edited Jul 1, 2010 at 8:50 PM

Hi,

 I am trying to use EntLib 5.0 on a new project.

Currently just have the data access block hooked up. Went to deploy it to our shared environment (that is setup as medium trust) and got the following exception:

Security Exception Description: The application attempted to perform an operation not allowed by the security policy. To grant this application the required permission please contact your system administrator or change the application's trust level in the configuration file.

Exception Details: System.Security.SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.

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: [SecurityException: Request for the permission of type 'System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' failed.] System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) +150 System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) +100 System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Object assemblyOrString, SecurityAction action, Boolean throwException) +284 System.Security.PermissionSetTriple.CheckSetDemand(PermissionSet demandSet, PermissionSet& alteredDemandset, RuntimeMethodHandle rmh) +69 System.Security.PermissionListSet.CheckSetDemand(PermissionSet pset, RuntimeMethodHandle rmh) +150 System.Security.PermissionListSet.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet) +30 System.Threading.CompressedStack.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet) +40 System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant, CompressedStack securityContext) +123 System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant, Resolver accessContext) +41

Any ideas on how to get around this?

thanks! Chris

Jul 2, 2010 at 1:13 AM

The list of permissions that may be required by DAAB under medium trust is included in the documentation.  Refer to this link.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 2, 2010 at 4:09 AM

Thanks for the info... I looked at everything and don't see anything that seems to relate to this exception and the need for reflection.

Has anyone tried to use 5.0 and the data access block in a medium trust environment?

thanks,

Chris

Jul 2, 2010 at 4:25 AM

Is this an ASP.NET application? Because if yes, ReflectionPermission is not available as mentioned here.  With that, I suggest looking into this or posting this in other asp.net forums.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 2, 2010 at 5:38 AM
Edited Jul 2, 2010 at 5:38 AM

It is an ASP.NET application.  I have seen that page that states that reflection is not permitted in a medium trust environment, but I am not using it in my code... I figured it was being used by the Enterprise Library somewhere.  Do you know if thats the case?  If so, is there any other way around it?

If reflection permission is required by the enterprise library in medium trust I'm surprised its not documented somewhere.

Thanks for all your info and help in this too!

Chris

 

Jul 6, 2010 at 8:22 AM

Yes, I believe reflection was used in entlib somewhere but I cannot tell if this is really the one that is hurting since as you have stated I haven't also seen this included (specifically reflection) in the documentation (Customizing the Medium Trust Policy). Though, I'm curious where exactly the exception mentioned was raised, would you know the exact line of code?

I've tried to reproduce it in a simple web app using only Data Access and with Medium trust level setup but I've got a different exception message upon instantiating a Database object "Request for ConfigurationPermission failed while attempting to access configuration section 'dataConfiguration'. To allow all callers to access the data for this section, set section attribute 'requirePermission' equal 'false' in the configuration file where this section is declared." but this can be easily addressed setting the requirePermission attribute of the DAAB config section to False.

Gino Terrado
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

 

 

Jul 13, 2010 at 6:28 PM

Sorry, it has taken a few days to get back to this...

I think I know where the problem is and why reflection is necessary.  Here is the code...

 Public Shared Function GetDB() As Database

 Try
     Dim objDatabase As Database = Nothing
     Dim sEnvironment As String = ConfigurationManager.AppSettings("Environment").ToString().ToLower()
     objDatabase = EnterpriseLibraryContainer.Current.GetInstance(Of Database)(sEnvironment)
     Return objDatabase
 Catch ex As Exception
     Throw New Exception("Failed to get db instance: " + ex.Message)
 End Try

End Function

I want to be able to use a database vendor independent connection.  I use the environment and configuration setup to have EntLib handle getting me the correct db instance type.  This generates the following exception.

 

Failed to get db instance:

Resolution of the dependency failed, type =
"Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator+LifetimeInspector"
, name = "(none)".Exception occurred while: while resolving.Exception is: TypeLoadException - Could not load type
'Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator' from assembly
'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=
31bf3856ad364e35'.-----------------------------------------------At the time of the exception, the container was:  Resolving
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator+LifetimeInspector,(none)

What do you think?

thanks again!

Chris

Jul 14, 2010 at 6:55 AM

What specific line of code generates this error?  

Since I'm not able to repro your error, could you try running this in a full trust environment?  Just to see if this error is related or not to the fact that you're running under medium trust.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 14, 2010 at 7:59 PM

The exact line generating this error is:

objDatabase = EnterpriseLibraryContainer.Current.GetInstance(Of Database)(sEnvironment)

It works in my local development environment, but I am getting the error when I try to run it in our medium trust production environment.

Thanks,

Chris

Jul 15, 2010 at 6:16 AM
csiege wrote:

Sorry, it has taken a few days to get back to this...

I think I know where the problem is and why reflection is necessary.  Here is the code...

 Public Shared Function GetDB() As Database

 Try
     Dim objDatabase As Database = Nothing
     Dim sEnvironment As String = ConfigurationManager.AppSettings("Environment").ToString().ToLower()
     objDatabase = EnterpriseLibraryContainer.Current.GetInstance(Of Database)(sEnvironment)
     Return objDatabase
 Catch ex As Exception
     Throw New Exception("Failed to get db instance: " + ex.Message)
 End Try

End Function

I want to be able to use a database vendor independent connection.  I use the environment and configuration setup to have EntLib handle getting me the correct db instance type.  This generates the following exception.

 

Failed to get db instance:

Resolution of the dependency failed, type =
"Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator+LifetimeInspector"
, name = "(none)".Exception occurred while: while resolving.Exception is: TypeLoadException - Could not load type
'Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator' from assembly
'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=
31bf3856ad364e35'.-----------------------------------------------At the time of the exception, the container was:  Resolving
Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator+LifetimeInspector,(none)

What do you think?

thanks again!

Chris

Hi Chris,

The exception raised in here looks to be different from your initially reported exception encountered. I'm curious what is the value of your "ConfigurationManager.AppSettings("Environment")" which you have assigned as the Connection String name on instantiating your database object. Note that you can directly supply your Connection String name in here. Also, have you tried configuring the requirePermission attribute of the DAAB config section to False when running it in your medium trust environment?

Given that we’re not able to reproduce the problem, do you have any sample app that can repro this? It’ll be very helpful to us so we can be able to further investigate your problem.

Gino Terrado
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

 

Jul 15, 2010 at 6:39 PM

Well, I'm not sure why but this latest exception is what I am getting when I try to deploy.  It works locally.  I do not have the EntLib assemblies in the GAC, but I didn't think I needed to.  I just about to abandon the thought of using EntLib for this proejct... :-(

I have a sample app.  Not sure how to get it to you.

Very small one page web app. Details below...

Thanks for all your help!
Chris

 

I have the following references in the webapp... am I missing anything?:

Microsoft.Practices.EnterpriseLibrary.Common
Microsoft.Practices.EnterpriseLibrary.Data
Microsoft.Practices.ServiceLocation
Microsoft.Practices.Unity
Microsoft.Practices.Unity.Interception

 

Code behind is:

 

Imports Microsoft.Practices.EnterpriseLibrary.Data
Imports Microsoft.Practices.EnterpriseLibrary.Common.Configuration
Imports System.Data.Common

Partial Public Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Dim objDatabase As Database = Nothing
        Try
            objDatabase = EnterpriseLibraryContainer.Current.GetInstance(Of Database)("dev")
            txtResults.Text = objDatabase.ConnectionString
        Catch ex As Exception
            txtResults.Text = "Failed to get db instance: " + ex.Message
        End Try

    End Sub

End Class

 

 

webconfig is:

 

<?xml version="1.0"?>

<configuration>
 

    <configSections>
      <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
      <sectionGroup name="system.web.extensions" type="System.Web.Configuration.SystemWebExtensionsSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
        <sectionGroup name="scripting" type="System.Web.Configuration.ScriptingSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="scriptResourceHandler" type="System.Web.Configuration.ScriptingScriptResourceHandlerSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication"/>
          <sectionGroup name="webServices" type="System.Web.Configuration.ScriptingWebServicesSectionGroup, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="jsonSerialization" type="System.Web.Configuration.ScriptingJsonSerializationSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="Everywhere" />
            <section name="profileService" type="System.Web.Configuration.ScriptingProfileServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="authenticationService" type="System.Web.Configuration.ScriptingAuthenticationServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
            <section name="roleService" type="System.Web.Configuration.ScriptingRoleServiceSection, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" allowDefinition="MachineToApplication" />
          </sectionGroup>
        </sectionGroup>
      </sectionGroup>
    </configSections> 

 

    <dataConfiguration defaultDatabase="dev" />
    <connectionStrings>
        <add name="dev" connectionString="Data Source=SERVERNAMEHERE;Initial Catalog=DBNAME;User ID=USER;Password=PASSWORD"
            providerName="System.Data.SqlClient" />
    </connectionStrings>
    <system.web>
        <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.

            Visual Basic options:
            Set strict="true" to disallow all data type conversions
            where data loss can occur.
            Set explicit="true" to force declaration of all variables.
        -->
        <compilation debug="false" strict="false" explicit="true">

          <assemblies>
            <add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
            <add assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add assembly="System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
          </assemblies>

        </compilation>
        <pages>
          <namespaces>
            <clear />
            <add namespace="System" />
            <add namespace="System.Collections" />
            <add namespace="System.Collections.Generic" />
            <add namespace="System.Collections.Specialized" />
            <add namespace="System.Configuration" />
            <add namespace="System.Text" />
            <add namespace="System.Text.RegularExpressions" />
            <add namespace="System.Linq" />
            <add namespace="System.Xml.Linq" />
            <add namespace="System.Web" />
            <add namespace="System.Web.Caching" />
            <add namespace="System.Web.SessionState" />
            <add namespace="System.Web.Security" />
            <add namespace="System.Web.Profile" />
            <add namespace="System.Web.UI" />
            <add namespace="System.Web.UI.WebControls" />
            <add namespace="System.Web.UI.WebControls.WebParts" />
            <add namespace="System.Web.UI.HtmlControls" />
          </namespaces>

          <controls>
            <add tagPrefix="asp" namespace="System.Web.UI" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
            <add tagPrefix="asp" namespace="System.Web.UI.WebControls" assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
          </controls>

        </pages>
        <!--
            The <authentication> section enables configuration
            of the security authentication mode used by
            ASP.NET to identify an incoming user.
        -->
        <authentication mode="Windows" />
        <!--
            The <customErrors> section enables configuration
            of what to do if/when an unhandled error occurs
            during the execution of a request. Specifically,
            it enables developers to configure html error pages
            to be displayed in place of a error stack trace.

        <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
            <error statusCode="403" redirect="NoAccess.htm" />
            <error statusCode="404" redirect="FileNotFound.htm" />
        </customErrors>
        -->

      <httpHandlers>
        <remove verb="*" path="*.asmx"/>
        <add verb="*" path="*.asmx" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="*" path="*_AppService.axd" validate="false" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" validate="false"/>
      </httpHandlers>
      <httpModules>
        <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </httpModules>


    </system.web>

    <system.codedom>
      <compilers>
        <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" warningLevel="4"
                  type="Microsoft.VisualBasic.VBCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
          <providerOption name="CompilerVersion" value="v3.5"/>
          <providerOption name="OptionInfer" value="true"/>
          <providerOption name="WarnAsError" value="false"/>
        </compiler>
      </compilers>
    </system.codedom>

    <!--
        The system.webServer section is required for running ASP.NET AJAX under Internet
        Information Services 7.0.  It is not necessary for previous version of IIS.
    -->
    <system.webServer>
      <validation validateIntegratedModeConfiguration="false"/>
      <modules>
        <remove name="ScriptModule" />
        <add name="ScriptModule" preCondition="managedHandler" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
      </modules>
      <handlers>
        <remove name="WebServiceHandlerFactory-Integrated"/>
        <remove name="ScriptHandlerFactory" />
        <remove name="ScriptHandlerFactoryAppServices" />
        <remove name="ScriptResource" />
        <add name="ScriptHandlerFactory" verb="*" path="*.asmx" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptHandlerFactoryAppServices" verb="*" path="*_AppService.axd" preCondition="integratedMode"
             type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>
        <add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
      </handlers>
    </system.webServer>

    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
        <dependentAssembly>
          <assemblyIdentity name="System.Web.Extensions.Design" publicKeyToken="31bf3856ad364e35"/>
          <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="3.5.0.0"/>
        </dependentAssembly>
      </assemblyBinding>
    </runtime>

</configuration>

Jul 16, 2010 at 4:18 AM

Could you check if there's an inner exception?  Are you sure the entlib assemblies aren't GAC'd or at least the Data assembly? Make sure the Copy Local property is set to True for the Data reference.

 

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 16, 2010 at 4:49 AM

Here is the inner exception:

Could not load type 'Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.Unity.UnityContainerConfigurator' from assembly 'Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

All the EntLib assemblies have copy local set to true....

I don't think any of the files are GAC'd.

Chris

Jul 16, 2010 at 6:28 AM
Edited Jul 16, 2010 at 6:48 AM

I am simulating a medium trust environment by adding <trust level="Medium" /> under <system.web>.  Could you try adding this in your config and run it in your local dev environment and see if you can repro the error you're getting after deployment?  Coz right now, we're really unable to repro this scenario. 

 I remember this post which concerns the same exception as yours but I don't see any similarity in the setup of your application, any chance you could?

Could you also tell me what did you exactly do to get pass the securityexception you initially encoutered?

Sarah Urmeneta
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com

Jul 20, 2010 at 9:58 PM

Unfortunately I have no idea what I did to get pass the securityexception I had initially...

I tried to reproduce the "Could not load type" problem on my local machine using the trust settings from our hosted environment.  I could not.  EXCEPT I could reproduce it if I set the trust level to "Low".  I really hope this helps. 

I have tried everything else I can think of.  I even rebuilt the EntLib source code and references those dll's and that didn't work.

Let me know if you can think of anything else I can try.

thanks,

Chris

 

 

Jul 21, 2010 at 12:34 PM

Chris,

You're right, this can be reproduce using trust level "Low". Upon reproducing the problem I've noticed that the "Could not load type" and "System.Security.Permissions.ReflectionPermission" that you have encountered seems only pertaining to one/same exception. This comes to my assumption that you never really did pass thru the SecurityException.

Anyway, I was able to resolve this in my machine by modifying the specific trust level configuration to add the ReflectionPermission in the Security class of the config. I'm not really sure if this is also the case in your hosted environment but I hope it'll help. Below are the steps;

1. Open the web_lowtrust.config found in X:\<windows>\Microsoft.NET\Framework\<version>\CONFIG (since what I'm using in my Web Application's web.config is <trust level="Low"/>)

2. Add ReflectionPermission class in the SecurityClass list/node. Add the section below.    

       <SecurityClass Name="ReflectionPermission"

               Description="System.Security.Permissions.ReflectionPermission, mscorlib, Version=2.0.0.0, Culture=neutral,

               PublicKeyToken=b77a5c561934e089"/>

 

3. Add ReflectionPermission in the PermissionSet. Add the section below.

     <IPermission class="ReflectionPermission"

             version="1"

             Unrestricted="true" />

 

4. Save the configuration then test your web application.

For more info you can also check this blog http://www.west-wind.com/Weblog/posts/5587.aspx. HTH.

Gino Terrado
Global Technology and Solutions
Avanade, Inc.
entlib.support@avanade.com