LLBLGen to Linq in Medium trust

Posts   
 
    
khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 14:50:04   

Hi,

we have another issue related to LLBLGen in medium trust and it is related to LLBLGen to Linq. Here is the exception that we get:

System.MethodAccessException was unhandled by user code
  Message="System.Runtime.CompilerServices.StrongBox`1..ctor(System.__Canon)"
  Source="mscorlib"
  StackTrace:
       at System.Reflection.MethodBase.PerformSecurityCheck(Object obj, RuntimeMethodHandle method, IntPtr parent, UInt32 invocationFlags)
       at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture, Object[] activationAttributes)
       at System.Linq.Expressions.ExpressionCompiler.AddGlobal(Type type, Object value)
       at System.Linq.Expressions.ExpressionCompiler.GenerateConstant(ILGenerator gen, Type type, Object value, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.GenerateConstant(ILGenerator gen, ConstantExpression c, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.GenerateArgs(ILGenerator gen, ParameterInfo[] pis, ReadOnlyCollection`1 args)
       at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall(ILGenerator gen, MethodInfo mi, ReadOnlyCollection`1 args, Type objectType)
       at System.Linq.Expressions.ExpressionCompiler.GenerateMethodCall(ILGenerator gen, MethodCallExpression mc, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.GenerateConvert(ILGenerator gen, UnaryExpression u)
       at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.GenerateConvert(ILGenerator gen, UnaryExpression u)
       at System.Linq.Expressions.ExpressionCompiler.Generate(ILGenerator gen, Expression node, StackType ask)
       at System.Linq.Expressions.ExpressionCompiler.GenerateLambda(LambdaExpression lambda)
       at System.Linq.Expressions.ExpressionCompiler.CompileDynamicLambda(LambdaExpression lambda)
       at System.Linq.Expressions.LambdaExpression.Compile()
       at SD.LLBLGen.Pro.LinqSupportClasses.LLBLGenProProvider2.SetupProjectionElementsForExecution(QueryExpression toExecute)
       at SD.LLBLGen.Pro.LinqSupportClasses.LLBLGenProProvider2.ExecuteValueListProjection(QueryExpression toExecute)
       at SD.LLBLGen.Pro.LinqSupportClasses.LLBLGenProProviderBase.ExecuteExpression(Expression handledExpression)
       at SD.LLBLGen.Pro.LinqSupportClasses.LLBLGenProProviderBase.Execute(Expression expression)
       at SD.LLBLGen.Pro.LinqSupportClasses.LLBLGenProProviderBase.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
       at SD.LLBLGen.Pro.LinqSupportClasses.QueryableExtensionMethods.CountColumn[TSource,TColumnType](IQueryable`1 source, Expression`1 selector, Boolean applyDistinct)
       at MonoSoftware.MonoX.Repositories.MessageRepository.GetMessages(Guid parentMessageId, Guid userId, Int32 pageIndex, Int32 pageSize, Int32& recordCount) in D:\Projects\MonoX2\Portal\MonoX\Code\Layers\Repositories\MessageRepository.cs:line 222
       at MonoSoftware.MonoX.ModuleGallery.SocialNetworking.MessageDetails.BindData() in D:\Projects\MonoX2\Portal\MonoX\ModuleGallery\SocialNetworking\Messaging\MessageDetails.ascx.cs:line 217
       at MonoSoftware.MonoX.ModuleGallery.SocialNetworking.MessageDetails.Page_Load(Object sender, EventArgs e) in D:\Projects\MonoX2\Portal\MonoX\ModuleGallery\SocialNetworking\Messaging\MessageDetails.ascx.cs:line 174
       at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
       at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
       at System.Web.UI.Control.OnLoad(EventArgs e)
       at MonoSoftware.MonoX.BasePart.OnLoad(EventArgs e) in D:\Projects\MonoX2\Portal\MonoX\Code\BaseClasses\BasePart.cs:line 1112
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Control.LoadRecursive()
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
  InnerException: System.Security.SecurityException
       Message="Request failed."
       Source="mscorlib"
       StackTrace:
            at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
            at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Object assemblyOrString, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed)
            at System.Security.CodeAccessSecurityEngine.CheckSetHelper(PermissionSet grants, PermissionSet refused, PermissionSet demands, RuntimeMethodHandle rmh, Object assemblyOrString, SecurityAction action, Boolean throwException)
            at System.Security.PermissionSetTriple.CheckSetDemand(PermissionSet demandSet, PermissionSet& alteredDemandset, RuntimeMethodHandle rmh)
            at System.Security.PermissionListSet.CheckSetDemand(PermissionSet pset, RuntimeMethodHandle rmh)
            at System.Security.PermissionListSet.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet)
            at System.Threading.CompressedStack.DemandFlagsOrGrantSet(Int32 flags, PermissionSet grantSet)
            at System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant, CompressedStack securityContext)
            at System.Security.CodeAccessSecurityEngine.ReflectionTargetDemandHelper(Int32 permission, PermissionSet targetGrant)
       InnerException: 

I have found a few posts related to the exception that we get, and all of them are suggesting the change in the configuration that we can do because Microsoft is moving towards this medium trust configuration:

<IPermission  class="ReflectionPermission" version="1" Flags="RestrictedMemberAccess"/>

Which will be required if we want to include our product in Microsoft application gallery.

The code that we are using is when we get the exception is:


