Ejemplo n.º 1
0
        public static RuleAppliedBase Map(this RuleAppliedPOCO rulePoco)
        {
            var re = new RuleAppliedBase {
            };

            return(re);
        }
        public RuleAppliedBase GetBaseRuleApplied(int ruleAppliedId, string ruleTable)
        {
            RuleAppliedBase ret = null;

            try
            {
                var raf = new RuleAppliedFilter
                {
                    RuleAppliedId = ruleAppliedId,
                    RuleTableName = ruleTable,
                };

                return(_dal.GetRuleApplied(raf));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                throw;
            }
            return(ret);
        }
        public RuleAppliedBase GetRuleApplied(RuleAppliedFilter raf)
        {
            if (raf == null)
            {
                return(null);
            }
            if (raf.RuleAppliedId == null | raf.RuleAppliedId <= 0)
            {
                return(null);
            }
            if (raf.RuleTableName == null)
            {
                return(null);
            }

            RuleAppliedBase ret = null;

            using (var conn = new SqlConnection(_connString))
                using (var cmd = new SqlCommand("RulesEngine.spa_GetRuleApplied", conn))
                {
                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandTimeout = 360;

                    if (raf.RuleAppliedId != null)
                    {
                        cmd.Parameters.Add("@ruleAppliedId", SqlDbType.VarChar).Value = raf.RuleAppliedId;
                    }

                    cmd.Parameters.Add("@ruleAppliedTableName", SqlDbType.VarChar).Value = raf.RuleTableName;

                    conn.Open();

                    using (var reader = cmd.ExecuteReader())
                    {
                        if (!reader.Read())
                        {
                            return(null);
                        }

                        var subCId           = reader["RuleSubCategoryId"].ToString();
                        var applyOrder       = reader["ApplyOrder"].ToString();
                        var condCodeId       = reader["ConditionCodeId"].ToString();
                        var condCodeInputId  = reader["ConditionCodeInputTypeId"].ToString();
                        var condCodeOutputId = reader["ConditionCodeOutputTypeId"].ToString();

                        ret = new RuleAppliedBase
                        {
                            RuleCategoryId             = int.Parse(reader["RuleCategoryId"].ToString()),
                            RuleSubCategoryId          = string.IsNullOrWhiteSpace(subCId) ? (int?)null : int.Parse(subCId),
                            ApplyOrder                 = string.IsNullOrWhiteSpace(applyOrder) ? (int?)null : int.Parse(applyOrder),
                            CodeId                     = int.Parse(reader["MainCodeId"].ToString()),
                            ConditionCodeId            = string.IsNullOrWhiteSpace(condCodeId) ? (int?)null : int.Parse(condCodeId),
                            IsEnabled                  = bool.Parse(reader["IsEnabled"].ToString()),
                            RuleAppliedId              = int.Parse(reader["id"].ToString()),
                            RuleCodeInTypeId           = int.Parse(reader["CodeInputTypeId"].ToString()),
                            RuleCodeOutTypeId          = int.Parse(reader["CodeOutputTypeId"].ToString()),
                            RuleCodeConditionInTypeId  = string.IsNullOrWhiteSpace(condCodeInputId) ? (int?)null : int.Parse(condCodeInputId),
                            RuleCodeConditionOutTypeId = string.IsNullOrWhiteSpace(condCodeOutputId) ? (int?)null : int.Parse(condCodeOutputId)
                        };
                    }
                }

            return(ret);
        }
