DynamicsCRMOperations 1.0.5

dotnet add package DynamicsCRMOperations --version 1.0.5
                    
NuGet\Install-Package DynamicsCRMOperations -Version 1.0.5
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="DynamicsCRMOperations" Version="1.0.5" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="DynamicsCRMOperations" Version="1.0.5" />
                    
Directory.Packages.props
<PackageReference Include="DynamicsCRMOperations" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add DynamicsCRMOperations --version 1.0.5
                    
#r "nuget: DynamicsCRMOperations, 1.0.5"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package DynamicsCRMOperations@1.0.5
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=DynamicsCRMOperations&version=1.0.5
                    
Install as a Cake Addin
#tool nuget:?package=DynamicsCRMOperations&version=1.0.5
                    
Install as a Cake Tool

DynamicsCRMOperations

A comprehensive .NET Framework 4.6.2 library for Microsoft Dynamics CRM / Dataverse online operations.
Designed for use in Plugins, Workflow Activities, console apps, and Azure Functions.


Table of Contents


Installation

Install via the NuGet Package Manager Console:

Install-Package DynamicsCRMOperations

Or via the .NET CLI:

dotnet add package DynamicsOperation

Or add directly to your .csproj:

<PackageReference Include="DynamicsCRMOperations" Version="1.0.0" />

Transitive dependencies — the following CRM SDK packages are pulled in automatically:

  • Microsoft.CrmSdk.CoreAssemblies
  • Microsoft.CrmSdk.XrmTooling.CoreAssembly
  • Microsoft.CrmSdk.Workflow

Quick Start

using DynamicsOperation.Core;
using DynamicsOperation.Operations.Query;
using Microsoft.Xrm.Sdk.Query;

// Inside a plugin
var crm = CrmService.FromPlugin(serviceProvider);

// Fluent query
var query = QueryExpressionBuilder.For("account")
    .Select("name", "telephone1", "emailaddress1")
    .WhereEqual("statecode", 0)
    .OrderBy("name")
    .Top(50)
    .Build();

var accounts = crm.Query.RetrieveAll(query);

foreach (var account in accounts)
    Console.WriteLine(account["name"]);

Connection

Inside a Plugin or Workflow

Use CrmService.FromPlugin to obtain a service scoped to the initiating user, or FromPluginAsSystem for elevated (SYSTEM) access.

public class MyPlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        // Runs as the user who triggered the plugin
        var crm = CrmService.FromPlugin(serviceProvider);

        // Runs as SYSTEM (no security role restrictions)
        var crmSystem = CrmService.FromPluginAsSystem(serviceProvider);
    }
}

Out-of-Process (Console / Azure Function)

OAuth Client Credentials (recommended for S2S / app users):

using DynamicsOperation.Connection;
using DynamicsOperation.Core;

using (var conn = CrmConnection.FromClientCredentials(
    organizationUrl : "https://yourorg.crm.dynamics.com",
    clientId        : "your-app-registration-client-id",
    clientSecret    : "your-client-secret",
    tenantId        : "your-aad-tenant-id"))
{
    var crm = CrmService.FromConnection(conn);
    // use crm...
}

Connection string (any auth type):

var connectionString =
    "AuthType=OAuth;" +
    "Url=https://yourorg.crm.dynamics.com;" +
    "Username=user@yourorg.com;" +
    "Password=yourpassword;" +
    "AppId=51f81489-12ee-4a9e-aaae-a2591f45987d;" +
    "RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;" +
    "LoginPrompt=Never";

using (var conn = CrmConnection.FromConnectionString(connectionString))
{
    var crm = CrmService.FromConnection(conn);
    // use crm...
}

Wrapping an existing IOrganizationService:

IOrganizationService existingService = /* obtained elsewhere */;
var crm = new CrmService(existingService);

CRUD Operations

All CRUD operations are available through crm.Crud.

Create

