22

Is it possible to check, from within solution, if it was deployed as sandboxed or not, e.g. something like this:

if(this.IamSandboxedSolution)
    // do something
else
    // do something else

3 Answers 3

18

Not out-of-the-box AFAIK.

You could check it like this:

if(AppDomain.CurrentDomain.FriendlyName ==
    "Sandboxed Code Execution Partially Trusted Asp.net AppDomain") {
    // I'm playing in the sandbox!
}
5
  • Good hack, but sounds like something that will break in the future. Mar 26, 2010 at 6:30
  • Yea, unfortunatley you cannot check the actual name of the process since that is not allowed. It will throw a SecurityException. Mar 26, 2010 at 7:36
  • Awesome stuff! I really need to read your book as soon as possible :) Mar 26, 2010 at 9:03
  • Could break, true. To minimise that risk, you would obviously make that string configurable. Mar 26, 2010 at 10:46
  • yup, e.g. in Beta2 it was called "User Code Execution Partially Trusted Asp.net AppDomain". But this will be okey. Mar 26, 2010 at 15:17
16

AFAIK there is no foolproof way to do this unfortunately. I know Microsoft's SharePoint Patterns & Practices team are using:

AppDomain.CurrentDomain.FriendlyName.Contains("Sandbox")

So if that's the best they've come up with, it's fair to say that's as good as it gets. Obviously some static helper method is the way to go rather than having this check littered through your code.

EDIT: IMHO this is far preferable to running some forbidden code and catching the exception, due to perf reasons.

4

Another equally hacky approach would be to try to do something that isn't allowed in the sandbox and catch the resulting exception. Something like this:

static bool? _isSandboxed;
static bool IsSandboxed() {
    if(!_isSandboxed.HasValue) {
        try {
            SPSecurity.RunWithElevatedPrivileges(delegate { });
            _isSandboxed = false;
        } catch (PolicyException) {
            _isSandboxed = true;
        }
    }
    return _isSandboxed.Value;
}
4
  • Yea, that's another approach but like mine it can fail. Assume that you deploy an application to the WebApplication (bin) and disallow RWEP with CAS? Mar 26, 2010 at 10:18
  • You're right, and I was only half serious about this, anyway. :-)
    – Rytmis
    Mar 26, 2010 at 13:33
  • Btw. while I agree that this isn't a good solution, saying that it's because of poor performance is silly. This code throws a single exception once (possibly twice, allowing for race conditions). That's not very expensive.
    – Rytmis
    Mar 26, 2010 at 18:23
  • I dont like using exceptions to check if somthing is there or not. Jun 24, 2011 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.