Friday, June 01, 2012

MS CRM 2011: CallerOrigin in plugins

Yesterday well-known MVP Tanguy Touzard, author of amazing tools for Dynamics CRM 4.0/2011 asked about CallerOrigin property in plugins for Dynamics CRM 2011. This property worked for CRM 4.0 and returned the source of plugin invocation (Application, AsyncService or WebService). I and Gayan suggested to use HttpContext class from System.Web namespace to check source.
 Today during debug of one plugin in QuickWatch window I have seen that CallerOrigin property is still in context but it is not property of IPluginExecutionContext:



Following class is helper which allows you easily get origin of plugin invocation:
namespace CallerOrigin.Plugins
{
    internal enum CallerOrigin : int
    {
        Undefind = 0,
        Application = 1,
        WebService = 2,
        AsyncService = 3
    }

    internal class CallerOriginHelper
    {
        internal static CallerOrigin GetCallerOrigin(
            Microsoft.Xrm.Sdk.IPluginExecutionContext context)
        {
            if (context.GetType().Name == "SandboxPluginExecutionContext")
                return CallerOrigin.Undefind;

            object callerorigin = 
                context.GetType().GetProperty("CallerOrigin").GetValue(context, null);

            switch (callerorigin.GetType().Name)
            {
                case "ApplicationOrigin":
                    return CallerOrigin.Application;
                case "AsyncServiceOrigin":
                    return CallerOrigin.AsyncService;
                case "WebServiceApiOrigin":
                    return CallerOrigin.WebService;
            }

            return CallerOrigin.Undefind;
        }
    }
}

Here is a sample how to use this helper:

var callerorigin = CallerOriginHelper.GetCallerOrigin(localContext.PluginExecutionContext);

Unfortunately this solution works only for plugins that are not registered in Isolation, so for CRM Online it would not work - Undefined value would be returned.