Using ExecuteTransaction in Dynamics 365 C#

Leave a comment

ExecuteTransaction can be used in Dynamics 365 to execute requests as a transaction.

Here’s some sample code:

[sourcecode language=”CSharp”] using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Microsoft.Xrm.Tooling.Connector;
using Microsoft.Xrm.Sdk;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using System.ServiceModel;

namespace Carl.Dynamics365ExecuteTransaction
{
class Program
{
static void Main(string[] args)
{
try
{
var connectionString = @"AuthType = Office365; Url = https://yourorg.crm.dynamics.com/;Username=your@email.com;Password=yourpassword";
CrmServiceClient conn = new CrmServiceClient(connectionString);

IOrganizationService service;
service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

var request = new ExecuteTransactionRequest()
{
Requests = new OrganizationRequestCollection()
};

for (int i = 0; i < 5; i++)
{
Entity contact = new Entity("contact");
contact["firstname"] = "Bob " + i.ToString();
contact["lastname"] = "Smith";

var createRequest = new CreateRequest()
{
Target = contact
};
request.Requests.Add(createRequest);
}

Console.WriteLine("Before execute");
var response = (ExecuteTransactionResponse)service.Execute(request);
Console.WriteLine("After execute");

foreach (var r in response.Responses)
{
var createResponse = (CreateResponse)r;
Console.WriteLine("Contact: " + createResponse.id);
}

Console.ReadLine();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadLine();
}
}
}
}
[/sourcecode]

 

Carl de Souza
Keep learning. Keep building.

Explore AI, agents & Microsoft technology.

I share practical ideas, tutorials, and videos about AI, AI agents, Microsoft technologies, and the Power Platform.

Subscribe on YouTube →
Carl de Souza Enterprise Architect at Microsoft · AI Technology Expert

Leave a Reply

Your email address will not be published. Required fields are marked *