This helper simplifies the integration platform functions.

Code

using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace *YOUR_NAMESPACE*.Helpers
{
    public class CopylIntegrationPlatformHelper
    {
        
        public CopylIntegrationPlatformHelper()
        {
           
        }

        public async Task SendEventToCIPAsync(
                                  IConfiguration configuration,
                                  dynamic _obj,
                                  string triggerName,
                                  string authorization,
                                  string[]? credentials = null) // Accept an array of key-value pair strings
        {
            // Parse and validate credentials if provided
            if (credentials != null && credentials.Length > 0)
            {
                // Parse credentials into a dictionary
                var credentialDictionary = ParseCredentials(credentials);

                bool allCredentialsValid = await ValidateCredentialsExternallyAsync(configuration, credentialDictionary, Authorization).ConfigureAwait(false);
                if (!allCredentialsValid)
                {
                    return; // Exit if any credential is invalid
                }
            }
            // Post to Copyl Integration Platform
            try
            {
                CopylHelper.Entities.IntegrationAppTriggerEventDTO _triggerEvent = new();
                _triggerEvent.SysCode = configuration["AppSettings:AppName"] + "." + triggerName;
                _triggerEvent.EnterpriseId = new Guid("*YOUR_ENTERPRISEID*");
                _triggerEvent.ApiKey = new Guid("*YOUR_APIKEY*");
                _triggerEvent.Authorization = authorization;
                _triggerEvent.Data = JsonConvert.SerializeObject(_obj, new Newtonsoft.Json.Converters.ExpandoObjectConverter());

                // Call the PublishTriggerToCopylAsync method
                _ = await CopylHelper.Trigger.PublishTriggerToCopylAsync(
                    _triggerEvent,
                    configuration["AppSettings:OcpApimSubscriptionKey"]).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                //_logger.LogError(ex,$"Unhandled exception when posting trigger to Copyl app: '{triggerName}'. Error: {ex.Message}");
            }
        }

        // Helper method for parsing credentials
        private Dictionary<string, string> ParseCredentials(string[] credentials)
        {
            var credentialDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);

            foreach (var credential in credentials)
            {
                var parts = credential.Split(':', 2); // Split into key and value
                if (parts.Length == 2)
                {
                    credentialDictionary[parts[0].Trim()] = parts[1].Trim(); // Add to dictionary
                }
                else
                {
                   // _logger.LogError($"Invalid credential format: {credential}. Expected format: 'key: value'.");
                }
            }

            return credentialDictionary;
        }

        // Updated validation method       
        private async Task<bool> ValidateCredentialsExternallyAsync(IConfiguration configuration, Dictionary<string, string> credentialDictionary, string Authorization)
        {
            var apiUrl = "<https://api.copyl.com/ms/IntegrationAppCredentialParams/validate>";
            var sysCode = configuration["AppSettings:AppName"];

            var requestBody = new
            {
                SysCode = sysCode,
                Credentials = credentialDictionary
            };

            using var client = new HttpClient();
            var jsonContent = new StringContent(JsonConvert.SerializeObject(requestBody), Encoding.UTF8, "application/json");

            // Include headers as required
            client.DefaultRequestHeaders.Add("Authorization", Authorization);
            client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", configuration["AppSettings:OcpApimSubscriptionKey"]);
            client.DefaultRequestHeaders.Add("Accept-Language", "en");

            var response = await client.PostAsync(apiUrl, jsonContent);
            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadAsStringAsync();
                return bool.TryParse(result, out var isValid) && isValid;
            }

            return false;
        }
    }

}

See also

How to submit Triggers that only reaches selected Subscribers