public object ExecuteEmailRetriever(EbApi Api, Service Service, EbStaticFileClient FileClient, bool isMq)
        {
            try
            {
                EbConnectionFactory EbConnectionFactory = new EbConnectionFactory(Api.SolutionId, Api.Redis);
                if (EbConnectionFactory.EmailRetrieveConnection[this.MailConnection] != null)
                {
                    RetrieverResponse retrieverResponse = EbConnectionFactory.EmailRetrieveConnection[this.MailConnection].Retrieve(Service, this.DefaultSyncDate, FileClient, Api.SolutionId, isMq, SubmitAttachmentAsMultipleForm);

                    EbWebForm _form = Api.Redis.Get <EbWebForm>(this.Reference);
                    SchemaHelper.GetWebFormSchema(_form);
                    if (!(_form is null))
                    {
                        WebformData data = _form.GetEmptyModel();

                        foreach (RetrieverMessage _m in retrieverResponse?.RetrieverMessages)
                        {
                            InsertFormData(_form, data, _m, this.Reference, Api.SolutionId, Api.UserObject, Api.Redis, Service, EbConnectionFactory);
                        }
                    }
                    else
                    {
                        throw new ApiException("[ExecuteEmailRetriever], form objects is not in redis.");
                    }
                }
                else
                {
                    throw new ApiException("[ExecuteEmailRetriever], mail connection doesn't exist.");
                }
            }
        public object ExecuteDataWriter(EbApi Api)
        {
            List <DbParameter> dbParams = new List <DbParameter>();

            try
            {
                EbDataWriter dataWriter = Api.GetEbObject <EbDataWriter>(Reference, Api.Redis, Api.ObjectsDB);

                List <Param> InputParams = dataWriter.GetParams(null);

                Api.FillParams(InputParams);

                foreach (Param param in InputParams)
                {
                    dbParams.Add(Api.DataDB.GetNewParameter(param.Name, (EbDbTypes)Convert.ToInt32(param.Type), param.ValueTo));
                }

                int status = Api.DataDB.DoNonQuery(dataWriter.Sql, dbParams.ToArray());

                if (status > 0)
                {
                    Api.ApiResponse.Message.Description = status + "row inserted";
                    return(true);
                }
                else
                {
                    Api.ApiResponse.Message.Description = status + "row inserted";
                    return(false);
                }
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteDataWriter], " + ex.Message);
            }
        }
        public object ExecuteFormResource(EbApi Api, Service Service)
        {
            try
            {
                int     RecordId = 0;
                NTVDict _params  = new NTVDict();
                foreach (KeyValuePair <string, object> p in Api.GlobalParams)
                {
                    EbDbTypes _type;
                    if (p.Value is int)
                    {
                        _type = EbDbTypes.Int32;
                    }
                    else //check other types here if required
                    {
                        _type = EbDbTypes.String;
                    }
                    _params.Add(p.Key, new NTV()
                    {
                        Name = p.Key, Type = _type, Value = p.Value
                    });
                }

                if (!string.IsNullOrWhiteSpace(this.DataIdParam) && Api.GlobalParams.ContainsKey(this.DataIdParam))
                {
                    int.TryParse(Convert.ToString(Api.GlobalParams[this.DataIdParam]), out RecordId);
                }
                InsertOrUpdateFormDataRqst request = new InsertOrUpdateFormDataRqst
                {
                    RefId        = this.Reference,
                    PushJson     = this.PushJson,
                    UserId       = Api.UserObject.UserId,
                    UserAuthId   = Api.UserObject.AuthId,
                    RecordId     = RecordId,
                    LocId        = Convert.ToInt32(Api.GlobalParams["eb_loc_id"]),
                    SolnId       = Api.SolutionId,
                    WhichConsole = "uc",
                    FormGlobals  = new FormGlobals {
                        Params = _params
                    },
                    //TransactionConnection = TransactionConnection
                };

                EbConnectionFactory        ebConnection = new EbConnectionFactory(Api.SolutionId, Api.Redis);
                InsertOrUpdateFormDataResp resp         = EbFormHelper.InsertOrUpdateFormData(request, Api.DataDB, Service, Api.Redis, ebConnection);

                if (resp.Status == (int)HttpStatusCode.OK)
                {
                    return(resp.RecordId);
                }
                else
                {
                    throw new Exception(resp.Message);
                }
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteFormResource], " + ex.Message);
            }
        }
        public bool ExecuteEmail(EbApi Api, RabbitMqProducer MessageProducer3)
        {
            bool status;

            try
            {
                EbEmailTemplate emailTemplate = Api.GetEbObject <EbEmailTemplate>(this.Reference, Api.Redis, Api.ObjectsDB);

                List <Param> InputParams = EbApiHelper.GetEmailParams(emailTemplate, Api.Redis, Api.ObjectsDB);

                Api.FillParams(InputParams);

                MessageProducer3.Publish(new EmailAttachmentRequest()
                {
                    ObjId      = Convert.ToInt32(this.Reference.Split(CharConstants.DASH)[3]),
                    Params     = InputParams,
                    UserId     = Api.UserObject.UserId,
                    UserAuthId = Api.UserObject.AuthId,
                    SolnId     = Api.SolutionId,
                    RefId      = this.Reference
                });

                status = true;

                string msg = $"The mail has been sent successfully to {emailTemplate.To} with subject {emailTemplate.Subject} and cc {emailTemplate.Cc}";

                Api.ApiResponse.Message.Description = msg;
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteEmail], " + ex.Message);
            }
            return(status);
        }
        public object ExecuteDataReader(EbApi Api)
        {
            EbDataSet dataSet;

            try
            {
                EbDataReader dataReader = Api.GetEbObject <EbDataReader>(this.Reference, Api.Redis, Api.ObjectsDB);

                List <DbParameter> dbParameters = new List <DbParameter>();

                List <Param> InputParams = dataReader.GetParams((RedisClient)Api.Redis);

                Api.FillParams(InputParams);

                foreach (Param param in InputParams)
                {
                    dbParameters.Add(Api.DataDB.GetNewParameter(param.Name, (EbDbTypes)Convert.ToInt32(param.Type), param.ValueTo));
                }

                dataSet = Api.DataDB.DoQueries(dataReader.Sql, dbParameters.ToArray());
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteDataReader], " + ex.Message);
            }
            return(dataSet);
        }
 public string ReplacePlaceholders(string text, EbApi Api)
 {
     if (!String.IsNullOrEmpty(text))
     {
         string pattern = @"\{{(.*?)\}}";
         IEnumerable <string> matches = Regex.Matches(text, pattern).OfType <Match>().Select(m => m.Groups[0].Value).Distinct();
         foreach (string _col in matches)
         {
             try
             {
                 string parameter_name = _col.Replace("{{", "").Replace("}}", "");
                 if (Api.GlobalParams.ContainsKey(parameter_name))
                 {
                     string value = Api.GlobalParams[parameter_name].ToString();
                     text = text.Replace(_col, value);
                 }
             }
             catch (Exception ex)
             {
                 throw new ApiException("[Replace Placeholders in Url], parameter - " + _col + ". " + ex.Message);
             }
         }
     }
     return(text);
 }
        public object ExecuteThirdPartyApi(EbThirdPartyApi thirdPartyResource, EbApi Api)
        {
            Uri uri = new Uri(ReplacePlaceholders(thirdPartyResource.Url, Api));

            object result;

            try
            {
                RestClient client = new RestClient(uri.GetLeftPart(UriPartial.Authority));

                RestRequest request = thirdPartyResource.CreateRequest(uri.PathAndQuery, Api.GlobalParams);

                List <Param> _params = thirdPartyResource.GetParameters(Api.GlobalParams) ?? new List <Param>();

                if (thirdPartyResource.Method == ApiMethods.POST && thirdPartyResource.RequestFormat == ApiRequestFormat.Raw)
                {
                    if (_params.Count > 0)
                    {
                        RequestParam requestParam = this.Parameters[0];
                        if (!string.IsNullOrEmpty(requestParam.Value) && requestParam.EnableEncryption)
                        {
                            string ciphertext = EbEncryption.ExecuteEncrypt(_params[0].Value, requestParam.KeyName, requestParam.DataReader, Api, requestParam.EncryptionAlgorithm);
                            request.AddJsonBody(ciphertext);
                        }
                        else
                        {
                            request.AddJsonBody(_params[0].Value);
                        }
                    }
                }
                else
                {
                    foreach (Param param in _params)
                    {
                        request.AddParameter(param.Name, param.ValueTo);
                    }
                }

                IRestResponse resp = client.Execute(request);

                if (resp.IsSuccessful)
                {
                    result = resp.Content;
                }
                else
                {
                    throw new Exception($"Failed to execute api [{thirdPartyResource.Url}], {resp.ErrorMessage}, {resp.Content}");
                }

                if (this.EnableDecryption)
                {
                    result = EbEncryption.ExecuteDecrypt(resp.Content, this.KeyName, this.DataReader, Api, this.EncryptionAlgorithm);
                }
            }
            catch (Exception ex)
            {
                throw new Exception("[ExecuteThirdPartyApi], " + ex.Message);
            }
            return(result);
        }
        public EbApi GetApi(string RefId, IRedisClient Redis, IDatabase ObjectsDB, IDatabase DataDB)
        {
            EbApi Api = GetEbObject <EbApi>(RefId, Redis, ObjectsDB);

            Api.Redis     = Redis;
            Api.ObjectsDB = ObjectsDB;
            Api.DataDB    = DataDB;
            return(Api);
        }
        public object ExecuteConnectApi(EbApi Api, Service Service)
        {
            ApiResponse resp = null;

            try
            {
                EbApi apiObject = Api.GetEbObject <EbApi>(this.Reference, Api.Redis, Api.ObjectsDB);

                if (apiObject.Name.Equals(Api.Name))
                {
                    Api.ApiResponse.Message.ErrorCode   = ApiErrorCode.ResourceCircularRef;
                    Api.ApiResponse.Message.Description = "Calling Api from the same not allowed, terminated due to circular reference";

                    throw new ApiException("[ExecuteConnectApi], Circular refernce");
                }
                else
                {
                    List <Param> InputParam = EbApiHelper.GetReqJsonParameters(apiObject.Resources, Api.Redis, Api.ObjectsDB);


                    Api.FillParams(InputParam);

                    Dictionary <string, object> d = InputParam.Select(p => new { prop = p.Name, val = p.Value }).ToDictionary(x => x.prop, x => x.val as object);

                    string version = this.Version.Replace(".w", "");

                    resp = Service.Gateway.Send(new ApiMqRequest
                    {
                        Name       = this.RefName,
                        Version    = version,
                        Data       = d,
                        SolnId     = Api.SolutionId,
                        UserAuthId = Api.UserObject.AuthId,
                        UserId     = Api.UserObject.UserId
                    });

                    if (resp.Message.ErrorCode == ApiErrorCode.NotFound)
                    {
                        Api.ApiResponse.Message.ErrorCode   = ApiErrorCode.ResourceNotFound;
                        Api.ApiResponse.Message.Description = resp.Message.Description;

                        throw new ApiException("[ExecuteConnectApi], resource api not found");
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteConnectApi], " + ex.Message);
            }
            return(resp);
        }
        public object ExecuteSqlFunction(EbApi Api)
        {
            SqlFuncTestResponse response;

            try
            {
                EbSqlFunction sqlFunc = Api.GetEbObject <EbSqlFunction>(this.Reference, Api.Redis, Api.ObjectsDB);

                List <Param> InputParams = sqlFunc.GetParams(null);

                Api.FillParams(InputParams);

                response = EbObjectsHelper.SqlFuncTest(InputParams, sqlFunc.Name, Api.ObjectsDB);
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteSqlFunction], " + ex.Message);
            }
            return(response);
        }
        public static string ExecuteDecrypt(String ciphertext, string KeyName, string Refid, EbApi Api, EncryptionAlgorithm EncryptionAlgorithm)
        {
            string pri_key   = "";
            string plaintext = "";

            try
            {
                if (!String.IsNullOrEmpty(KeyName))
                {
                    pri_key = Api.Redis.Get <string>("privatekey_" + Api.SolutionId + "_" + KeyName);
                }

                if (String.IsNullOrEmpty(pri_key) && !String.IsNullOrEmpty(Refid))
                {
                    EbDataReader dataReader = Api.GetEbObject <EbDataReader>(Refid, Api.Redis, Api.ObjectsDB);

                    List <DbParameter> dbParameters = new List <DbParameter> {
                        Api.DataDB.GetNewParameter("keyname", EbDbTypes.String, KeyName)
                    };

                    EbDataSet dataSet = Api.DataDB.DoQueries(dataReader.Sql, dbParameters.ToArray());
                    pri_key = dataSet.Tables?[0].Rows[0]["key"].ToString();

                    Api.Redis.Set <string>("privatekey_" + Api.SolutionId + "_" + KeyName, pri_key);
                }

                if (EncryptionAlgorithm == EncryptionAlgorithm.RSA)
                {
                    plaintext = RSADecrypt(ciphertext, pri_key);
                }
            }
            catch (Exception ex)
            {
                throw new ApiException("[ExecuteEncrypt], " + ex.Message);
            }
            return(plaintext);
        }
        public object ExecuteScript(EbApi Api, RabbitMqProducer mqp, Service service, EbStaticFileClient Fileclient)
        {
            ApiGlobalParent global;

            if (this.EvaluatorVersion == EvaluatorVersion.Version_1)
            {
                global = new ApiGlobals(Api.GlobalParams);
            }
            else
            {
                global = new ApiGlobalsCoreBase(Api.GlobalParams);
            }

            global.ResourceValueByIndexHandler += (index) =>
            {
                object resourceValue = Api.Resources[index].Result;

                if (resourceValue != null && resourceValue is string converted)
                {
                    if (converted.StartsWith("{") && converted.EndsWith("}") || converted.StartsWith("[") && converted.EndsWith("]"))
                    {
                        string formated = converted.Replace(@"\", string.Empty);
                        return(JObject.Parse(formated));
                    }
                }
                return(resourceValue);
            };

            global.ResourceValueByNameHandler += (name) =>
            {
                int index = Api.Resources.GetIndex(name);

                object resourceValue = Api.Resources[index].Result;

                if (resourceValue != null && resourceValue is string converted)
                {
                    if (converted.StartsWith("{") && converted.EndsWith("}") || converted.StartsWith("[") && converted.EndsWith("]"))
                    {
                        string formated = converted.Replace(@"\", string.Empty);
                        return(JObject.Parse(formated));
                    }
                }
                return(resourceValue);
            };

            global.GoToByIndexHandler += (index) =>
            {
                Api.Step = index;
                Api.Resources[index].Result = EbApiHelper.GetResult(Api.Resources[index], Api, mqp, service, Fileclient);
            };

            global.GoToByNameHandler += (name) =>
            {
                int index = Api.Resources.GetIndex(name);
                Api.Step = index;
                Api.Resources[index].Result = EbApiHelper.GetResult(Api.Resources[index], Api, mqp, service, Fileclient);
            };

            global.ExitResultHandler += (obj) =>
            {
                ApiScript script = new ApiScript
                {
                    Data = JsonConvert.SerializeObject(obj),
                };
                Api.ApiResponse.Result = script;
                Api.Step = Api.Resources.Count - 1;
            };

            ApiResources lastResource = Api.Step == 0 ? null : Api.Resources[Api.Step - 1];

            if (this.EvaluatorVersion == EvaluatorVersion.Version_1 && lastResource?.Result is EbDataSet dataSet)
            {
                (global as ApiGlobals).Tables = dataSet.Tables;
            }

            ApiScript result;

            try
            {
                result = this.Execute(global);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(result);
        }