Introducing Transactions with Dynamics CRM 2015

 

We always wanted a transactions capabilities when you are performing business logic in enterprise applications, given the complexity of the application, integration or business rules. Transactions gives full capability to manage application behavior.

In order to implement transactions through windows or web based applications we used to write our own logic to roll back the operations in case of any business logic failure or change in data status.

We can take the example of my project where I wanted to rollback all operations in case of payment failure while buying order through online portal. In case of payment failure, I wrote my own logic to rollback records.

In Dynamics CRM 2015 update 1, as transactions been introduced, I was able to use ExecuteTransactionRequest, this is  helpful to maintain integrity during the context of transactions.

We can execute multiple operations in single database transaction so that either all operations will be executed successfully or none (revert back).

You need to add the reference to Microsoft.Xrm.Sdk dll.. We can provide collection of Organization request as given in below example.  I have added 3 requests to the collection. ExecuteTransactionRequest takes request collections as a parameter

public static void PerformTransactionOperation(OrganizationService service)
{
var request = new ExecuteTransactionRequest()
{
Requests = new OrganizationRequestCollection()
};

var account = new Entity(“account”);
account[“name”] = “Account Test”;
var createRequest = new CreateRequest() { Target = account };
request.Requests.Add(createRequest);

RetrieveRequest retReq = new RetrieveRequest() { Target = new EntityReference(“account”, new Guid(“B6F79317-5E8E-E511-80E7-3863BB2E1390”)) };

retReq.ColumnSet = new ColumnSet(“name”);
request.Requests.Add(retReq);
Entity accToUpdate = new Entity(“account”);

accToUpdate.Id = new Guid(“B6F79317-5E8E-E511-80E7-3863BB2E1390”);
var updateRequest = new UpdateRequest() { Target = accToUpdate };
request.Requests.Add(updateRequest);
try
{
var respTrans = (ExecuteTransactionResponse)service.Execute(request);
foreach (var response in respTrans.Responses)
{
switch (response.ResponseName.ToUpper())
{
case “CREATE”:
var createResponse = (CreateResponse)response;
Console.WriteLine(“Account created: {0}”, createResponse.id);
break;

case “UPDATE”:
var updateResponse = (UpdateResponse)response;
break;

case “DELETE”:
var deleteResponse = (DeleteResponse)response;
break;

case “SETSTATE”:

var setstateResponse = (SetStateResponse)response;

break;

case “RETRIEVE”:
var retResponse = (RetrieveResponse)response;
break;
}}}
catch (FaultException<OrganizationServiceFault> ex)
{
ExecuteTransactionFault fault = (ExecuteTransactionFault)ex.Detail;
}}

It will be executed in the same order as it was added to collection.

In our case we got 3 responses for each request. In my code, I am checking the Response name and accordingly performing each operation.

If you want to know the exact request that was failed, you can check the FaultedRequestIndex as given below. It will tell you the index number of the request that was failed.

Few important points to Note:

  • An ExecuteMultipleRequest may have multiple ExecuteTransactionRequest instances.
  • An ExecuteTransactionRequest instance may not contain a ExecuteMultipleRequest or ExecuteTransactionRequest.
  • It has same limit as ExecuteMultipleRequest. Maximum batch size could be 1000. You can have maximum 1000 Requests in a batch.
  • CRM online can have maximum 2 Concurrent batch request.
  • If you have more than 1000 Requests you have to split the requests in batches.

Hope this Post is helpful. I would love to hear your suggestions.

Happy CRMing!!!!!!!!
Thank you,
Kalim Ansar
Adisys Corporation

Advertisements

Set Custom Help URLs in Dynamics CRM Online 2015

Set Custom Help URL CRM Online 2015
Custom Help URL is another exciting feature in Dynamics CRM 2015. Administer can simply enable and configure the URL at both Global Level and Entity Level.

There are 3 kind of Help URL:

  • Build-in CRM Help (Default)
  • Global Level Custom Help
  • Entity Level Custom Help (Support both OOB entity and Custom Entity)

1)    Build-in CRM Help:

Below is the built-in CRM Online Help hosted on Microsoft website. User will be navigated to this online knowledge base center by default after clicking on Help link.

Dynamics CRM Help #1

Dynamics CRM Help #1

Dynamics CRM Help #1

 

 

 

 

 

 

2)     Custom URL at Global Level

System administrator can configure Global custom Help URL. Go to Settings -> Administration -> System Settings -> General:

Dynamics CRM Help #2

Dynamics CRM Help #2

 

 

Global Custom Help URL link in CRM:

Dynamics CRM Help #3

Dynamics CRM Help #3

 

3)     Entity Level Custom Help URL

To enable and configure the custom help URL on a specific entity form, administrator can go to Entity Customization:

Dynamics CRM Help #4

Dynamics CRM Help #4

 

Help Link on Entity form:

Dynamics CRM Help #5

Dynamics CRM Help #5

Hopefully you will find it useful!
Thank you,
Zhe Chen
Adisys Corporation

Set Hierarchy Security in Dynamics CRM Online

We have a requirement to allow the manager to view and update the records owned by the direct report.

In Dynamics CRM 2015 introduced hierarchy security model in CRM 2015 Update 1 which make it super easy to implement this kind security requirement.

