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
Toni Frankola
  • 4,319
  • 28
  • 38

3 Answers3

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!
}
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.

Chris O'Brien - MVP
  • 3,655
  • 18
  • 14
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;
}
Rytmis
  • 186
  • 6
  • 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? – Wictor Wilen MCA MCM MVP Mar 26 '10 at 10:18
  • You're right, and I was only half serious about this, anyway. :-) – Rytmis Mar 26 '10 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 '10 at 18:23
  • I dont like using exceptions to check if somthing is there or not. – Heiko Hatzfeld_MSFT Jun 24 '11 at 15:45