Untitled

mail@pastecode.io avatar
unknown
plain_text
8 months ago
5.6 kB
3
Indexable
Never
Certainly, I've modified the JavaScript code to create appointments with the "scheduledstart" attribute set to the same time the next day and added a "participants" field that includes all contacts related to the account:

### JavaScript Code:

```javascript
var AccountRibbon = window.AccountRibbon || {};
(function () {

    // #region Button that creates appointments

    this.CreateAppointmentsCommand = function (formContext) {
        var alertStrings = { confirmButtonLabel: "Yes", text: "Are you sure you want to create appointments?", title: "Attention" };
        var alertOptions = { height: 120, width: 260 };
        Xrm.Navigation.openAlertDialog(alertStrings, alertOptions).then(
            function (success) {
                Xrm.Utility.showProgressIndicator("Processing...");

                var accountId = formContext.data.entity.getId();
                var execute_CreateAppointments_Request = {
                    // Parameters
                    Target: { "@odata.type": "Microsoft.Dynamics.CRM.account", accountid: accountId },

                    getMetadata: function () {
                        return {
                            boundParameter: null,
                            parameterTypes: {
                                Target: { typeName: "mscrm.crmbaseentity", structuralProperty: 5 }
                            },
                            operationType: 0, operationName: "yod_CreateAppointments"
                        };
                    }
                };

                Xrm.WebApi.execute(execute_CreateAppointments_Request).then(
                    function success(response) {
                        if (response.ok) {
                            alert("Appointments created successfully!");
                            Xrm.Utility.closeProgressIndicator();
                            console.log("Success");
                        }
                    }
                ).catch(function (error) {
                    Xrm.Utility.closeProgressIndicator();
                    console.log(error.message);
                });
            },
            function (error) {
                console.log(error.message);
            }
        );
    }
    // #endregion
}).call(AccountRibbon);
```

### C# Action Plugin Code:

```csharp
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Collections.Generic;
using System.Linq;

namespace TRIAL1.ACTION
{
    public class CreateAppointments : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                {
                    EntityReference accountRef = (EntityReference)context.InputParameters["Target"];
                    Entity account = service.Retrieve(accountRef.LogicalName, accountRef.Id, new ColumnSet("name"));

                    var accountId = account.Id;
                    var contacts = GetRelatedContacts(service, accountId);
                    CreateAppointmentsForContacts(service, contacts);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException($"Error CreateAppointments: {ex.Message}");
            }
        }

        private List<EntityReference> GetRelatedContacts(IOrganizationService service, Guid accountId)
        {
            var query = new QueryExpression("contact");
            query.ColumnSet = new ColumnSet("contactid");

            var linkEntity = new LinkEntity("contact", "account", "contactid", "primarycontactid", JoinOperator.Inner);
            linkEntity.LinkCriteria = new FilterExpression();
            linkEntity.LinkCriteria.AddCondition(new ConditionExpression("accountid", ConditionOperator.Equal, accountId));
            query.LinkEntities.Add(linkEntity);

            var contacts = service.RetrieveMultiple(query).Entities
                .Select(e => e.ToEntityReference())
                .ToList();

            return contacts;
        }

        private void CreateAppointmentsForContacts(IOrganizationService service, List<EntityReference> contacts)
        {
            foreach (var contactRef in contacts)
            {
                var appointment = new Entity("appointment");
                appointment.Attributes["scheduledstart"] = DateTime.Now.AddDays(1); // Set to the same time the next day
                appointment.Attributes["scheduledend"] = DateTime.Now.AddDays(1).AddHours(19); // Set to the same time the next day + 19 hours

                var participants = new EntityCollection(new List<EntityReference> { contactRef });
                appointment.Attributes["participants"] = participants;

                service.Create(appointment);
            }
        }
    }
}
```

Make sure to register the plugin on the `yod_CreateAppointments` message for the `account` entity.
Leave a Comment