var account = new Entity("account");
account["name"]        = "Contoso Ltd";
account["telephone1"]  = "+1-555-0100";
account["emailaddress1"] = "info@contoso.com";

Guid newId = crm.Crud.Create(account);

Retrieve

// Late-bound — explicit columns
Entity account = crm.Crud.Retrieve(
    "account",
    accountId,
    new ColumnSet("name", "telephone1", "emailaddress1"));

// Strongly typed — auto-ColumnSet (no ColumnSet argument needed)
// The library reflects over Account's [AttributeLogicalName] properties once,
// builds the exact ColumnSet, and caches it for the lifetime of the process.
Account typedAccount = crm.Crud.Retrieve<Account>(accountId);

// Strongly typed — explicit ColumnSet (override the auto-selection)
Account typedAccount2 = crm.Crud.Retrieve<Account>(accountId, new ColumnSet("name", "telephone1"));

// Late-bound — all columns
Entity fullRecord = crm.Crud.Retrieve("contact", contactId, new ColumnSet(true));

Auto-ColumnSet behaviour: when Retrieve<T>(Guid id) is called, the library walks every property on T that carries [AttributeLogicalName] (the attribute added by CrmSvcUtil to every mapped property) and builds a ColumnSet from those names. The result is cached per-type in a ConcurrentDictionary so reflection only runs once per type across the lifetime of the process. If T has no decorated properties (e.g. a hand-written subclass), the fallback is new ColumnSet(true) (all columns).

Update

var update = new Entity("account", accountId);
update["name"]      = "Contoso Ltd (Updated)";
update["telephone1"] = "+1-555-9999";

crm.Crud.Update(update);

Delete

// By entity name and Id
crm.Crud.Delete("account", accountId);

// By EntityReference
crm.Crud.Delete(new EntityReference("account", accountId));

Upsert

Creates the record if it does not exist; updates it if it does.
Requires at least one alternate key defined on the entity.

var contact = new Entity("contact");
contact["emailaddress1"] = "jane.doe@contoso.com"; // alternate key
contact["firstname"]     = "Jane";
contact["lastname"]      = "Doe";

UpsertResult result = crm.Crud.Upsert(contact);

if (result.RecordCreated)
    Console.WriteLine($"Created new contact: {result.RecordId}");
else
    Console.WriteLine($"Updated existing contact: {result.RecordId}");

Set State

var accountRef = new EntityReference("account", accountId);

// Deactivate (statecode=1, statuscode=2)
crm.Crud.SetState(accountRef, stateCode: 1, statusCode: 2);

// Reactivate (statecode=0, statuscode=1)
crm.Crud.SetState(accountRef, stateCode: 0, statusCode: 1);

Assign

var accountRef = new EntityReference("account", accountId);
var newOwner   = new EntityReference("systemuser", newOwnerId);

crm.Crud.Assign(accountRef, newOwner);

Query Operations

All query operations are available through crm.Query.

QueryExpressionBuilder

A fluent builder that reduces boilerplate when constructing QueryExpression objects.

using DynamicsOperation.Operations.Query;

QueryExpression query = QueryExpressionBuilder
    .For("contact")
    .Select("firstname", "lastname", "emailaddress1", "parentcustomerid")
    .WhereEqual("statecode", 0)
    .WhereNotNull("emailaddress1")
    .WhereIn("gendercode", 1, 2)
    .OrderBy("lastname")
    .OrderBy("firstname")
    .Top(200)
    .Build();

OR filter logic:

var query = QueryExpressionBuilder
    .For("lead")
    .Select("fullname", "emailaddress1")
    .WhereEqual("statecode", 0)
    .WithOrLogic()
    .WhereEqual("leadsourcecode", 1)
    .WhereEqual("leadsourcecode", 8)
    .Build();

With a linked entity (join):

