This helper simplifies the integration platform functions.

See also

How to submit Triggers that only reaches selected Subscribers

Code

using CopylAPI_Services.Context;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json;

namespace *YOUR_NAMESPACE*.Helpers
{
    public class CopylIntegrationPlatformHelper
    {
        private readonly CopylContext _context;
        private readonly ILogger _logger;

        public CopylIntegrationPlatformHelper(CopylContext copylContext, ILogger logger)
        {
            _context = copylContext;
            _logger = logger;
        }

        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 ValidateCredentialsAsync(configuration, credentialDictionary);
                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"]);
            }
            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> ValidateCredentialsAsync(IConfiguration configuration, Dictionary<string, string> credentialDictionary)
        {
            var sysCode = configuration["AppSettings:AppName"];

            // Retrieve integration apps with the specified name
            IList<Guid> integrationAppIds = await _context.IntegrationApps
                .AsNoTracking()
                .Where(x => x.SysCode == sysCode)
                .Select(x => x.Id)
                .ToListAsync();

            // Validate each credential key-value pair
            foreach (var credential in credentialDictionary)
            {
                string key = credential.Key;
                string value = credential.Value;

                //bool credentialIsValid = await _context.IntegrationAppCredentialParams
                //    .AnyAsync(c => c.Name == $"{key}: {value}" && integrationAppIds.Contains(c.IntegrationAppId));
                bool credentialIsValid = await _context.IntegrationAppCredentialParams
                   .AnyAsync(c => c.Name == key && c.Description == value && integrationAppIds.Contains(c.IntegrationAppId));

                if (!credentialIsValid)
                {
                    return false; // Return false if any credential is invalid
                }
            }

            return true; // All credentials are valid
        }
    }

}