October 5, 2013

Get the current user inside a Workflow

Inside CRM 2011 Process editor it's not possible to get the current user, in some cases a reference can be necessary (specially for automated workflows) in order to set the right user when the workflow is used to create or assign records.
A Custom Workflow Activity can be created for this purpose, taking advantage of the InitiatingUserId property.
using System;
using System.Activities;
using System.Collections.Generic;
using System.Runtime.Serialization;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;

namespace WFUtils
{
    public class GetCurrentUser : CodeActivity
    {
        [Output("Current User")]
        [ReferenceTarget("systemuser")]
        public OutArgument<EntityReference> CurrentUser { get; set; }
        protected override void Execute(CodeActivityContext context)
        {
            IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
            CurrentUser.Set(context, new EntityReference("systemuser", workflowContext.InitiatingUserId));

        }
    }
}
After the Custom Activity is deployed using the Plugin Registration Tool, a new step is available

and the output parameter (Current User) can be used inside other steps


5 comments:

  1. Hello.

    I have a little problem after Register the new assembly with help of the Plugin Registration Tool.

    Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: The type OutArgument of the property CurrentUser is not supported.
    Detail:
    -2147200995


    CallStack
    at Microsoft.Crm.Extensibility.VersionedPluginProxyStepBase.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.Pipeline.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.MessageProcessor.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.InternalMessageDispatcher.Execute(PipelineExecutionContext context)
    at Microsoft.Crm.Extensibility.ExternalMessageDispatcher.ExecuteInternal(IInProcessOrganizationServiceFactory serviceFactory, IPlatformMessageDispatcherFactory dispatcherFactory, String messageName, String requestName, Int32 primaryObjectTypeCode, Int32 secondaryObjectTypeCode, ParameterCollection fields, CorrelationToken correlationToken, CallerOriginToken originToken, UserAuth userAuth, Guid callerId, Guid transactionContextId, Int32 invocationSource, Nullable`1 requestId, Version endpointVersion)
    at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.ExecuteRequest(OrganizationRequest request, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)
    at Microsoft.Crm.Extensibility.OrganizationSdkServiceInternal.Create(Entity entity, CorrelationToken correlationToken, CallerOriginToken callerOriginToken, WebServiceType serviceType)


    The type OutArgument of the property CurrentUser is not supported.
    2014-02-07T11:04:51.8339154Z

    -2147200995


    CallStack
    at Microsoft.Crm.ObjectModel.WorkflowActivityValidator.ValidateDotNet4CustomActivity(Type activityType)
    at Microsoft.Crm.ObjectModel.PluginValidatorBase.Validate()
    at Microsoft.Crm.ObjectModel.PluginTypeValidator.ValidateInternal()
    at Microsoft.Crm.ObjectModel.PluginValidatorBase.Validate()
    at Microsoft.Crm.ObjectModel.PluginTypeServiceInternal`1.Create(IBusinessEntity entity, ExecutionContext context)


    The type OutArgument of the property CurrentUser is not supported.
    2014-02-07T11:04:51.8339154Z






    Server stack trace:
    at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
    at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
    at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

    Exception rethrown at [0]:
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
    at Microsoft.Xrm.Sdk.IOrganizationService.Create(Entity entity)
    at Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy.CreateCore(Entity entity)
    at PluginRegistrationTool.RegistrationHelper.RegisterPlugin(CrmOrganization org, CrmPlugin plugin)
    at PluginRegistrationTool.PluginRegistrationForm.btnRegister_Click(Object sender, EventArgs e)

    ReplyDelete
    Replies
    1. Hi Karsten,
      please check again the code, the syntax highlighter removed some characters by mistake, I updated it.

      Delete
  2. Hi Karsten,
    which version is your instance? CRM 2011 or 2013? online or onpremise? are you using the plugin registration tool from the latest sdk?

    ReplyDelete
  3. Thanks a lot for this useful information, I didn't find it anywhere else!

    ReplyDelete