CRM 2011: Fetch entity ID in process/workflow

Let’s say you need to fetch the GUID of an entity record in a process in order to build a link in an e-mail. The default process wizard does’nt give you this information. So you need to build your own custom workflow activitylibrary in Visual Studio.

Here’s the basic how to: http://msdn.microsoft.com/en-us/library/gg328515.aspx

And here’s the code for extracting the ID:

using System;
using System.Collections.Generic;
using System.Text;
using System.Activities;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;

namespace SYSteam.CRM._2011.ActivityLibrary
{
    public class EntityDetails : CodeActivity
    {
        [Output(“PrimaryEntityId”)]
        public OutArgument<string> PrimaryEntityId { get; set; }

        [Output(“PrimaryEntityName”)]
        public OutArgument<string> PrimaryEntityName { get; set; }

        [Output(“PageURLOut”)]
        public OutArgument<string> PageURLOut { get; set; }

        [Input(“PageURLIn”)]       
        public InArgument<string> PageURLIn { get; set; }

        protected override void Execute(CodeActivityContext codeActivityContext)
        {
            //Create the context
            IWorkflowContext workflowContext = codeActivityContext.GetExtension<IWorkflowContext>();

            PrimaryEntityId.Set(codeActivityContext, workflowContext.PrimaryEntityId.ToString());
            PrimaryEntityName.Set(codeActivityContext, workflowContext.PrimaryEntityName);

            string url = PageURLIn.Get(codeActivityContext);
            if (url != null)
            {
                url = url.Replace(“&id=”, “&id=” + workflowContext.PrimaryEntityId.ToString());
                PageURLOut.Set(codeActivityContext, url);
            }
        }
    }
}

Don’t forget to sign your assembly with a public strong name key file (from Visual Studio, project properites, signing).

You’ll find the ID of the Entity in output argument PrimaryEntityID. Also if you set the input argument PageURLIn then the output argument PageURLOut will hold the URL with the entity ID as i replaces the &id= querystring argument.