var query = QueryExpressionBuilder
    .For("contact")
    .Select("firstname", "lastname")
    .WhereEqual("statecode", 0)
    .Join(
        linkedEntityName  : "account",
        fromAttributeName : "parentcustomerid",
        toAttributeName   : "accountid",
        joinOperator      : JoinOperator.Inner,
        configure         : link =>
        {
            link.Columns = new ColumnSet("name", "telephone1");
            link.EntityAlias = "parentaccount";
            link.LinkCriteria.AddCondition("statecode", ConditionOperator.Equal, 0);
        })
    .Build();

With explicit paging:

var query = QueryExpressionBuilder
    .For("account")
    .SelectAll()
    .Page(pageNumber: 2, pageSize: 100, pagingCookie: cookieFromPreviousPage)
    .Build();

Retrieve All (auto-paged)

Automatically iterates through all pages and returns the complete result set.

var query = QueryExpressionBuilder
    .For("contact")
    .Select("firstname", "lastname", "emailaddress1")
    .WhereEqual("statecode", 0)
    .Build();

IList<Entity> allContacts = crm.Query.RetrieveAll(query);

// Strongly typed
IList<Contact> allContactsTyped = crm.Query.RetrieveAll<Contact>(query);

Retrieve a Single Page

var query = QueryExpressionBuilder
    .For("account")
    .Select("name", "telephone1")
    .WhereEqual("statecode", 0)
    .Build();

PagedResult<Entity> page1 = crm.Query.RetrievePage(query, pageSize: 50);

Console.WriteLine($"Returned {page1.TotalCount} records.");
Console.WriteLine($"More available: {page1.MoreRecordsAvailable}");

if (page1.MoreRecordsAvailable)
{
    PagedResult<Entity> page2 = crm.Query.RetrievePage(
        query,
        pageSize: 50,
        pagingCookie: page1.PagingCookie);
}

FetchXML Queries

string fetchXml = @"
<fetch>
  <entity name='opportunity'>
    <attribute name='name' />
    <attribute name='estimatedvalue' />
    <attribute name='closedate' />
    <filter>
      <condition attribute='statecode' operator='eq' value='0' />
      <condition attribute='estimatedvalue' operator='gt' value='10000' />
    </filter>
    <order attribute='closedate' descending='false' />
  </entity>
</fetch>";

// All records (auto-paged)
IList<Entity> opportunities = crm.Query.RetrieveAllByFetchXml(fetchXml);

// Strongly typed
IList<Opportunity> typed = crm.Query.RetrieveAllByFetchXml<Opportunity>(fetchXml);

// Single page
PagedResult<Entity> page = crm.Query.RetrievePageByFetchXml(
    fetchXml,
    page: 1,
    pageSize: 100);

Retrieve First

var query = QueryExpressionBuilder
    .For("systemuser")
    .Select("fullname", "internalemailaddress")
    .WhereEqual("internalemailaddress", "admin@contoso.com")
    .Build();

Entity user = crm.Query.RetrieveFirst(query); // null if not found

// Strongly typed
SystemUser typedUser = crm.Query.RetrieveFirst<SystemUser>(query);

Count Records

var query = QueryExpressionBuilder
    .For("lead")
    .WhereEqual("statecode", 0)
    .WhereEqual("leadsourcecode", 3)
    .Build();

int count = crm.Query.Count(query);
Console.WriteLine($"Open leads from web: {count}");

Bulk Operations

All bulk operations are available through crm.Bulk.
They use ExecuteMultiple internally and respect the 1,000-records-per-batch CRM limit.

Bulk Create

var newContacts = new List<Entity>();
for (int i = 0; i < 5000; i++)
{
    var c = new Entity("contact");
    c["firstname"] = $"User {i}";
    c["lastname"]  = "Test";
    newContacts.Add(c);
}

BulkOperationResult result = crm.Bulk.BulkCreate(
    entities      : newContacts,
    continueOnError: true,
    batchSize     : 500);

Console.WriteLine($"Created: {result.SuccessCount}, Failed: {result.FailureCount}");