Hierarchy security is an extension to the existing security models that use business units, security roles, sharing, and teams. There are two security options in Hierarchy Security Model:

  • Management Chain, based on the direct reporting structure and the hierarchy depth
  • Position Hierarchy, based on the defined job positions and the hierarchy depth
Dynamics CRM 2015 Hieararchy Security

Dynamics CRM 2015 Hieararchy Security

 

A user can be assigned to one position and hence get a Read, Write, Update, Append, AppendTo access to the lower positions’ data in the direct ancestor path. The non-direct higher positions, have Read-only access to the lower positions’. Following is a sample of the Position Hierarchy structure defined in CRM.

In this organization, CEO has full access to the data owned by HR Managers, Sales Managers and Service Managers. Sales managers has the full access to the data owned by Sales. Once you have position hierarchy defined in system then administrator can easily assign the user for the position to get the access accordingly.

Dynamics CRM 2015 Hierarchy Security #2

Dynamics CRM 2015 Hierarchy Security #2

Hopefully you find it useful!
Thank you,
Zhe Chen
Adisys Corporation

Time-Zone Independent Date Field in Dynamics CRM Online 2015

Time-Zone Independent Date Field in CRM Online 2015 Update

 Prior to CRM Online 2015 update 1, CRM saves date in UTC format in Database and show the local date time to user based on the login user’s time zone configuration. It works perfect if you have users around the world. However it might cause some confusions for below scenarios:

  • The exact date not depend on the time zone. Ex: birthday, Anniversary
  • The exact date time not depend on time zone. Ex: Hotel Check in/out Date and time
  • Data migration
  • System/Data Integration

With the latest CRM Online 2015 update release, Microsoft introduces the DateTimeBehavior property to define whether to store date and time values with or without time zone information. Followings are the definition for these three Behavior:

 

CRM Online Time Settings

CRM Online Time Settings

 

Member name and value Description
UserLocal
  • Stores the date and time value as UTC value in the system.
  • The retrieve operation returns the UTC value.
  • The update operation converts the UTC value to the current user’s time zone value, and then stores the updated value as is or as the equivalent UTC value depending on the kind (DateTimeKind) of the value specified for update. If the specified value is of UTC kind, it’s stored as is. Otherwise, the UTC-equivalent value is stored.
  • Retrieving the formatted value converts from UTC to the user’s current time zone based on the time zone and locale setting of the user.
  • For the OData endpoint, the attribute is exposed as DateTimeOffset.
  • This behavior is used for system attributes like CreatedOn and ModifiedOn, and cannot be changed. You should use this behavior for custom attributes where you want to store date and time values with the time zone information.
DateOnly
  • Stores the actual date value with the time value as 12:00 AM (00:00:00) in the system.
  • For the retrieve and update operations, no time zone conversion is performed, and the time value is always 12 AM (00:00:00).
  • Retrieving the formatted value displays the date value without any time zone conversion.
  • For the OData endpoint, the attribute is exposed as DateTimeOffset.
  • This behavior should be used for custom attributes that store birthdays and anniversaries, where the time information is not required.
TimeZoneIndependent
  • Stores the actual date and time values in the system regardless of the user time zone.
  • For the retrieve and update operations, no time zone conversion is performed, and actual date and time values are returned and updated respectively in the system regardless of the user time zone.
  • Retrieving the formatted value displays the date and time value (without any time zone conversion) based on the format as specified by the current user’s time zone and locale setting.
  • For the OData endpoint, the attribute is exposed as DateTimeOffset.
  • This behavior should be used for attributes that store information such as check in and check out time for hotels.

Hopefully you find it useful!
Thank you,
Zhe Chen

Optimistic concurrency in CRM Online 2015 Update 1

Another enterprise capability has been added to the Dynamics CRM 2015 Online Update 1. Kudo’s the Dynamics CRM PG team.  This is going to ease the Optimistic concurrency enablement in the product layer.

Prior to CRM online 2015 update 1, There were no concurrency lock checks out of the box and CRM always saves the value on the field level. The latest transaction will win (Overwrite). Developers might build some customization code to ensure the data integrity. However it requires lot of customization effort.

Provided in the latest SDK release is the ability to detect whether an entity record has changed on the server in the time between when your application retrieved the record and when it tries to update or delete that record.

The ConcurrencyBehavior Property specifies the type of optimistic concurrency behavior that should be performed by the Web service when processing this request:

Member name Description
AlwaysOverwrite Specifies the behavior where an update or delete operation is applied without regard to the version of the record in the database. Value = 2.If optimistic concurrency is not enabled for the target entity, the AlwaysOverwrite behavior is applied.
Default Specifies to use the default behavior. Value = 0. The default value is also used if no value is set in the ConcurrencyBehavior property of the request. The meaning of “default” is interpreted differently based on the calling context.
IfRowVersionMatches Specifies the behavior where an update or delete operation is only applied if the entity record in the database has the same row version as the entity or entity reference in the request. Value = 1.If no row version value is provided on the entity or entity references in the request, the request fails immediately.

The following sample code from SDK shows how to use optimistic concurrency for update and delete operations. The complete sample can be downloaded from MSDN: https://code.msdn.microsoft.com/Use-optimistic-concurrency-e0b0440d.

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);
}

Hopefully you find it useful!
Thank you,
Zhe Chen