private string HandleSBNErrorNotification(string inputXML)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            string result = "200";
            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNErrorNotification1));
            SBNErrorNotification1 errorNotification;

            using (TextReader reader = new StringReader(inputXML))
            {
                errorNotification = (SBNErrorNotification1)serializer.Deserialize(reader);
            }


            // check to see if it is simply a problem with an old account number.
            if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11845")) // Transaction not allowed - Duplicate Client event exists )
            {
                Log.Logger.Error($"CRA has rejected the message due to an incorrect business number.  The business in question may have had multiple business numbers in the past and the number in the record is no longer valid.  Please correct the business number for record with partnernote of {errorNotification.header.partnerNote}");
            }
            else if (errorNotification.body.validationErrors[0].errorMessageNumber.Equals("11409")) // Old account number.
            {
                Log.Logger.Information("Error is old account number is already associated with another account.  Retrying.");
                // retry the request with a higher increment.

                string licenceGuid   = OneStopUtils.GetGuidFromPartnerNote(errorNotification.header.partnerNote);
                int    currentSuffix = OneStopUtils.GetSuffixFromPartnerNote(errorNotification.header.partnerNote, Log.Logger);

                string cacheKey = "_BPAR_" + licenceGuid;

                Log.Logger.Information($"Reading cache value for key {cacheKey}");

                if (!_cache.TryGetValue(cacheKey, out int suffixLimit))
                {
                    suffixLimit = 10;
                }

                // sanity check
                if (currentSuffix < suffixLimit)
                {
                    currentSuffix++;
                    Log.Logger.Information($"Starting resend of send program account request message, with new value of {currentSuffix}");

                    var patchRecord = new MicrosoftDynamicsCRMadoxioLicences
                    {
                        AdoxioBusinessprogramaccountreferencenumber = currentSuffix.ToString()
                    };
                    dynamicsClient.Licenceses.Update(licenceGuid, patchRecord);

                    BackgroundJob.Schedule(() => new OneStopUtils(_configuration, _cache).SendProgramAccountRequestREST(null, licenceGuid, currentSuffix.ToString("D3"), null) // zero pad 3 digit.
                                           , TimeSpan.FromSeconds(30));                                                                                                        // Try again after 30 seconds
                }
                else
                {
                    Log.Logger.Error($"Skipping resend of send program account request message as there have been too many tries({currentSuffix} - {suffixLimit}) Partner Note is partner note {errorNotification.header.partnerNote}");
                }
            }
            else
            {
                Log.Logger.Error($"Received error notification for record with partner note {errorNotification.header.partnerNote} Error Code is  {errorNotification.body.validationErrors[0].errorMessageNumber}. Error Text is {errorNotification.body.validationErrors[0].errorMessageText} {inputXML}");
            }

            return(result);
        }
        private string HandleSBNCreateProgramAccountResponse(string inputXML)
        {
            IDynamicsClient dynamicsClient = DynamicsSetupUtil.SetupDynamics(_configuration);

            Log.Logger.Information("Reached HandleSBNCreateProgramAccountResponse");
            if (!_env.IsProduction())
            {
                Log.Logger.Information($"InputXML is: {inputXML}");
            }

            string httpStatusCode = "200";

            // deserialize the inputXML
            var serializer = new XmlSerializer(typeof(SBNCreateProgramAccountResponse1));
            SBNCreateProgramAccountResponse1 licenseData;

            using (TextReader reader = new StringReader(inputXML))
            {
                licenseData = (SBNCreateProgramAccountResponse1)serializer.Deserialize(reader);
            }


            string licenceNumber = OneStopUtils.GetLicenceNumberFromPartnerNote(licenseData.header.partnerNote);

            Log.Logger.Information($"Getting licence with number of {licenceNumber}");

            // Get licence from dynamics

            string businessProgramAccountNumber = "1";
            MicrosoftDynamicsCRMadoxioLicences licence;

            string filter = $"adoxio_licencenumber eq '{licenceNumber}'";

            try
            {
                licence = dynamicsClient.Licenceses.Get(filter: filter).Value.FirstOrDefault();
                businessProgramAccountNumber = licenseData.body.businessProgramAccountNumber.businessProgramAccountReferenceNumber;
            }
            catch (Exception e)
            {
                Log.Logger.Error($"Unable to get licence data for licence number {licenceNumber} {e.Message}");
                licence = null;
            }


            if (licence == null)
            {
                Log.Logger.Information("licence is null - returning 400.");
                httpStatusCode = "400";
            }
            else
            {
                Log.Logger.Information("Licence record retrieved from Dynamics.");
                //save the program account number to dynamics

                int    tempBpan      = int.Parse(businessProgramAccountNumber);
                string sanitizedBpan = tempBpan.ToString();

                MicrosoftDynamicsCRMadoxioLicences pathLicence = new MicrosoftDynamicsCRMadoxioLicences
                {
                    AdoxioBusinessprogramaccountreferencenumber = sanitizedBpan,
                };
                Log.Logger.Information("Sending update to Dynamics for BusinessProgramAccountNumber.");
                try
                {
                    dynamicsClient.Licenceses.Update(licence.AdoxioLicencesid, pathLicence);
                    Log.Logger.Information($"ONESTOP Updated Licence {licenceNumber} record {licence.AdoxioLicencesid} to {businessProgramAccountNumber}");
                }
                catch (HttpOperationException odee)
                {
                    Log.Logger.Error(odee, "Error updating Licence {licence.AdoxioLicencesid}");
                    // fail if we can't get results.
                    throw (odee);
                }
                // now clear out the cache item.
                ClearProgramAccountDetails(licence.AdoxioLicencesid, dynamicsClient, inputXML);



                //Trigger the Send ProgramAccountDetailsBroadcast Message
                BackgroundJob.Enqueue(() => new OneStopUtils(_configuration, _cache).SendProgramAccountDetailsBroadcastMessageRest(null, licence.AdoxioLicencesid));

                Log.Logger.Information("send program account details broadcast done.");
            }

            return(httpStatusCode);
        }