Bulk Update

var updates = existingRecords.Select(e =>
{
    var update = new Entity("account", e.Id);
    update["description"] = "Processed";
    return update;
}).ToList();

BulkOperationResult result = crm.Bulk.BulkUpdate(updates);

Bulk Delete

var toDelete = records
    .Select(r => new EntityReference("contact", r.Id))
    .ToList();

BulkOperationResult result = crm.Bulk.BulkDelete(toDelete, continueOnError: true);

if (result.HasErrors)
    foreach (var err in result.Errors)
        Console.WriteLine($"[{err.RequestIndex}] {err.ErrorCode}: {err.ErrorMessage}");

Mixed Bulk Execute

Send any mix of request types in a single batched call.

var requests = new List<OrganizationRequest>();

requests.Add(new CreateRequest { Target = newAccount });
requests.Add(new UpdateRequest { Target = updatedContact });
requests.Add(new DeleteRequest { Target = new EntityReference("lead", leadId) });

BulkOperationResult result = crm.Bulk.BulkExecute(
    requests       : requests,
    continueOnError: true,
    batchSize      : 1000);

Association Operations

All association operations are available through crm.Associations.

Associate

var account   = new EntityReference("account", accountId);
var contact1  = new EntityReference("contact", contact1Id);
var contact2  = new EntityReference("contact", contact2Id);

// Associate multiple
crm.Associations.Associate(
    primaryRecord         : account,
    relationshipSchemaName: "contact_customer_accounts",
    relatedRecords        : new[] { contact1, contact2 });

// Associate a single record (convenience overload)
crm.Associations.Associate(account, "contact_customer_accounts", contact1);

Disassociate

crm.Associations.Disassociate(
    primaryRecord         : account,
    relationshipSchemaName: "contact_customer_accounts",
    relatedRecords        : new[] { contact1, contact2 });

Execute Operations

All execute operations are available through crm.Execute.

Generic Execute

using Microsoft.Xrm.Sdk.Messages;

// Typed overload
RetrieveEntityResponse response = crm.Execute.Execute<RetrieveEntityResponse>(
    new RetrieveEntityRequest
    {
        LogicalName  = "account",
        EntityFilters = EntityFilters.Attributes
    });

// Untyped overload
OrganizationResponse raw = crm.Execute.Execute(new PublishAllXmlRequest());

Custom Actions

var inputParams = new ParameterCollection
{
    { "EmailAddress", "customer@example.com" },
    { "TemplateId",   templateId }
};

OrganizationResponse response = crm.Execute.ExecuteAction(
    actionName      : "new_SendWelcomeEmail",
    inputParameters : inputParams,
    regarding       : new EntityReference("contact", contactId));

// Read output parameters
string result = response.Results["Status"]?.ToString();

WhoAmI

WhoAmIResponse whoAmI = crm.Execute.WhoAmI();
Console.WriteLine($"User Id     : {whoAmI.UserId}");
Console.WriteLine($"Business Unit: {whoAmI.BusinessUnitId}");
Console.WriteLine($"Organization : {whoAmI.OrganizationId}");

Helpers

EntityExtensions

Extension methods on Entity to simplify common attribute access patterns.

using DynamicsOperation.Helpers;

Entity contact = crm.Crud.Retrieve("contact", contactId, new ColumnSet(true));

// Safe attribute read with default
string name     = contact.GetValueOrDefault<string>("firstname", "Unknown");
DateTime? dob   = contact.GetValueOrDefault<DateTime?>("birthdate");

// OptionSetValue
int? statusCode = contact.GetOptionSetValue("statuscode");

// EntityReference
Guid   ownerId      = contact.GetLookupId("ownerid");
string ownerLogical = contact.GetLookupLogicalName("ownerid");

// Money
decimal? revenue = contact.GetMoneyValue("revenue");

