private void Cb_RuleTemplate_Checkchanged(object sender, RoutedEventArgs e) { CheckBox checkBox = sender as CheckBox; RuleTemplate curTemplate = RuleTemplate.GetByName(checkBox.Content as string); Rule selectedRule = Lv_RulesOverview.SelectedItem as Rule; if (curTemplate != null && selectedRule != null && checkBox.IsChecked != null) { bool hasTemplate = checkBox.IsChecked.Value; if (hasTemplate) { selectedRule.Templates.Add(curTemplate); selectedRule.CreateTemplateProperties(); } else { foreach (string prop in curTemplate.RequiredProperties.Keys) { selectedRule.Properties.Remove(prop); } selectedRule.Templates.Remove(curTemplate); } } StoreChanged = true; UpdateLists(); }
public void TestSingleValidation() { RuleTemplate basicRuleTemplate = RuleTemplate.GetByName("TestTemplate"); //#1: Invalid because required prop is not present Rule inValidRule1 = new Rule(basicRuleTemplate); //#2: Invalid because required prop is null Rule inValidRule2 = new Rule(basicRuleTemplate); inValidRule2.Properties.Add("TestKey", null); //#3 Invalid because required prop is wrong type Rule inValidRule3 = new Rule(basicRuleTemplate); inValidRule3.Properties.Add("TestKey", 1.1); //Valid because required prop is set and is of the right type Rule validRule = new Rule(basicRuleTemplate); validRule.Properties.Add("test", null); validRule.Properties.Add("TestKey", 1); Assert.IsFalse(inValidRule1.IsValid); Assert.IsFalse(inValidRule2.IsValid); Assert.IsFalse(inValidRule3.IsValid); Assert.IsTrue(validRule.IsValid); }
public void TestRuleStore() { string fileLoc = "Unittest.json"; string key = "password123"; string templateName = "Empty"; string saveKey = "testKey"; string saveValue = "testVal"; if (File.Exists(fileLoc)) { File.Delete(fileLoc); } RuleStore newStore = RuleStore.Create(fileLoc, key); newStore.Rules.Add( new Rule(RuleTemplate.GetByName(templateName)) { Properties = new Dictionary <string, object>() { { saveKey, saveValue }, { "key2", 1 } } }); newStore.WriteToDisc(); var readStore = RuleStore.Open(fileLoc, key); Assert.AreEqual(saveValue, readStore.Rules.First().Properties[saveKey]); Assert.IsTrue(readStore.Rules.First().Templates.First().Name == templateName); File.Delete(fileLoc); }
public IList <RuleTemplate> GetRuleTemplates(decimal[] ruleTemplateIds) { if (ruleTemplateIds == null) { return(new List <RuleTemplate>()); } RuleTemplate ruleTemplateAlias = null; IList <decimal> accessableIDs = ruleTemplateIds; IList <RuleTemplate> result = new List <RuleTemplate>(); IList <RuleTemplate> ruleTemplateList = new List <RuleTemplate>(); if (accessableIDs.Count < this.operationBatchSizeValue && this.operationBatchSizeValue < 2100) { ruleTemplateList = NHibernateSession.QueryOver <RuleTemplate>() .WhereRestrictionOn(x => x.ID) .IsIn(ruleTemplateIds) .List <RuleTemplate>(); } else { GTS.Clock.Model.Temp.Temp tempAlias = null; TempRepository tempRep = new TempRepository(false); string operationGUID = tempRep.InsertTempList(accessableIDs); ruleTemplateList = NHibernateSession.QueryOver <RuleTemplate>(() => ruleTemplateAlias) .JoinAlias(() => ruleTemplateAlias.TempList, () => tempAlias) .Where(() => tempAlias.OperationGUID == operationGUID) .List <RuleTemplate>(); tempRep.DeleteTempList(operationGUID); } return(ruleTemplateList); }
public RuleTemplateProxy(RuleTemplate ruleTemplate) { Id = ruleTemplate.ID; Script = ruleTemplate.Script; Name = ruleTemplate.Name; IdentifierCode = ruleTemplate.IdentifierCode; CustomCategoryCode = ruleTemplate.CustomCategoryCode; TypeId = ruleTemplate.TypeId; CSharpCode = ruleTemplate.CSharpCode; UserDefined = ruleTemplate.UserDefined; JsonObject = ruleTemplate.JsonObject; Order = ruleTemplate.Order; OperationalArea = ruleTemplate.OperationalArea; if (ruleTemplate.DesignedRule != null) { RuleStateObject = ruleTemplate.DesignedRule.RuleStateObject; RuleParametersObject = ruleTemplate.DesignedRule.ParameterObject; RuleVariablesObject = ruleTemplate.DesignedRule.VariablesObject; DesignedRuleID = ruleTemplate.DesignedRule.ID; } else { RuleStateObject = string.Empty; RuleParametersObject = string.Empty; RuleVariablesObject = string.Empty; } }
/// <summary> /// Формирование заявок пляшем от АИС 3 /// </summary> /// <param name="userRule">Спаршенные данные АИС 3</param> /// <returns></returns> public async Task <ModelPathReport> GenerateTemplateRule(UserRules userRule) { var report = new ModelPathReport(); try { return(await Task.Factory.StartNew(() => { var sql = new SelectSql(); var templateword = new TemplateUserRule(); var ruletemplate = new RuleTemplate() { SenderUsers = new SenderUsers() }; var modelselect = sql.SendersUsers(ref ruletemplate); sql.UserRuleModel(ref ruletemplate, userRule, modelselect); templateword.CreateDocum(_parametrService.ReportMassTemplate, ruletemplate, null); report.Note = "Заявки запущены и сохраняются в папку"; report.Url = _parametrService.ReportMassTemplate; return report; })); } catch (Exception e) { Loggers.Log4NetLogger.Error(e); report.Note = e.Message; return(report); } }
public void TestTemplateGetByName() { RuleTemplate foundTemplate = RuleTemplate.GetByName("bAsIc"); Rule rule = new Rule(foundTemplate); Assert.IsTrue(rule.RuleTypeNames.Contains("Basic")); }
/// <summary> /// Adds a rule to the current context /// </summary> /// <param name="conditionTemplateType"></param> /// <param name="conditionData"></param> /// <param name="consequenceTemplateType"></param> /// <param name="consequenceData"></param> /// <returns></returns> public async Task <Guid> AddRule( int conditionTemplateType, string conditionData, int consequenceTemplateType, string consequenceData) { var condition = _ruleTemplateFactory .CreateCondition(conditionTemplateType, conditionData); var consequence = _ruleTemplateFactory .CreateConsequence(consequenceTemplateType, consequenceData); var template = new RuleTemplate <TFact, TOutput>(condition, consequence); var ruleId = RuleExecuter.AddRule(template.Rule); var ruleData = new RuleData() { Id = ruleId, ContextId = ContextId, ConditionType = conditionTemplateType, ConditionData = conditionData, ConsequenceType = consequenceTemplateType, ConsequenceData = consequenceData }; await _ruleRepository.AddRule(ruleData); return(ruleId); }
public void DumpToDB() { Contract.Assert(RuleTemplateDB.RuleTemplateSet.Count == 0); foreach (var r in table) { RuleTemplate t = new RuleTemplate(r); RuleTemplateDB.record(t); } }
public RuleTemplateProxy(RuleTemplate ruleTemplate) { TemplateId = ruleTemplate.ID; Script = ruleTemplate.Script; Name = ruleTemplate.Name; IdentifierCode = ruleTemplate.IdentifierCode; CustomCategoryCode = ruleTemplate.CustomCategoryCode; TypeId = ruleTemplate.TypeId; CSharpCode = ruleTemplate.CSharpCode; UserDefined = ruleTemplate.UserDefined; JsonObject = ruleTemplate.JsonObject; }
public void CreateDocum(string path, RuleTemplate template, object obj) { foreach (var tempuotdel in template.Otdel) { Fullpathdocumentword = path + tempuotdel.Number + "_" + tempuotdel.NameOtdel + "_" + tempuotdel.Dates + Constant.WordConstant.Formatword; using (WordprocessingDocument package = WordprocessingDocument.Create(Fullpathdocumentword, WordprocessingDocumentType.Document)) { CreateWord(package, tempuotdel, template.SenderUsers, obj); package.MainDocumentPart.Document.Save(); package.Close(); } } }
public void RuleTemplate_ConstructorProvidesInstanceOfConditionAndConsequence() { //Setup Func <SampleFact, bool> cond = x => x.SampleInt == 0; Func <SampleFact, SampleOutput> cons = y => new SampleOutput(3); //Execution var ruleTemplate = new RuleTemplate <SampleFact, SampleOutput>( _moqCondition.Object, _moqConsequence.Object); //Setup Assert.Equal(_moqCondition.Object, ruleTemplate.RuleCondition); Assert.Equal(_moqConsequence.Object, ruleTemplate.RuleConsequence); }
public void TestMultipleValidation() { //Tests case insensitivity and duplicate template detection Rule multipleTemplateTest = new Rule( RuleTemplate.GetByName("TestTemplate"), RuleTemplate.GetByName("ApplicaTION"), RuleTemplate.GetByName("tESTteMPLATE")); multipleTemplateTest.Properties.Add("TestKey", 1); //The rule is not complete and should be invalid (!IsValid) Assert.IsFalse(multipleTemplateTest.IsValid); //After this change the rule should be valid multipleTemplateTest.Properties.Add("Application", "testApplication"); Assert.IsTrue(multipleTemplateTest.IsValid); }
public decimal [] GetRuleTemplatIds(decimal[] IdentifierCode) { try { decimal[] ruleTemplateIds = new decimal[] {}; RuleTemplate ruleTemplateAlias = null; IList <decimal> RuleTemplateIds = NHSession.QueryOver(() => ruleTemplateAlias) .Where(() => ruleTemplateAlias.IdentifierCode.IsIn(IdentifierCode.ToArray())) .Select(x => x.ID) .List <decimal>(); return(RuleTemplateIds.ToArray()); } catch (Exception ex) { LogException(ex, "BRuleCategory", "GetRuleTemplatIds"); throw ex; } }
public void RuleTemplate_TemplateShouldHaveCompiledRule() { //Setup Func <SampleFact, bool> cond = x => x.SampleInt == 0; Func <SampleFact, SampleOutput> cons = y => new SampleOutput(3); _moqCondition.Setup(x => x.GetCondition()).Returns(cond); _moqConsequence.Setup(x => x.GetConsequence()).Returns(cons); var rule = GetSampleRule(cond, cons); //Exection var ruleTemplate = new RuleTemplate <SampleFact, SampleOutput>( _moqCondition.Object, _moqConsequence.Object); //Assert Assert.Equal(rule.Condition, ruleTemplate.Rule.Condition); Assert.Equal(rule.Consequence, ruleTemplate.Rule.Consequence); }
public RuleInstance CreateRuleInstanceFromTemplate(RuleTemplate template) { var rule = new RuleInstance(); foreach (var i in template.RuleInterfaceTemplate) { var intInst = new RuleInterfaceInstance(); intInst.This2RuleInstanceNavigation = rule; intInst.This2RuleInterfaceTemplateNavigation = i; intInst.This2RuleInterfaceTemplate = i.ObjId; intInst.Value = i.DefaultValue; rule.RuleInterfaceInstance.Add(intInst); } rule.Name = template.Name; rule.This2RuleTemplate = template.ObjId; rule.This2RuleTemplateNavigation = template; return(rule); }
/// <summary> /// Запрос на лиц кто согласовывает надо добавлять в xml /// </summary> /// <param name="template">Шаблон возврата</param> public ModelSelect SendersUsers(ref RuleTemplate template) { try { ModelSelect model = new ModelSelect { LogicaSelect = SqlSelectModel(13) }; template.SenderUsers.Security = Inventory.Database.SqlQuery <Security>(model.LogicaSelect.SelectUser, new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[0], 3), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[1], "Отдел безопасности"), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[2], DBNull.Value)).FirstOrDefault(); template.SenderUsers.ItOtdel = Inventory.Database.SqlQuery <ItOtdel>(model.LogicaSelect.SelectUser, new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[0], 4), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[1], "Отдел информатизации"), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[2], DBNull.Value)).FirstOrDefault(); template.SenderUsers.SenderRukovodstvo = Inventory.Database.SqlQuery <SenderRukovodstvo>(model.LogicaSelect.SelectUser, new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[0], 5), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[1], "Руководство"), new SqlParameter(model.LogicaSelect.SelectedParametr.Split(',')[2], DBNull.Value)).FirstOrDefault(); return(model); } catch (Exception e) { Loggers.Log4NetLogger.Error(e); } return(null); }
public CreateTemplateCode CreateRuleTemplate(Guid ui, string name, string description, string key, string group, double height, double width) { var interfaceType = new RuleTemplate(); if (!_ruleTemplates.ContainsKey(ui)) { _ruleTemplates.Add(ui, interfaceType); } var retValue = CreateTemplateCode.Created; interfaceType.ObjId = ui; interfaceType.Name = name; interfaceType.Description = description; interfaceType.Key = key; interfaceType.Group = group; interfaceType.Height = (float)height; interfaceType.Width = (float)width; _ruleTemplates[ui] = interfaceType; return(retValue); }
/// <summary> /// Loads a context by a given identifier based on a passed in repository /// </summary> /// <param name="identifier">Identifier representing a context</param> /// <param name="ruleExecuter">Passed in empty rule executer</param> /// <param name="ruleRepository">Repository for saved rules</param> /// <param name="ruleTemplateFactory">Factory for service specific templates</param> /// <returns></returns> public static async Task <RuleContext <TFact, TOutput> > LoadContext( Guid identifier, IRuleExecuter <TFact, TOutput> ruleExecuter, IRuleRepository ruleRepository, IRuleTemplateFactory <TFact, TOutput> ruleTemplateFactory) { var rules = await ruleRepository.GetRulesByContext(identifier); var context = new RuleContext <TFact, TOutput>(ruleExecuter, ruleRepository, identifier, ruleTemplateFactory); foreach (var ruleData in rules) { var condition = ruleTemplateFactory .CreateCondition(ruleData.ConditionType, ruleData.ConditionData); var consequence = ruleTemplateFactory .CreateConsequence(ruleData.ConsequenceType, ruleData.ConsequenceData); var template = new RuleTemplate <TFact, TOutput>(condition, consequence); ruleExecuter.AddRule(ruleData.Id, template.Rule); } return(context); }
public void TestRuleTemplateStore() { string fileLoc = "Unittest.json"; string key = "password123"; if (File.Exists(fileLoc)) { File.Delete(fileLoc); } RuleStore newStore = RuleStore.Create(fileLoc, key); Rule rule = new Rule(RuleTemplate.GetByName("Basic"), RuleTemplate.GetByName("Application")); newStore.Rules.Add(rule); newStore.WriteToDisc(); var readStore = RuleStore.Open(fileLoc, key); Assert.IsTrue(readStore.Rules.First().Templates.Count() == 2); Assert.IsTrue(readStore.Rules.First().Templates.FirstOrDefault(rt => rt.Name == "Basic") != null); Assert.IsTrue(readStore.Rules.First().Templates.FirstOrDefault(rt => rt.Name == "Application") != null); File.Delete(fileLoc); }
private void AddRuleTemplate(RuleTemplate ruleTemplate) { _ruleTemplates.Add(ruleTemplate.ID, ruleTemplate); }
public string[] UpdateRule_RulesPage( string ID, string IdentifierCode, string Name, string CustomCategoryCode, string TypeId, string UserDefined, string Script, string CSharpCode, string JsonObject, string PageState) { this.InitializeCulture(); UIValidationExceptions uiValidationExceptions = new UIValidationExceptions(); string[] retMessage = new string[4]; decimal iID = 0; RuleTemplate RuleRecived = new RuleTemplate(); RuleRecived.ID = Convert.ToDecimal(StringBuilder.CreateString(ID)); PageState = StringBuilder.CreateString(PageState); if (PageState != "Delete") { RuleRecived.IdentifierCode = Convert.ToDecimal(StringBuilder.CreateString(IdentifierCode)); RuleRecived.Name = StringBuilder.CreateString(Name); RuleRecived.CustomCategoryCode = StringBuilder.CreateString(CustomCategoryCode); RuleRecived.TypeId = Convert.ToDecimal(StringBuilder.CreateString(TypeId)); RuleRecived.UserDefined = bool.Parse(StringBuilder.CreateString(UserDefined)); RuleRecived.Script = StringBuilder.CreateString(Script); RuleRecived.CSharpCode = StringBuilder.CreateString(CSharpCode); if (!string.IsNullOrEmpty(JsonObject)) { RuleRecived.JsonObject = JsonObject.Substring(1, JsonObject.Length - 2); } } #region Effect on DB try { #region Set UIActionType Enum UIActionType uiActionType = UIActionType.ADD; switch (PageState.ToUpper()) { #region Add case "ADD": uiActionType = UIActionType.ADD; iID = RuleBusiness.InsertRule(RuleRecived); break; #endregion #region Edit case "EDIT": uiActionType = UIActionType.EDIT; if (RuleRecived.ID == 0) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, new Exception(GetLocalResourceObject("NoRuleSelectedforEdit").ToString()), retMessage); return(retMessage); } var concept = RuleBusiness.GetByID(RuleRecived.ID); RuleBusiness.Copy(RuleRecived, ref concept); iID = RuleBusiness.UpdateRule(concept); break; #endregion #region Delete case "DELETE": uiActionType = UIActionType.DELETE; if (RuleRecived.ID == 0) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, new Exception(GetLocalResourceObject("NoRuleSelectedforDelete").ToString()), retMessage); return(retMessage); } iID = RuleBusiness.DeleteRule(RuleRecived); break; #endregion default: break; } #endregion retMessage[0] = GetLocalResourceObject("RetSuccessType").ToString(); string SuccessMessageBody = string.Empty; switch (uiActionType) { case UIActionType.ADD: SuccessMessageBody = GetLocalResourceObject("AddComplete").ToString(); break; case UIActionType.EDIT: SuccessMessageBody = GetLocalResourceObject("EditComplete").ToString(); break; case UIActionType.DELETE: SuccessMessageBody = GetLocalResourceObject("DeleteComplete").ToString(); break; default: break; } retMessage[1] = SuccessMessageBody; retMessage[2] = "success"; retMessage[3] = iID.ToString(); return(retMessage); } catch (UIValidationExceptions ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.UIValidationExceptions, ex, retMessage); return(retMessage); } catch (UIBaseException ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.UIBaseException, ex, retMessage); return(retMessage); } catch (Exception ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, ex, retMessage); return(retMessage); } #endregion }
protected void CallBackSaveRules_Rules_OnCallBack(object sender, CallBackEventArgs e) { //UpdateRule_RulesPage( // e.Parameters[0], // e.Parameters[1], // e.Parameters[2], // e.Parameters[3], // e.Parameters[4], // e.Parameters[5], // e.Parameters[6], // e.Parameters[7], // e.Parameters[8], // e.Parameters[9] // ); string ID = e.Parameters[0]; string IdentifierCode = e.Parameters[1]; string Name = e.Parameters[2]; string CustomCategoryCode = e.Parameters[3]; string TypeId = e.Parameters[4]; string UserDefined = e.Parameters[5]; string Script = e.Parameters[6]; string CSharpCode = e.Parameters[7]; string JsonObject = e.Parameters[8]; string PageState = e.Parameters[9]; this.InitializeCulture(); UIValidationExceptions uiValidationExceptions = new UIValidationExceptions(); string[] retMessage = new string[4]; decimal iID = 0; RuleTemplate RuleRecived = new RuleTemplate(); RuleRecived.ID = Convert.ToDecimal(StringBuilder.CreateString(ID)); PageState = StringBuilder.CreateString(PageState); if (PageState != "Delete") { RuleRecived.IdentifierCode = Convert.ToDecimal(StringBuilder.CreateString(IdentifierCode)); RuleRecived.Name = StringBuilder.CreateString(Name); RuleRecived.CustomCategoryCode = StringBuilder.CreateString(CustomCategoryCode); RuleRecived.TypeId = Convert.ToDecimal(StringBuilder.CreateString(TypeId)); RuleRecived.UserDefined = bool.Parse(StringBuilder.CreateString(UserDefined)); RuleRecived.Script = StringBuilder.CreateString(Script); RuleRecived.CSharpCode = StringBuilder.CreateString(CSharpCode); RuleRecived.JsonObject = JsonObject; } #region Effect on DB try { #region Set UIActionType Enum UIActionType uiActionType = UIActionType.ADD; switch (PageState.ToUpper()) { #region Add case "ADD": uiActionType = UIActionType.ADD; iID = RuleBusiness.InsertRule(RuleRecived); break; #endregion #region Edit case "EDIT": uiActionType = UIActionType.EDIT; if (RuleRecived.ID == 0) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, new Exception(GetLocalResourceObject("NoRuleSelectedforEdit").ToString()), retMessage); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } var concept = RuleBusiness.GetByID(RuleRecived.ID); RuleBusiness.Copy(RuleRecived, ref concept); iID = RuleBusiness.UpdateRule(concept); break; #endregion #region Delete case "DELETE": uiActionType = UIActionType.DELETE; if (RuleRecived.ID == 0) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, new Exception(GetLocalResourceObject("NoRuleSelectedforDelete").ToString()), retMessage); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } iID = RuleBusiness.DeleteRule(RuleRecived); break; #endregion default: break; } #endregion retMessage[0] = GetLocalResourceObject("RetSuccessType").ToString(); string SuccessMessageBody = string.Empty; switch (uiActionType) { case UIActionType.ADD: SuccessMessageBody = GetLocalResourceObject("AddComplete").ToString(); break; case UIActionType.EDIT: SuccessMessageBody = GetLocalResourceObject("EditComplete").ToString(); break; case UIActionType.DELETE: SuccessMessageBody = GetLocalResourceObject("DeleteComplete").ToString(); break; default: break; } retMessage[1] = SuccessMessageBody; retMessage[2] = "success"; retMessage[3] = iID.ToString(CultureInfo.InvariantCulture); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } catch (UIValidationExceptions ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.UIValidationExceptions, ex, retMessage); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } catch (UIBaseException ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.UIBaseException, ex, retMessage); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } catch (Exception ex) { retMessage = this.ExceptionHandler.HandleException(this.Page, ExceptionTypes.Exception, ex, retMessage); hfCallBackDataSaveRules_Rules.Value = Newtonsoft.Json.JsonConvert.SerializeObject(retMessage); this.hfCallBackDataSaveRules_Rules.RenderControl(e.Output); } #endregion }
public string GenerateAndCompile() { #region Source Main Text string sourceTextMain = @" using System; using System.Collections.Generic; using System.Linq; using GTS.Clock.ModelEngine; using GTS.Clock.ModelEngine.ELE; using GTS.Clock.ModelEngine.Concepts; using GTS.Clock.ModelEngine.Concepts.Operations; using GTS.Clock.Infrastructure.Utility; namespace GTS.Clock.Business.DesignedCalculator { public static class DesignedRuleCalculator { //#region Rules ###RULES### //#endregion } public static class DesignedConceptCalculator { #region Concepts ###CONCEPTS### #endregion } }"; #endregion #region CONCEPTS string sourceTextConcepts = @" /// <summary> /// ###SUMMARY### /// </summary> /// <param name=""MyRule""></param> public static void ###IDENTIFIER###(this GTS.Clock.Business.Calculator.ConceptCalculator calculator, BaseScndCnpValue Result, SecondaryConcept MyConcept) { ###CSHARPSOURCE### } "; var Conceptsource = new EntityRepository <SecondaryConcept>().GetAll().Where(x => x.UserDefined) .Select(cnp => new RuleConceptCompileProxy() { Identifier = cnp.IdentifierCode.ToString(CultureInfo.InvariantCulture), CSharpCode = cnp.CSharpCode, Summery = cnp.FnName, }) .ToList(); string strConcepts = string.Empty; foreach (var ruleConceptCompileProxy in Conceptsource) { var tt = sourceTextConcepts.Replace("###SUMMARY###", " C" + ruleConceptCompileProxy.Summery + "Summary"); tt = tt.Replace("###IDENTIFIER###", "C" + ruleConceptCompileProxy.Identifier); tt = tt.Replace("###CSHARPSOURCE###", ruleConceptCompileProxy.CSharpCode); strConcepts += tt; } sourceTextMain = sourceTextMain.Replace("###CONCEPTS###", strConcepts); #endregion #region RULES string sourceTextMethods = @" /// <summary> /// ##SUMMARY### /// </summary> /// <param name=""MyRule""></param> public static void ###IDENTIFIER###(this GTS.Clock.Business.Calculator.RuleCalculator calculator, AssignedRule MyRule) { ###CSHARPSOURCE### } "; //var Rulesource = new EntityRepository<DesignedRule>() // //var Rulesource = new EntityRepository<RuleTemplate>() // //.GetAll().Where(x => x.UserDefined) // .GetAll().Select(cnp => new RuleConceptCompileProxy() // { // //Identifier = cnp.RuleTemplateID.IdentifierCode.ToString(CultureInfo.InvariantCulture), // //CSharpCode = cnp.CSharpCode, // //Summery = cnp.RuleTemplateID.Name // Identifier = cnp.RuleTemplate.IdentifierCode.ToString(CultureInfo.InvariantCulture), // CSharpCode = cnp.CSharpCode, // Summery = cnp.RuleTemplate.Name // }) // .ToList(); IList <RuleConceptCompileProxy> Rulesource = new List <RuleConceptCompileProxy>(); DesignedRule designedRuleAlias = null; RuleTemplate RuleTemplateAlias = null; IList <DesignedRule> designedRuleList = this.NHSession.QueryOver <DesignedRule>(() => designedRuleAlias) .JoinAlias(() => designedRuleAlias.RuleTemplate, () => RuleTemplateAlias) .List <DesignedRule>(); if (designedRuleList != null && designedRuleList.Count > 0) { designedRuleList.ToList <DesignedRule>().ForEach(x => { Rulesource.Add(new RuleConceptCompileProxy() { Identifier = x.RuleTemplate.IdentifierCode.ToString(CultureInfo.InvariantCulture), CSharpCode = x.CSharpCode, Summery = x.RuleTemplate.Name }); }); } string strMethods = string.Empty; foreach (var ruleConceptCompileProxy in Rulesource) { var tt = sourceTextMethods.Replace("###SUMMARY###", "R" + ruleConceptCompileProxy.Summery + "Summary"); tt = tt.Replace("###IDENTIFIER###", "R" + ruleConceptCompileProxy.Identifier); tt = tt.Replace("###CSHARPSOURCE###", ruleConceptCompileProxy.CSharpCode); strMethods += tt; } sourceTextMain = sourceTextMain.Replace("###RULES###", strMethods); #endregion var providerOptions = new Dictionary <string, string> { { "CompilerVersion", "v4.0" } }; CSharpCodeProvider provider = new CSharpCodeProvider(providerOptions); CompilerParameters compilerParams = new CompilerParameters { OutputAssembly = OutputDLLFullPath, GenerateInMemory = false, GenerateExecutable = false }; #region ReferencedAssemblies compilerParams.ReferencedAssemblies.Add("mscorlib.dll"); compilerParams.ReferencedAssemblies.Add("System.dll"); compilerParams.ReferencedAssemblies.Add("System.Core.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.dll"); compilerParams.ReferencedAssemblies.Add("System.Data.DataSetExtensions.dll"); compilerParams.ReferencedAssemblies.Add("System.Xml.dll"); compilerParams.ReferencedAssemblies.Add("System.Xml.Linq.dll"); var refDlls = new List <string>() { "GTS.Clock.Business.dll", "GTS.Clock.Infrastructure.dll", "GTS.Clock.Infrastructure.RepositoryEngine.dll", "GTS.Clock.ModelEngine.dll", "log4net.dll", "GTS.Clock.Business.Calculator.dll", "GTS.Clock.Business.GeneralCalculator.dll" }; foreach (var refDll in refDlls) { var dllPath = string.Format("{0}\\{1}", AppDomain.CurrentDomain.BaseDirectory + "RuleGenerator\\bin", refDll); if (System.IO.File.Exists(dllPath)) { compilerParams.ReferencedAssemblies.Add(dllPath); } } #endregion CompilerResults results = provider.CompileAssemblyFromSource(compilerParams, sourceTextMain); var message = string.Empty; if (results.Errors.Count == 0) { using (StreamWriter streamWriter = new StreamWriter(OutputCSharpCodeFullPath)) { streamWriter.Write(sourceTextMain); } } else { using (StreamWriter streamWriter = new StreamWriter(OutputCSharpCodeFullPath + ".LOG")) { for (int index = 0; index < results.Errors.Count; index++) { CompilerError err = results.Errors[index]; streamWriter.Write(err.ErrorText); message += "\r\n" + err.ErrorText; } } } return(message); }
public void AddRuleTemplate(RuleTemplate ruleTemplate) { _ruleTemplates.Add(ruleTemplate.ID, ruleTemplate); }
public RuleAsString(RuleTemplate t) { preSet.UnionWith(t.preSetStr); postSet.UnionWith(t.postSetStr); }
/// <summary> /// Вытягивание данных на отдел и пользователей /// </summary> /// <param name="template">Шаблон раскладки</param> /// <param name="userRule">Данные ролей из АИС 3</param> /// <param name="sqlSelect">Запрос к БД для выборки данных</param> public void UserRuleModel(ref RuleTemplate template, UserRules userRule, ModelSelect sqlSelect) { var groupElement = userRule.User.Where(x => x.Number != "Скрипт").Select(x => new { x.Dates, x.Number, Otdel = x.Otdel.Replace("№ ", "№") }).GroupBy(x => new { x.Dates, x.Number, x.Otdel }).Select(x => new { x.Key.Number, x.Key.Dates, x.Key.Otdel }).ToList(); int i = 0; foreach (var gr in groupElement) { if (template.Otdel == null) { template.Otdel = new Otdel[groupElement.Count]; } template.Otdel[i] = Inventory.Database.SqlQuery <Otdel>( sqlSelect.LogicaSelect.SelectUser, new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[0], 1), new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[1], gr.Otdel.Replace("№ ", "№")), new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[2], gr.Number)).FirstOrDefault() ?? new Otdel() { Number = gr.Number, NameOtdel = "Ошибка в наименование отдела Кадры,AD,АИС3", RnameOtdel = "Ошибка в наименование отдела Кадры,AD,АИС3", SmallName = "Отсутствует", NamePosition = "Отсутствует" }; template.Otdel[i].Dates = gr.Dates; var user = userRule.User.Where(userRole => (userRole.Dates == gr.Dates) && (userRole.Number == gr.Number) && (userRole.Otdel.Replace("№ ", "№") == gr.Otdel)).Select(u => new { u.Dates, u.Fio, u.SysName, u.Dolj, Otdel = u.Otdel.Replace("№ ", "№"), u.Number }).Distinct().ToList(); int j = 0; foreach (var userRole in user) { var roleAll = userRule.User.Where(u => u.Dates == userRole.Dates && u.Dolj == userRole.Dolj && u.Otdel.Replace("№ ", "№") == userRole.Otdel && u.Fio == userRole.Fio && u.SysName == userRole.SysName && u.Number == userRole.Number). Select(x => x.Rule).Aggregate((element, next) => element.Concat(next).ToArray()); if (template.Otdel[i].Users == null) { template.Otdel[i].Users = new LibaryXMLAutoModelXmlAuto.OtdelRuleUsers.Users[user.Count]; } template.Otdel[i].Users[j] = Inventory.Database.SqlQuery <LibaryXMLAutoModelXmlAuto.OtdelRuleUsers.Users>(sqlSelect.LogicaSelect.SelectUser, new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[0], 2), new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[1], userRole.SysName.Split('@')[0]), new SqlParameter(sqlSelect.LogicaSelect.SelectedParametr.Split(',')[2], DBNull.Value)).FirstOrDefault() ?? new LibaryXMLAutoModelXmlAuto.OtdelRuleUsers.Users() { Name = userRole.Fio, NamePosition = userRole.Dolj, IpAdress = null, Tabel = $"regions\\{userRole.SysName.Split('@')[0]}", NumberKabinet = null, RuleTemplate = null }; template.Otdel[i].Users[j].RuleTemplate = roleAll.Select(elem => $"{elem.Types}: {elem.Name}").Aggregate( (element, next) => element + (string.IsNullOrWhiteSpace(element) ? string.Empty : ", ") + next); template.Otdel[i].Users[j].Pushed = roleAll[0].Pushed; j++; } i++; } }
public RuleInstance CreateRuleInstance(RuleTemplate template) { return(RuleInstance.CreateFromTemplate(template)); }