Sample: Use optimistic concurrency with update and delete operations

Applies to Dynamics 365 (online), version 9.x

Demonstrates how to use the optimistic concurrency feature, introduced in Dynamics CRM Online 2015 Update 1, to prevent potential data loss when doing an update or delete of entity records. For more details about the technique used, refer to this topic: Reduce potential data loss using optimistic concurrency

The complete sample can be downloaded at Use optimistic concurrency with update and delete operations.

Prerequisites

To run this sample you must have:

  • Access to a Dynamics CRM Online 2016 Update or Microsoft Dynamics 365 on-premises organization.

  • Microsoft .NET Framework 4.5.2 installed on your development computer.

  • An active Internet connection for the required NuGet packages to automatically download when building the sample.

What this sample does

This sample shows how to use optimistic concurrency for update and delete operations. Code snippets showing just the key sections of the sample are shown. This sample sets the concurrency behavior on the update and delete requests so the server will check for a specific version of an account record for those operations. If the update or delete operations are attempted using a record with a different row version, an exception results. Otherwise, the operation is successful.



// Connect to the Organization service. 
// The using statement assures that the service proxy will be properly disposed.
using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri,
    serverConfig.Credentials, serverConfig.DeviceCredentials))
{
    CreateRequiredRecords();

    // Retrieve an account.
    var account = _serviceProxy.Retrieve("account", _accountId, new ColumnSet("name","creditlimit"));
    Console.WriteLine("\tThe row version of the created account is {0}", account.RowVersion);

    if (account != null)
    {
        // Create an in-memory account object from the retrieved account.
        Entity updatedAccount = new Entity()
        {
            LogicalName = account.LogicalName,
            Id = account.Id,
            RowVersion = account.RowVersion
        };

        // Update just the credit limit.
        updatedAccount["creditlimit"] = new Money(1000000);

        // Set the request's concurrency behavour to check for a row version match.
        UpdateRequest accountUpdate = new UpdateRequest()
        {
            Target = updatedAccount,
            ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
        };

        // Do the update.
        UpdateResponse accountUpdateResponse = (UpdateResponse) _serviceProxy.Execute(accountUpdate);
        Console.WriteLine("Account '{0}' updated with a credit limit of {1}.", account["name"], 
            ((Money)updatedAccount["creditlimit"]).Value);

        account = _serviceProxy.Retrieve("account", updatedAccount.Id, new ColumnSet());
        Console.WriteLine("\tThe row version of the updated account is {0}", account.RowVersion);
        _accountRowVersion = account.RowVersion;
    }

    DeleteRequiredRecords(promptforDelete);
}



// Delete the account record only if the row version matches.
EntityReference accountToDelete = new EntityReference("account", _accountId);
accountToDelete.RowVersion = _accountRowVersion;

DeleteRequest request = new DeleteRequest()
{
    Target = accountToDelete,
    ConcurrencyBehavior = ConcurrencyBehavior.IfRowVersionMatches
};

_serviceProxy.Execute(request);

Install NuGet packages

  1. Download this sample and extract the files.

  2. Navigate to the C# folder and open the solution file in Visual Studio.

  3. In Solution Explorer, right-click the project and click Manage NuGet Packages.

  4. In the drop down list at the top of the dialog, click Include Prerelease if you’re using a Dynamics 365 (online) Preview organization. Otherwise, click Stable Only.

  5. Close the dialog.

    The required packages are automatically installed when you build the solution.

Run the sample

  1. In Visual Studio, press F5 to build and run the sample. You’ll be prompted to accept the licenses for the NuGet packages that are to be installed.

  2. If you haven’t previously run one of the Dynamics 365 Customer Engagement managed code samples before, you’ll need to enter information to run the code. Otherwise, enter the number for one of the Dynamics 365 servers you have previously set up.

    Prompt Description
    Enter a Dynamics 365 server name and port [crm.dynamics.com] Type the name of your Dynamics 365 server. The default is Dynamics 365 (online) (crm.dynamics.com) in North America.

    Example:
    crm5.dynamics.com

    Don’t include the name of your organization or Internet protocol (http or https). You’ll be prompted for that later.
    Is this organization provisioned in Microsoft Online Services (y/n) [n] Type y if this is a Microsoft Online Services provisioned organization. Otherwise, type n.
    Enter domain\username For Dynamics 365 (online), enter your Microsoft account. For example: someone@mydomain.onmicrosoft.com.
    Enter password Type your password. Your password is securely saved in the Windows Credential Manager for later reuse.
    Specify an organization number (1-n) [1] From the list of organizations shown that you belong to, type the corresponding number. The default is 1, indicating the first organization in the list.
  3. The sample will perform the operations described in What this sample does and may prompt you with additional options.

  4. When the sample is complete, press ENTER to close the console window.

See also

Reduce potential data loss using optimistic concurrency