Ejemplo n.º 4
0
        public CompilerResults CompileRules(List <RuleAppliedBase> rules)
        {
            if (!rules.Any())
            {
                return(null);
            }

            List <int> rulesToPull = rules.Select(c => c.CodeId).ToList();

            rulesToPull.AddRange(rules.Where(c => c.ConditionCodeId != null).Select(c => (int)c.ConditionCodeId).ToList());

            _rulesDAL.DALCache.RefreshRuleCodes(rulesToPull, true);

            string catName = "", subCatName = "";

            RuleCategory a = _rulesDAL.DALCache.RuleCategories.FirstOrDefault(c =>
            {
                RuleAppliedBase ruleAppliedBase = rules.FirstOrDefault();
                return(ruleAppliedBase != null && c.RuleCategoryId == ruleAppliedBase.RuleCategoryId);
            });

            if (a != null)
            {
                catName = a.CategoryName;
            }

            RuleCategory b = _rulesDAL.DALCache.RuleCategories.FirstOrDefault(c =>
            {
                RuleAppliedBase ruleAppliedBase = rules.FirstOrDefault();
                return(ruleAppliedBase != null && c.RuleCategoryId == ruleAppliedBase.RuleSubCategoryId);
            });

            if (b != null)
            {
                subCatName = b.CategoryName;
            }

            var tempFileName = Guid.NewGuid().ToString();
            var realFileName = catName + "_" + subCatName + ".cs";

            var codeFileExists = false;
            var linesToRemove  = new List <RuleCacheRefresh>();

            //if the file already exists, we need to read through and get info on the what code was written out
            //we also need to copy over all code that has the same method signature into a new temp file
            //afterwards, we will insert the new/altered code at the end of the temp file and swap them out.
            if (File.Exists(realFileName))
            {
                linesToRemove = GetRuleInfoFromFile(realFileName);

                using (FileStream realFs = File.OpenRead(realFileName))
                    using (FileStream tempFs = File.Create(tempFileName))
                    {
                        PrepFile(realFs, tempFs, linesToRemove);
                    }

                codeFileExists = true;
            }

            _rulesDAL.GetRuleCode(_rulesDAL.DALCache.RuleCodes.Where(c => c.NeedsRefresh || !c.ExistsInCache).ToList());

            using (TextWriter tw = new StreamWriter(tempFileName, codeFileExists))
            {
                if (codeFileExists)
                {
                    foreach (RuleCacheRefresh ruleRemoved in linesToRemove)
                    {
                        RuleCodeCache code =
                            _rulesDAL.DALCache.RuleCodes.FirstOrDefault(d => d.RuleCodeId == ruleRemoved.CodeId);

                        if (code == null)
                        {
                            throw new NullReferenceException("code not found");
                        }

                        int?tempRuleAppId = null;

                        if (ruleRemoved.RuleAppliedId > 0)
                        {
                            tempRuleAppId = ruleRemoved.RuleAppliedId;
                        }

                        WriteRuleCodeToStream(tw, code, tempRuleAppId);
                    }
                }
                else
                {
                    tw.WriteLine(
                        "using System.Linq; using System.Collections; using System.Collections.Generic; namespace LawsonCS.RulesEngine { ");
                    //example
                    //public static class Validator_PostEnrollment
                    tw.WriteLine(" public static class " + catName + "_" + subCatName + "{");

                    foreach (RuleAppliedBase rule in rules)
                    {
                        RuleCodeCache code =
                            _rulesDAL.DALCache.RuleCodes.FirstOrDefault(d => d.RuleCodeId == rule.CodeId);

                        if (code == null)
                        {
                            throw new NullReferenceException("code not found");
                        }

                        //we only want to write the rule out if it is marked as needsRefresh
                        RuleCodeCache foundRuleCacheCheck =
                            _rulesDAL.DALCache.RuleCodes.FirstOrDefault(c => c.RuleCodeId == rule.CodeId);

                        if (foundRuleCacheCheck != null && foundRuleCacheCheck.NeedsRefresh)
                        {
                            WriteRuleCodeToStream(tw, code, rule.RuleAppliedId);
                        }
                    }

                    foreach (RuleAppliedBase ruleCond in rules.Where(c => c.ConditionCodeId != null))
                    {
                        if (ruleCond.ConditionCodeId == null)
                        {
                            continue;
                        }

                        RuleCodeCache code =
                            _rulesDAL.DALCache.RuleCodes.FirstOrDefault(
                                d => d.RuleCodeId == ruleCond.ConditionCodeId.Value);

                        if (code == null)
                        {
                            throw new NullReferenceException("code not found");
                        }

                        //we only want to write the rule out if it is marked as needsRefresh
                        RuleCodeCache foundRuleCacheCheck =
                            _rulesDAL.DALCache.RuleCodes.FirstOrDefault(c => c.RuleCodeId == ruleCond.CodeId);

                        if (foundRuleCacheCheck != null && foundRuleCacheCheck.NeedsRefresh)
                        {
                            WriteRuleCodeToStream(tw, code, null);
                        }
                    }
                }

                foreach (var s in _codeFooter)
                {
                    tw.WriteLine(s);
                }

                tw.Flush();
            }

            foreach (RuleCodeCache ruleCodeCache in _rulesDAL.DALCache.RuleCodes)
            {
                ruleCodeCache.CodeText     = null;
                ruleCodeCache.NeedsRefresh = false;
            }

            File.Copy(tempFileName, realFileName, true);
            File.Copy(tempFileName, ConfigurationManager.AppSettings["NonStandardLogLocation"] + "\\" + DateTime.Now.ToString("yy-MM-dd@HH mm ss") + "_" + realFileName, true);

            File.Delete(tempFileName);
            File.Delete(_ruleTable + ".dll");

            var compilerparams = new CompilerParameters()
            {
                GenerateExecutable      = false,
                GenerateInMemory        = false,
                IncludeDebugInformation = false,
                TreatWarningsAsErrors   = false,
                CompilerOptions         = string.Format("/lib:{0}", AppDomain.CurrentDomain.BaseDirectory),
                OutputAssembly          = _ruleTable + ".dll",
            };

            List <string> fileList = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory).Where(c => c.Substring(c.Length - 3) == "dll").ToList();

            compilerparams.ReferencedAssemblies.AddRange(fileList.ToArray());
            compilerparams.ReferencedAssemblies.AddRange(Directory.GetFiles(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETCore\v4.5").Where(c => c.EndsWith(".dll") && !c.EndsWith("mscorlib.dll")).ToArray());

            CompilerResults results = CodeDomProvider.CreateProvider("CSharp").CompileAssemblyFromFile(compilerparams, realFileName);

            if (results.Errors.HasErrors)
            {
                throw new Exception(results.Errors[0].ErrorText);
            }

            return(results);
        }