using (IDataAccessAdapter dataAdapter = GetAdapter())
            {
                LinqMetaData metaData = new LinqMetaData(dataAdapter);
                var q = (from topics in metaData.SnDiscussionTopic
                         where topics.SnDiscussionBoardId == boardId
                         select topics).Count();
                return q;
            }

I have seen the http://www.llblgen.com/TinyForum/Messages.aspx?ThreadID=19640 thread but for us it is unacceptable to move to the 3.x version, we are bound to the 2.6 version.

Is there anything that we can do to fix this issue ?

Our previous topic on medium trust http://www.llblgen.com/TinyForum/Messages.aspx?ThreadID=19685

Regards

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 18-May-2011 16:02:55   

IMHO, you have 2 options: 1- Move to 3.x version. (You said you can't). 2- Use LLBLGen's native query APIs instead of Linq.

khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 16:08:57   

I have reviewed the http://www.llblgen.com/TinyForum/Messages.aspx?ThreadID=19640 and as Frans said:

Linq To use Linq, the service provider has to have enabled ReflectionPermission to be unrestricted. This is in general the case, as Entity Framework and Linq to Sql require this setting to be unrestricted. It's a change in the Medium Trust level, so it's not enabled by default when the default Medium Trust is selected. If your service provider doesn't want to enable ReflectionPermission to be unrestricted, you have to use our native query API instead of Linq. Linq uses compiled lambda's and this .NET 3.5 feature requires ReflectionPermission to be unrestricted.

And take a close look at .NET 3.5 feature requires ReflectionPermission to be unrestricted, and I said that Microsoft application gallery will require us ti use

<IPermission class="ReflectionPermission" version="1" Flags="RestrictedMemberAccess"/>

.

So is there any other solution to this problem ?

Regards

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 18-May-2011 16:23:06   

Yes but that was for v.3.x.

So for this to work (Medium Trust + Linq), you have to use v.3.x and enable ReflectionPermission.

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 18-May-2011 16:25:50   

I think it's caused by something similar to this: http://stackoverflow.com/questions/3194678/expressiontdelegate-compile-in-medium-trust-environment

We use lambdaExpression.Compile() a lot to produce a projection func which is usable as a projector without having to interpret the code used for a projection. As you didn't specify any custom projection, the projection we add is causing this. With the stackoverflow thread above and the info in there, we can look into if we run into the same issue (i.e. a ConstantExpression used with an internal type).

V3.x has the same problem I think.

I really do hate the way Microsoft forces this crap upon developers, time and time again. But as they won't listen nor do they give a f**k, I'll save my energy wink .

(edit) I can confirm that we run into the same issue. We obtain the type through reflection (which is allowed) but it's a 'RuntimeType' instance, which is an internal type within .NET's BCL. This means the compile method will run into the security issue.

I'll adjust the linqsupportclasses, and will attach a new build for you to test.

Frans Bouma | Lead developer LLBLGen Pro
khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 16:45:11   

Yes we are angry too, and honestly I'm sick of this medium trust b.s. but we need to solve it somehow ... I saw the stackoverflow link but as I can see we can't get to that code ... so is there anything that we can do or you need to make some code modifications on your side to get around this ?

Regards

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 18-May-2011 16:45:12   

Could you test the attached dll? It should make sure the Constant expression with the reflected type is not a RuntimeType but a Type, so compilation should succeed.

This is a debug build. If it works, I'll attach a full build. It takes a lot of time to setup a proper test environment for this problem so we didn't test whether the fix fixes your particular problem, however we changed the statement which could cause this.

Frans Bouma | Lead developer LLBLGen Pro
khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 16:46:35   

That's great, let me know when you done.

Thanks

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 18-May-2011 16:47:13   

khorvat wrote:

Yes we are angry too, and honestly I'm sick of this medium trust b.s. but we need to solve it somehow ... I saw the stackoverflow link but as I can see we can't get to that code ... so is there anything that we can do or you need to make some code modifications on your side to get around this ? Regards

You do run into that wink . The linq provider creates a lambda, like (values, indexes) => COnvert(Convert(Changetype(values[indexes[0]], Constant(System.Int32))));

The Constant(System.Int32) is the problem. We fixed that according to the stackoverflow article and I attached a new build to my previous post for you to test it out.

Frans Bouma | Lead developer LLBLGen Pro
khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 17:00:16   

Hi,

I have tested the assembly you have sent and it is working without throwing the security exception, can you send us a full build?

Thanks for super fast solution simple_smile

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 18-May-2011 17:11:49   

Glad it's sorted simple_smile (all our tests passed, so it has no influence on the functionality, just makes sure medium trust works)

See attached dll.

Out of curiosity, what kind of website / web app is it that you're adding to the MS web gallery? Always interested in what people build with LLBLGen Pro simple_smile

Frans Bouma | Lead developer LLBLGen Pro
khorvat avatar
khorvat
User
Posts: 65
Joined: 17-Feb-2011
# Posted on: 18-May-2011 17:47:27   

Hi,

we are adding the MonoX CMS (http://www.mono-software.com/MonoX-ASP-NET-CMS-Social-Networking-Platform/) to MS gallery, thanks for the quick fix it was the last thing on our medium trust list (round 2 wink of who knows how many).

Thanks

Otis avatar
Otis
LLBLGen Pro Team
Posts: 39614
Joined: 17-Aug-2003
# Posted on: 19-May-2011 11:25:17   

Looks great!

Frans Bouma | Lead developer LLBLGen Pro