// AliasedValue (FetchXML aggregate or linked column)
int count = contact.GetAliasedValue<int>("linked_entity.record_count");

// Null-safe existence check
bool hasEmail = contact.HasValue("emailaddress1");

// Fluent setters
contact.SetOptionSetValue("statecode",  0);
contact.SetMoneyValue("revenue",        99999.99m);
contact.SetLookup("ownerid", "systemuser", userId);

// Build EntityReference from Entity
EntityReference contactRef = contact.ToEntityReference();

// Merge attributes from another entity (target wins on conflict)
contact.MergeAttributes(anotherEntity);

FetchXmlHelper

using DynamicsOperation.Helpers;

// Build a minimal FetchXML from scratch
string fetchXml = FetchXmlHelper.Build(
    entityLogicalName : "account",
    attributes        : new[] { "name", "telephone1" },
    top               : 10);

// Add a condition at runtime
fetchXml = FetchXmlHelper.AddCondition(fetchXml, "statecode", "eq", "0");

// Limit top N
fetchXml = FetchXmlHelper.SetTop(fetchXml, 500);

// Read entity name from existing FetchXML
string entityName = FetchXmlHelper.GetEntityName(fetchXml); // "account"

// Strip paging attributes before re-using a query
fetchXml = FetchXmlHelper.ResetPaging(fetchXml);

PluginContextHelper

Simplifies access to common plugin execution context items.

using DynamicsOperation.Helpers;

public class AccountUpdatePlugin : IPlugin
{
    public void Execute(IServiceProvider serviceProvider)
    {
        var context = (IPluginExecutionContext)serviceProvider
            .GetService(typeof(IPluginExecutionContext));

        // Validate entity
        PluginContextHelper.AssertEntityLogicalName(context, "account");

        // Target entity (the fields being changed in this Update)
        Entity target = PluginContextHelper.GetTargetEntity(context);

        // Pre-image (full record state before the update)
        Entity preImage = PluginContextHelper.GetPreImage(context, "PreImage");

        // Post-image (full record state after the update)
        Entity postImage = PluginContextHelper.GetPostImage(context, "PostImage");

        // Merged view: preImage fields overridden by target changes
        Entity merged = PluginContextHelper.MergeWithPreImage(context, "PreImage");
        string newName = merged.GetValueOrDefault<string>("name");

        // Check whether a specific field was included in the update
        bool nameChanged = PluginContextHelper.AttributeChanged(context, "name");
        if (!nameChanged) return;

        // Throw a user-facing validation error
        if (string.IsNullOrWhiteSpace(newName))
            PluginContextHelper.Throw("Account Name is required.");
    }
}

Error Handling

All operations throw CrmOperationException on failure, wrapping the original SDK exception.

using DynamicsOperation.Exceptions;

try
{
    crm.Crud.Update(entity);
}
catch (CrmOperationException ex)
{
    Console.WriteLine($"Operation : {ex.OperationName}");   // "Update"
    Console.WriteLine($"Entity    : {ex.EntityLogicalName}"); // "account"
    Console.WriteLine($"CRM Code  : {ex.ErrorCode}");
    Console.WriteLine($"Message   : {ex.Message}");
    Console.WriteLine($"Inner     : {ex.InnerException?.Message}");
}

Inside a plugin, re-throw as InvalidPluginExecutionException to surface the message to the user:

catch (CrmOperationException ex)
{
    throw new InvalidPluginExecutionException(ex.Message, ex);
}

Metadata Operations

Access entity definitions, attribute metadata, and OptionSet label dictionaries without writing raw SDK requests.

// Full entity metadata (attributes, keys, relationships, etc.)
EntityMetadata meta = crm.Metadata.GetEntityMetadata("account", EntityFilters.Attributes);
Console.WriteLine($"Primary key: {meta.PrimaryIdAttribute}");

// Single attribute metadata
AttributeMetadata attr = crm.Metadata.GetAttributeMetadata("contact", "gendercode");

