View Complete Post
The challenge in SharePoint development has always been the balance between creating and deploying solutions that you can trust not to damage or impair a SharePoint farm. A new feature in SharePoint 2010, called Sandboxed Solutions, enables farm administrators to feel comfortable that the SharePoint farm is safe, gives site collection administrators the authority to manage applications in their site collection, and provides developers with the flexibility to create solutions they know will be deployed in a safe and rapid manner.
MSDN Magazine November 2009
You could execute a function call that is not allowed in the sandbox (for example call a static method on SPSecurity) and catch the exception. A better approach is to test the friendly name of you app domain:
AppDomain.CurrentDomain.FriendlyName returns "Sandboxed Code Execution Partially Trusted Asp.net AppDomain"
Because you can never be sure that this string changes in the future, a safer approach will be:
See http://www.sharepointoverflow.com/questions/2051/how-to-check-if-code-is-running-as-sandboxed-solution for a discussion on this topic.
You can't log directly from sandbox code to the SharePoint ULS log. Developing code without any form of logging is out of this time, so you need approaches for the two situations you can end up with when developing sandbox code:
You don't have control over the server (BPOS scenario):
You have control over the server: