using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Workflow; using System; using System.Activities; using System.Globalization; using System.ServiceModel; namespace Esc.D365CE.CSharp.Workflow { public class WorkflowBase { public abstract class CodeActivityBase : CodeActivity { public class LocalWorkflowContext { internal IServiceProvider ServiceProvider { get; private set; } internal IOrganizationService OrganizationService { get; } internal IWorkflowContext WorkflowExecutionContext { get; } internal ITracingService TracingService { get; } internal CodeActivityContext ActivityContext { get; private set; } internal LocalWorkflowContext() { } internal LocalWorkflowContext(CodeActivityContext executionContext) { ActivityContext = executionContext ?? throw new ArgumentNullException(nameof(executionContext)); WorkflowExecutionContext = executionContext.GetExtension(); TracingService = executionContext.GetExtension(); var factory = executionContext.GetExtension(); OrganizationService = factory.CreateOrganizationService(WorkflowExecutionContext.UserId); } internal void Trace(string message, params object[] args) { if (string.IsNullOrWhiteSpace(message) || TracingService == null) { return; } if (WorkflowExecutionContext == null) { TracingService.Trace(message); } else { TracingService.Trace( "{0}, Correlation Id: {1}, Initiating User: {2}", message, WorkflowExecutionContext.CorrelationId, WorkflowExecutionContext.InitiatingUserId, args); } } } protected override void Execute(CodeActivityContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } var localcontext = new LocalWorkflowContext(context); localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Entered {0}.Execute()", "Custom Workflow Activity")); try { ExecuteCrmWorkFlowActivity(localcontext); } catch (FaultException e) { localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exception: {0}", e.ToString())); throw; } finally { localcontext.Trace(string.Format(CultureInfo.InvariantCulture, "Exiting {0}.Execute()", "Custom Workflow Activity")); } } protected virtual void ExecuteCrmWorkFlowActivity(LocalWorkflowContext context) { } } } }