// OptionSet value → label dictionary (language code 1033 = English)
Dictionary<int, string> labels = crm.Metadata.GetOptionSetLabels("lead", "leadsourcecode");
// labels[1] == "Advertisement", labels[8] == "Other"

string label = labels.TryGetValue(myOptionSetValue, out var l) ? l : "Unknown";

// All entities (summary only)
IList<EntityMetadata> allEntities = crm.Metadata.GetAllEntities();
foreach (var e in allEntities)
    Console.WriteLine($"{e.LogicalName} — {e.DisplayName?.UserLocalizedLabel?.Label}");

Sharing & Security Operations

Manage record-level sharing (who can read/write/delete a specific record).

var accountRef = new EntityReference("account", accountId);
var userRef    = new EntityReference("systemuser", userId);
var teamRef    = new EntityReference("team", teamId);

// Grant read + write access to a user
crm.Sharing.GrantAccess(accountRef, userRef,
    AccessRights.ReadAccess | AccessRights.WriteAccess);

// Grant read-only to a team
crm.Sharing.GrantAccess(accountRef, teamRef, AccessRights.ReadAccess);

// Change existing access rights
crm.Sharing.ModifyAccess(accountRef, userRef,
    AccessRights.ReadAccess | AccessRights.WriteAccess | AccessRights.DeleteAccess);

// Remove all shared access for a user
crm.Sharing.RevokeAccess(accountRef, userRef);

// Check what access the current principal has
AccessRights rights = crm.Sharing.RetrievePrincipalAccess(accountRef, userRef);
bool canDelete = (rights & AccessRights.DeleteAccess) != 0;

Process & Workflow Operations

Trigger on-demand workflows and move records through Business Process Flows.

// Execute an on-demand (on-demand = true) workflow against a specific record
crm.Process.ExecuteWorkflow(workflowId: myWorkflowId, targetEntityId: contactId);

// Move a record to a specific BPF stage
crm.Process.SetProcessStage(
    record  : new EntityReference("lead", leadId),
    stageId : myBpfStageId);

FetchXmlBuilder (Fluent)

A fluent builder for FetchXML strings — use it when you need aggregates, grouping, or features not available in QueryExpression.

using DynamicsOperation.Operations.Query;

// Basic query
string fetchXml = FetchXmlBuilder
    .For("contact")
    .Select("firstname", "lastname", "emailaddress1")
    .WhereEqual("statecode", 0)
    .WhereNotNull("emailaddress1")
    .WhereStartsWith("lastname", "Smith")
    .OrderBy("lastname")
    .Top(100)
    .Build();

var contacts = crm.Query.RetrieveAllByFetchXml(fetchXml);

Aggregate / GROUP BY:

string aggFetch = FetchXmlBuilder
    .For("opportunity")
    .Aggregate("estimatedvalue", "sum",  alias: "total_value")
    .Aggregate("opportunityid",  "count", alias: "opp_count")
    .GroupBy("ownerid", alias: "owner")
    .WhereEqual("statecode", 0)
    .Build();

var rows = crm.Query.RetrieveAllByFetchXml(aggFetch);
foreach (var row in rows)
{
    decimal total = row.GetAliasedValue<decimal>("total_value");
    int     count = row.GetAliasedValue<int>("opp_count");
}

Join with conditions:

string joinFetch = FetchXmlBuilder
    .For("contact")
    .Select("firstname", "lastname")
    .WhereEqual("statecode", 0)
    .Join(
        linkedEntityName : "account",
        fromAttribute    : "parentcustomerid",
        toAttribute      : "accountid",
        linkType         : "inner",
        alias            : "parentaccount",
        configure        : link =>
        {
            link.Add(new XElement("attribute", new XAttribute("name", "name")));
            link.Add(new XElement("filter",
                new XElement("condition",
                    new XAttribute("attribute", "statecode"),
                    new XAttribute("operator", "eq"),
                    new XAttribute("value", "0"))));
        })
    .Build();

Extended QueryExpressionBuilder conditions (also updated):

var query = QueryExpressionBuilder
    .For("opportunity")
    .Select("name", "estimatedvalue", "closedate")
    .WhereGreaterThan("estimatedvalue", 10000)
    .WhereLessThanOrEqual("closedate", DateTime.Today.AddDays(30))
    .WhereBetween("probability", 50, 100)
    .WhereContains("name", "renewal")
    .WhereThisMonth("createdon")
    .WhereIn("statecode", 0, 1)
    .Build();

Retry Policy

Wrap any CRM operation in automatic exponential-backoff retry to handle throttling and transient failures.

using DynamicsOperation.Resilience;

// Default: 3 retries, 500ms base delay, jitter enabled
var retry = new RetryPolicy();

// Custom: 5 retries, 1s base delay, with logger
var retry = new RetryPolicy(
    maxRetries  : 5,
    baseDelayMs : 1000,
    useJitter   : true,
    logger      : new CrmTracingLogger(tracingService));

// Pass to CrmService — stored and exposed as crm.RetryPolicy for consumers
var crm = CrmService.FromPlugin(serviceProvider, retryPolicy: retry);

// Use the retry policy directly to wrap any code block
Guid newId = retry.Execute(() => crm.Crud.Create(entity));

retry.Execute(() =>
{
    crm.Bulk.BulkCreate(largeList, continueOnError: true);
});

Errors that trigger a retry:

  • HTTP 429 / CRM throttling error codes (0x80060612, 0x80060613)
  • CRM service temporarily unavailable (0x8006088d)
  • TimeoutException
  • CommunicationException (WCF transport error)
  • Any exception whose message contains "timeout" or "throttl"

Plugin Base Class

Inherit from CrmPluginBase instead of IPlugin to get the same automatic wiring that CrmWorkflowActivityBase provides for workflow activities: CrmService, Logger, Context, and clean exception handling — all set up before your code runs.

using DynamicsOperation.Plugin;
using DynamicsOperation.Helpers;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

public class AccountUpdatePlugin : CrmPluginBase
{
    protected override void ExecutePlugin(IPluginExecutionContext context)
    {
        // Crm, Logger, Context, and ServiceFactory are all pre-wired
        Logger.Info($"Plugin fired on {context.PrimaryEntityName} ({context.MessageName})");

        // Validate we're on the right entity
        PluginContextHelper.AssertEntityLogicalName(context, "account");

        var target = PluginContextHelper.GetTargetEntity(context);
        if (!PluginContextHelper.AttributeChanged(context, "name")) return;

        // Read full record — auto-ColumnSet resolves all Account properties automatically
        var account = Crm.Crud.Retrieve<Account>(target.Id);
        Logger.Info($"New name: {account.Name}");

        // Merge pre-image + target to get the full updated view
        var merged = PluginContextHelper.MergeWithPreImage(context, "PreImage");

        // Throw a user-facing validation error
        if (string.IsNullOrWhiteSpace(merged.GetValueOrDefault<string>("name")))
            PluginContextHelper.Throw("Account Name cannot be empty.");
    }
}

Available inside ExecutePlugin:

Property Type Description
Crm ICrmService Full CRM facade (initiating user)
Logger ICrmLogger Backed by ITracingService
Context IPluginExecutionContext Plugin execution context
ServiceFactory IOrganizationServiceFactory For creating services as other users
CreateSystemService() IOrganizationService SYSTEM-level service (no security filtering)

Error handling: any InvalidPluginExecutionException you throw is passed through unchanged (surfaces to the user). All other exceptions are caught, logged via Logger.Error, and re-wrapped in an InvalidPluginExecutionException with the class name in the message.


Workflow Activity Base Class

Inherit from CrmWorkflowActivityBase instead of CodeActivity to get automatic CRM service setup, tracing, and error handling.

