Microsoft Fakes and LINQ (Custom Workflow Activity) in CRM


Hi,

Just sharing a sample code to test a custom workflow activity using Microsoft Fakes.

The custom workflow activity uses LINQ.

The custom workflow activity code


public sealed class MyCustomWorkflowActivity : CodeActivity
{
#region Public Properties

[Input("Stage Name")]
public InArgument<string> StageName { get; set; }

#endregion

#region Methods

/// <summary>
/// Executes the workflow activity.
/// </summary>
/// <param name="executionContext">
/// The execution context.
/// </param>
protected override void Execute(CodeActivityContext executionContext)
{
// Create the tracing service
var tracingService = executionContext.GetExtension<ITracingService>();

// Create the context
var context = executionContext.GetExtension<IWorkflowContext>();

var serviceFactory = executionContext.GetExtension<IOrganizationServiceFactory>();

IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

try
{
using (var xrmServiceContext = new XrmServiceContext(service))
{
// get the business process workflow id
var workflow = (from w in xrmServiceContext.WorkflowSet
where w.Name == "Business Process Workflow Name"
select new Workflow { WorkflowId = w.WorkflowId }).FirstOrDefault();

if (workflow != null)
{
// get the stage name from the context's input parameter
var stageName = this.StageName.Get<string>(executionContext);
var stage = (from s in xrmServiceContext.ProcessStageSet
where s.StageName == stageName && s.ProcessId.Id == workflow.WorkflowId
select new ProcessStage { ProcessStageId = s.ProcessStageId }).FirstOrDefault();

if (stage != null)
{
// update the sales state in the case record to which the above business process flow is associated
var incident = new Incident
{
Id = context.PrimaryEntityId,
StageId = stage.ProcessStageId
};
service.Update(incident);
}
}
}
}
catch (FaultException<OrganizationServiceFault> e)
{
tracingService.Trace("Exception: {0}", e.ToString());
throw;
}

}

Unit Test Code


public void UnitTestCustomWorkflowActivity()
{

var workflowUserId = Guid.NewGuid();
var workflowCorrelationId = Guid.NewGuid();
var workflowInitiatingUserId = Guid.NewGuid();

var service = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationService();

var workflowContext = new Microsoft.Xrm.Sdk.Workflow.Fakes.StubIWorkflowContext();
workflowContext.UserIdGet = () =>
{
return workflowUserId;
};
workflowContext.CorrelationIdGet = () =>
{
return workflowCorrelationId;
};
workflowContext.InitiatingUserIdGet = () =>
{
return workflowInitiatingUserId;
};

// ITracingService
var tracingService = new Microsoft.Xrm.Sdk.Fakes.StubITracingService();
tracingService.TraceStringObjectArray = (f, o) =>
{
Debug.WriteLine(f, o);
};

// IOrganizationServiceFactory
var factory = new Microsoft.Xrm.Sdk.Fakes.StubIOrganizationServiceFactory();
factory.CreateOrganizationServiceNullableOfGuid = id =>
{
return service;
};

SetBpfStage target = new SetBpfStage();

var wfEntity = new Workflow();
wfEntity.Id = Guid.NewGuid();
wfEntity["name"] = "abcabcabc";
var wfEntity1 = new Workflow();
wfEntity1.Id = Guid.NewGuid();
wfEntity1["name"] = "abcabcabc";

var processStageEntity = new ProcessStage();
processStageEntity.Id = Guid.NewGuid();
processStageEntity["name"] = "abcabcabc";
service.ExecuteOrganizationRequest = r =>
{
RetrieveMultipleResponse response = null;
if (((Microsoft.Xrm.Sdk.Query.QueryExpression)((RetrieveMultipleRequest)r).Query).EntityName
== "workflow")
{
List<Entity> entities = new List<Entity> { wfEntity };

response = new RetrieveMultipleResponse
{
Results =
new ParameterCollection
{
{
"EntityCollection",
new EntityCollection
(entities)
}
}
};

return response;
}

if (((Microsoft.Xrm.Sdk.Query.QueryExpression)((RetrieveMultipleRequest)r).Query).EntityName
== "processstage")
{

List<Entity> entities = new List<Entity> { processStageEntity };

response = new RetrieveMultipleResponse
{
Results =
new ParameterCollection
{
{
"EntityCollection",
new EntityCollection
(entities)
}
}
};

return response;
}

return response;
};

service.UpdateEntity = (p) =>
{
};

var invoker = new WorkflowInvoker(target);
invoker.Extensions.Add<ITracingService>(() => tracingService);
invoker.Extensions.Add<IWorkflowContext>(() => workflowContext);
invoker.Extensions.Add<IOrganizationServiceFactory>(() => factory);

var inputs = new Dictionary<string, object>
{
{ "StageName", "New" }
};

invoker.Invoke(inputs);
}

Hope it helps..


Discover more from Nishant Rana's Weblog

Subscribe to get the latest posts sent to your email.

Unknown's avatar

Author: Nishant Rana

I love working in and sharing everything about Microsoft.NET technology !

3 thoughts on “Microsoft Fakes and LINQ (Custom Workflow Activity) in CRM”

Leave a reply to Nikhil Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from Nishant Rana's Weblog

Subscribe now to keep reading and get access to the full archive.

Continue reading

Power Platform Puzzles

D365 CRM, Power Platform Tips &Tricks

Power Spark

Power Spark By Shrangarika

Van Carl Nguyen

Exploration of Power Platform

My Trial

It is my experience timeline.

Power⚡Thomas

Sharing my knowledge and experience about the Microsoft Power Platform.

Arpit Power Guide

a guide to powering up community

Welcome to the Blog of Paul Andrew

Sponsored by Cloud Formations Ltd

Deriving Dynamics 365

Deriving Solutions and features on Power Platform/Dynamics 365

The CRM Ninja

Thoughts & musings from a Microsoft Business Applications Ninja!

D CRM Explorer

Learn about Microsoft Dynamics CRM Power Platform customization and implementation and other cool stuffs

Stroke // Jonas Rapp

I know pre-stroke. I will improve who I was.

Power Melange

Power Melange By Shalinee

Clavin's Blog - PPUG.ORG

AI - Power Automate - Power Apps - SharePoint Online - Azure - Nintex - K2 - Artificial Intelligence

Sat Sangha Salon

An Inquiry in Being

The Indoencers

The Influencers & Influences of Indian Music

Monika Halan's blog

Hand's-free money management

D365 Demystified

A closer look at Microsoft Dynamics 365.

Microsoft Mate (msftmate) - Andrew Rogers

Experienced consultant primarily focused on Microsoft Dynamics 365 and the Power Platform

Manmit Rahevar's Blog

One Stop Destination for Microsoft Technology Solutions

MG

Naturally Curious

Brian Illand

Power Platform and Dynamics 365

Steve Mordue

The Professional Paraphraser

Subwoofer 101

Bass defines your home theater

SQLTwins by Nakul Vachhrajani

SQL Server tips and experiences dedicated to my twin daughters.

Everything D365

Discovering Azure DevOps and D365 Business Applications

Tech Wizard

Lets do IT Spells

XRM Tricks (Power Platform & Dynamics CRM )

Power Platform & Dynamics CRM

CRM TIPS BY PRM

Mail to crmtipsbyprm@gmail.com for queries and suggestions

nijos.dev

Giving back to the community what I have learned

Power Platform Learning

Your Go-To Resource for Power Apps, Power Automate & More

xrm CRM Dynamics

Dynamics CRM Technical & Functional Info

Dynamics 365 Blogs - Explained in unique way

Sometimes you need to look at things from different perspective.