Untitled

mail@pastecode.io avatar
unknown
plain_text
20 days ago
4.9 kB
3
Indexable
Never
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# Code (for the Custom Action Plugin):
csharp
Copy code
using System;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

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"];

                    // Retrieve related contacts
                    QueryExpression query = new QueryExpression("contact");
                    query.ColumnSet = new ColumnSet("contactid");
                    query.Criteria.AddCondition("parentcustomerid", ConditionOperator.Equal, accountRef.Id);
                    EntityCollection contacts = service.RetrieveMultiple(query);

                    DateTime nextDay = DateTime.Now.AddDays(1).Date;
                    DateTime scheduledStart = new DateTime(nextDay.Year, nextDay.Month, nextDay.Day, 9, 0, 0); // 9:00 AM
                    DateTime scheduledEnd = new DateTime(nextDay.Year, nextDay.Month, nextDay.Day, 19, 0, 0);   // 7:00 PM

                    foreach (Entity contact in contacts.Entities)
                    {
                        Entity appointment = new Entity("appointment");
                        appointment.Attributes.Add("subject", "Meeting with " + contact.GetAttributeValue<string>("fullname"));
                        appointment.Attributes.Add("scheduledstart", scheduledStart);
                        appointment.Attributes.Add("scheduledend", scheduledEnd);

                        EntityReference participant = new EntityReference("contact", contact.Id);
                        appointment.Attributes.Add("requiredattendees", new EntityReference[] { participant });

                        service.Create(appointment);
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException($"Error CreateAppointments: {ex.Message}");
            }
        }
    }
}
Leave a Comment