using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using DynamicsOperation.Workflow;

public class SendWelcomeEmailActivity : CrmWorkflowActivityBase
{
    [Input("Contact")]
    [ReferenceTarget("contact")]
    public InArgument<EntityReference> Contact { get; set; }

    [Output("EmailSent")]
    public OutArgument<bool> EmailSent { get; set; }

    protected override void ExecuteActivity(CodeActivityContext context)
    {
        var contactRef = Contact.Get(context);

        // Crm, Logger, and WorkflowContext are all pre-wired
        Logger.Info($"Processing contact {contactRef.Id}");

        var contact = Crm.Crud.Retrieve(
            "contact", contactRef.Id,
            new Microsoft.Xrm.Sdk.Query.ColumnSet("emailaddress1", "firstname"));

        string email = contact.GetValueOrDefault<string>("emailaddress1");
        if (string.IsNullOrEmpty(email))
        {
            Logger.Warning("Contact has no email address — skipping.");
            EmailSent.Set(context, false);
            return;
        }

        // Execute a custom action to send the email
        Crm.Execute.ExecuteAction("new_SendEmail",
            new Microsoft.Xrm.Sdk.ParameterCollection { { "To", email } },
            regarding: contactRef);

        EmailSent.Set(context, true);
    }
}

Available inside ExecuteActivity:

Property Type Description
Crm ICrmService Full CRM facade (initiating user)
Logger ICrmLogger Backed by ITracingService
WorkflowContext IWorkflowContext Raw workflow context
ServiceFactory IOrganizationServiceFactory For creating services as other users
CreateSystemService() IOrganizationService SYSTEM-level service

Dependency Injection (ASP.NET Core / Azure Functions)

Add DYNAMICS_DI to your project's DefineConstants and then register all services in one call.

.csproj:

<PropertyGroup>
  <DefineConstants>DYNAMICS_DI</DefineConstants>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="6.0.0" />
</ItemGroup>

Startup / Program.cs:

using DynamicsOperation.Extensions;

// OAuth S2S (recommended for Azure Functions / APIs)
builder.Services.AddDynamicsOperation(
    organizationUrl : "https://yourorg.crm.dynamics.com",
    clientId        : configuration["Dynamics:ClientId"],
    clientSecret    : configuration["Dynamics:ClientSecret"],
    tenantId        : configuration["Dynamics:TenantId"]);

// OR connection string
builder.Services.AddDynamicsOperation(configuration["Dynamics:ConnectionString"]);

Inject into your service / function:

public class ContactService
{
    private readonly ICrmService _crm;

    public ContactService(ICrmService crm) => _crm = crm;

    public IList<Entity> GetActiveContacts() =>
        _crm.Query.RetrieveAll(
            QueryExpressionBuilder.For("contact")
                .Select("firstname", "lastname")
                .WhereEqual("statecode", 0)
                .Build());
}

Performance: Plugin vs Out-of-Process

Aspect Inside Plugin/Workflow Out-of-Process
Service creation Injected by CRM runtime — instant OAuth token + HTTPS setup: 1–2 s on first call
Per-call latency In-process channel: ~1–5 ms HTTPS/SOAP round-trip: 50–300 ms
Throughput High; no network overhead Limited by HTTPS + API rate limits
Max execution time Plugin: 2 min; Workflow: 2 min async No platform limit (set your own timeout)
Retry Use sparingly — plugins run synchronously Always use RetryPolicy
Bulk operations Safe for moderate sizes Safe for large datasets
Metadata calls Expensive — cache results locally Expensive — cache results locally

Recommendation: For plugins, avoid RetrieveAll on large datasets and use Top() or page-based processing. Use ExecuteMultiple (via crm.Bulk) for batch writes instead of looping Create/Update.


Product Compatible and additional computed target framework versions.
.NET Framework net462 is compatible.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.5 166 5/16/2026