call plugin on Ribbon button click in mscrm

call plugin on Ribbon button click in mscrm
///////////// one way
a button click is a client event, so at least a few javascript lines are required.
the easiest way in my opinion is to create a dummy entity and attach the plugin to the create event of records of this dummy entity.
the custom javascript will just create a record of this dummy entity using an odata call
///////////////another way
Create a dummy field and hide it in form. update the field value once button is clicked.
and you can call the plugin once the dummy fields value gets updated.

//Load the .js file on ribbon click with fucntion name "ribbonButtonClick"
/////javascript code
function ribbonButtonClick() {
    debugger;
    var recBillID = Xrm.Page.data.entity.getId().replace("{", "").replace("}", "");
    var count = Xrm.Page.getAttribute("apy_updatecount").getValue();
    if (count == null || count == undefined) {
        count = 1;
    }
    var entity = {};
    count = parseInt(count) + 1;
    entity.apy_updatecount = parseInt(count);
    //entity.stateCode = 0;
    //entity.statuscode = 621260000;
    var req = new XMLHttpRequest();
    req.open("PATCH", Xrm.Page.context.getClientUrl() + "/api/data/v8.0/apy_recurringbillings(" + recBillID + ")", false);
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version", "4.0");
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
    req.setRequestHeader("Prefer", "odata.include-annotations=\"*\"");
    req.onreadystatechange = function () {
        if (this.readyState === 4) {
            req.onreadystatechange = null;
            if (this.status === 204) {
                //Success - No Return Data - Do Something
                alert("Update Successfully");
            } else {
                Xrm.Utility.alertDialog(this.statusText);
            }
        }
    };
    req.send(JSON.stringify(entity));
    Xrm.Page.data.refresh();
}
/// plugin code
 public class RecurringBilling : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
           // ANetApiResponse subscriptionResponse = null;
            ARBCancelSubscriptionResponse cancelResponse;
            Entity recurringBillingEnt = null;
            ConnectionMode connectionMode;
            // CustomerGateway customerGateway;
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory organizationServiceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService _service = organizationServiceFactory.CreateOrganizationService(new Guid?(context.UserId));
            ITracingService _tracing = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            if (context.Depth > 1)
            {
                return;
            }
            if (!LicensingKeyValidate(_service))
            {
                throw new InvalidPluginExecutionException("Not a valid license key , please contact MTC.");
            }
            ARBCreateSubscriptionResponse createSubscriptionResponse = null;
            CreateSubscription subgatewayARB = null;
            string apiLogin = "";
            string apiTransactionKey = "";
            decimal num = new decimal(0, 0, 0, false, 2);
            Guid recBillEntCreaditCardId = Guid.Empty;
            Guid customerACId = Guid.Empty;
            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                recurringBillingEnt = _service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet(
                                  RecurringBillingAttributes.Name,                               
                                  RecurringBillingAttributes.SUBSCRIPTIONID,                               
                    ));
}
}
}
 if (context.MessageName.ToLower() == HelperClass.UPDATE)
                                {
                                    #region Cancel Subscription
                                    string subscriptionId = recurringBillingEnt.Attributes.Contains(RecurringBillingAttributes.SUBSCRIPTIONID) ? recurringBillingEnt.GetAttributeValue<string>(RecurringBillingAttributes.SUBSCRIPTIONID).ToString() : string.Empty;
                                    if (subscriptionId != string.Empty)
                                    {
                                        cancelResponse = "ok";
                                        if (cancelResponse.messages.resultCode.ToString() == "Ok")
                                        {
                                            SetStateRequest state = new SetStateRequest();
                                            state.EntityMoniker = new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId);
                                            state.State = new OptionSetValue(1);
                                            state.Status = new OptionSetValue(2);
                                            SetStateResponse stateSet = (SetStateResponse)_service.Execute(state);
                                        }
                                    }
                                    //throw new InvalidPluginExecutionException("HMM");
                                    #endregion
                                }
}

Comments

Popular posts from this blog

Meta Data Using WebApiRequest

Sample CRUD Operations Using C# in MSCRM

Basic Plugin Code in D365 using C#