tags:

views:

42

answers:

2

Hi! The following code works but it uses a security demand, which in my application all too often often leads to a SecurityException being thrown. As you can see the code handles this just fine but I'd like to speed it up if possible. Any suggestions on how to improve things would be greatly appreciated!

using System.Security;
using System.Web;

namespace MyProject
{
    internal static class TrustHelper
    {
        public static bool IsHighlyTrusted()
        {
            try
            {
                AspNetHostingPermission permission =
                    new AspNetHostingPermission(
                        AspNetHostingPermissionLevel.High);

                permission.Demand();

                return true;
            }
            catch (SecurityException)
            {
                return false;
            }
        }
    }
}
+1  A: 

Why not just calculate the value once in the static initialiser and store the result?

Security "evidence" in .NET is gathered when an assembly loads, and is used to determine permissions. Hence, permissions do not change during the lifetime of an assembly, and can be determined upon startup.

internal static class TrustHelper
{
    static TrustHelper()
    {
        try
        {
            var permission = new AspNetHostingPermission(
                AspNetHostingPermissionLevel.High);
            permission.Demand();

            TrustHelper.IsHighlyTrusted = true;
        }
        catch (SecurityException)
        {
            TrustHelper.IsHighlyTrusted = false;
        }
    }

    public static bool IsHighlyTrusted()
    {
        get;
        private set;
    }
}
Noldorin
+1  A: 

Use the SecurityManager ...

var perm = new AspNetHostingPermission( AspNetHostingPermissionLevel.High );
var hasPerm = System.Security.SecurityManager.IsGranted( perm );
JP Alioto
Any reason for the down vote?
JP Alioto