/// <summary> /// Разбор вызова. Разбор конкретного вызова приложения из файла конфигурации. /// Выполнено с учетом нескольких команд в файла конфигурации. /// </summary> /// <returns>Результат разбора. Хотя бы один алгоритм нормально отработал.</returns> public static bool ParseAllProp(string[] args) //, out ICommandLineRun result) { bool rc = false; List <string> Parameters; // Список параметров подкомманды (например режимы работы класса). //Разбор конкретного вызова приложения из файла конфигурации. if (ParseConfig()) // { rc = true; } //Разбор конкретного вызова приложения из командной строки. if (ParseCommandLine(args, out Parameters))// { rc = true; } // продолжаем разбор в команде(CommandLineSample). // Создаем исполняющий класс. // Присваиваем свойствам значения. foreach (KeyValuePair <string, Dictionary <string, string> > propSubCom in subComs) { string subCom = propSubCom.Key; CommandLineSample cmdSample = CommandLineService.GetOrAddCommand(subCom, false); if (cmdSample == null) // Нет обработки { continue; } Dictionary <string, string> properties = propSubCom.Value; rc = cmdSample.ParseCommandLine(properties, Parameters); //Создали исполняющий класс } return(rc); }
/// <summary> /// Дать экземпляр CommandLineSample по имени подкоманды /// или создать подкоманду если f_add = true /// </summary> /// <param name="realName"> имя подкоманды</param> /// <param name="f_add"> добавлять подкоманду в случае отсутствия.</param> /// <returns></returns> public static CommandLineSample GetOrAddCommand(string realName, bool f_add = true) { CommandLineSample cmdln = cmdlines.FirstOrDefault( cmd => cmd.CommandName == realName); if (cmdln == null && f_add) // нет такой + нужно создавать { // создаем команду cmdln = new CommandLineSample(realName); cmdlines.Add(cmdln); } return(cmdln); }
/// <summary> /// выполнить /// </summary> public override void Run() { CommandLineSample cmdln = CommandLineService.GetOrAddCommand(this.CommandName, false); if (cmdln != null) { // совпала cmdln.Help(); } else // неправильная команда help { Console.WriteLine("Error calling program {0}. command {1} does not exist ", AppName, this.CommandNameHelp); RulesOfchallenge(); } }
/// <summary> /// Разбор конкретного вызова приложения из файла конфигурации. /// Выполнено с учетом нескольких подкоманд в файле конфигурации. /// </summary> /// <returns>Результат разбора</returns> public static bool ParseConfig() //, out ICommandLineRun result) { bool rc = false; CommandLineSample cmdSample; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Обработка секции CmdRunConfs Type t4 = typeof(CommandLineRunSection); CommandLineRunSection AddConfSections = config.GetSection("CmdRunConfs") as CommandLineRunSection; if (AddConfSections != null) // получили секцию CmdRunConfs из конфигурации { for (int ii = 0; ii < AddConfSections.CmdRunConfs.Count; ii++) { string subCom = AddConfSections.CmdRunConfs[ii].Subcommand; if (string.IsNullOrEmpty(subCom)) // сбой значения { continue; } cmdSample = CommandLineService.GetOrAddCommand(subCom, true); if (cmdSample == null) // Нет обработки { continue; } cmdSample.NumberExecution = AddConfSections.CmdRunConfs[ii].NumberExecution; cmdSample.AssemblyNameWithPath = AddConfSections.CmdRunConfs[ii].AssemblyNameWithPath; } } // Обработка секции CMDProperties Type tPr = typeof(CMDPropertySection); CMDPropertySection cmdProperties = config.GetSection("CMDProperties") as CMDPropertySection; if (cmdProperties != null) // получили секцию CMDProperties из конфигурации { for (int ii = 0; ii < cmdProperties.CMDProperties.Count; ii++) { string subCom = cmdProperties.CMDProperties[ii].Subcommand; if (string.IsNullOrEmpty(subCom)) // сбой значения { continue; } else { cmdSample = CommandLineService.GetOrAddCommand(subCom, true); if (cmdSample == null) // Нет обработки { continue; } Dictionary <string, string> properties; if (!subComs.TryGetValue(subCom, out properties)) // нет в справочнике { // создаем properties = new Dictionary <string, string>(); subComs.Add(subCom, properties); } string val = cmdProperties.CMDProperties[ii].Value; string key = cmdProperties.CMDProperties[ii].NameProperty; if (string.IsNullOrEmpty(key)) // сбой значения { continue; } else { properties.Add(key, val); //Console.WriteLine($"Add: {key} - {val}."); rc = true; } } } } // Обработка секции CmdRunSpecifications Type tPS = typeof(CMDPropertySection); CMDRunSpecificationSection cmdSpecifications = config.GetSection("CmdRunSpecifications") as CMDRunSpecificationSection; if (cmdSpecifications != null) // получили секцию CmdRunSpecifications из конфигурации { for (int ii = 0; ii < cmdSpecifications.CMDRunSpecifications.Count; ii++) { string subComLeft = cmdSpecifications.CMDRunSpecifications[ii].SubcommandLeft; if (string.IsNullOrEmpty(subComLeft)) // сбой значения { continue; } string subComRight = cmdSpecifications.CMDRunSpecifications[ii].SubcommandRight; if (string.IsNullOrEmpty(subComRight)) // сбой значения { continue; } string specification = cmdSpecifications.CMDRunSpecifications[ii].Specification; if (string.IsNullOrEmpty(specification)) // сбой значения { continue; } else { specification = specification.ToUpper(); CommandLineSample cmdSampleL = CommandLineService.GetOrAddCommand(subComLeft, false); if (cmdSampleL == null) // Нет обработки { continue; } CommandLineSample cmdSampleR = CommandLineService.GetOrAddCommand(subComRight, false); if (cmdSampleR == null) // Нет обработки { continue; } else { switch (specification) { case "XOR": cmdSampleL = cmdSampleL ^ cmdSampleR; break; case "OR": cmdSampleL = cmdSampleL | cmdSampleR; break; case "AND": cmdSampleL = cmdSampleL & cmdSampleR; break; default: continue; } } } } } return(rc); }
/// <summary> /// Создание подкоманды вызова приложения из командной строки /// </summary> /// <param name="name">'/' + имя_подкоманды.</param> /// <returns></returns> public static CommandLineSample CmdRunCommand(string name) { CommandLineSample cmdS = GetOrAddCommand(name.Substring(1).Trim()); return(cmdS); }
/// <summary> /// Разбор вызова. Разбор конкретного вызова приложения из командной строки. /// Выполнено с учетом нескольких подкоманд в командной строке. /// </summary> /// <param name="args">подкоманды в командной строке.</param> /// <param name="Parameters"> Список параметров подкомманды</param> /// <returns>Результат разбора</returns> public static bool ParseCommandLine(string[] args, out List <string> Parameters) //, out ICommandLineRun result) { bool rc = false; Parameters = new List <string>(); Dictionary <string, string> properties; for (int ind = 0; ind < args.Length; ind++)// разбор всех аргументов { if (args[ind].StartsWith(slesh2)) { // подкоманда string subCom = args[ind].Substring(1).Trim(); // имя команды CommandLineSample cmdSample = CommandLineService.GetOrAddCommand(subCom, true); if (cmdSample == null) // Нет обработки { continue; } if (!subComs.TryGetValue(subCom, out properties)) //нет в справочнике. Новая подкоманда { // создаем properties = new Dictionary <string, string>(); subComs.Add(subCom, properties); } ind++; // след. аргумент в ком. строке while (ind < args.Length) // разбор опций и параметров для команды { // if (args[ind].StartsWith(const_PREF)) // префикс '-' { // опция string KeyOpt = args[ind].Substring(1); //без разделителя if (KeyOpt.StartsWith(const_PREF)) // префикс ='--' { KeyOpt = KeyOpt.Substring(1); //без префикса '--' } string[] nameValue = KeyOpt.Split(const_SPLIT); // разделитель значение параметра командной строки if (nameValue.Length == 0) { // неправильный вызов break; //??? return rc; } string ValueOpt; switch (nameValue.Length) { case 1: // возможно неправильный вызов ValueOpt = null; break; case 2: // сейчас правильный вызов ValueOpt = nameValue[1]; break; default: // сейчас неправильный вызов. но берем только 2 ValueOpt = nameValue[1]; break; } if (!properties.TryGetValue(nameValue[0], out string ss)) { // Нет такого свойства в справочнике. properties.Add(nameValue[0], ValueOpt); } else { // Значение было в файле конфигурации. Обновим значение. properties[nameValue[0]] = ValueOpt; } } else if (args[ind].StartsWith(slesh2)) { // Еще команда. ind--; break; // прервем. Обработаем в цикле for } else { // параметрический вызов. Вообще Позиционный вызов. В тесте только для Help if (Parameters.Find((pp => pp == args[ind])) != null) { Parameters.Add(args[ind]); } } ind++; // след. аргумент } // TODO проверим на совместимость } } return(rc); }
static bool ParseConfigurationCommandLineRun(out Dictionary <string, Dictionary <string, string> > subComs) { subComs = null; bool rc = false; // Get the current configuration file. System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); ConfigurationSection appS = config.GetSection("appSettings"); Type t0 = typeof(ConfigurationSection); AppSettingsSection appSettings = config.AppSettings; if (appSettings != null) // { //string ss = appSettings?.Settings?.AllKeys[0]; //string ss1 = appSettings?.Settings?.AllKeys[1]; //string ss2 = appSettings?.Settings.GetEnumerator. } //UserServices.ConfigurationCMDRun. Type t2 = typeof(ValidatedCMRunSection); ValidatedCMRunSection CMRunSection = config.GetSection("cmdrun") as ValidatedCMRunSection; if (CMRunSection != null) // { Console.WriteLine("CMRunSection not null."); } // var AddConfSections1 = (CommandLineRunSection)config.GetSection("CmdRunConfs"); Type t4 = typeof(CommandLineRunSection); CommandLineRunSection AddConfSections = config.GetSection("CmdRunConfs") as CommandLineRunSection; if (AddConfSections != null) // получили секцию AddConfSections из конфигурации { if (subComs == null) // { subComs = new Dictionary <string, Dictionary <string, string> >(); } for (int ii = 0; ii < AddConfSections.CmdRunConfs.Count; ii++) { string subCom = AddConfSections.CmdRunConfs[ii].Subcommand; if (string.IsNullOrEmpty(subCom)) // сбой значения { continue; } else { CommandLineSample cmdSample = CommandLineService.GetOrAddCommand(subCom, false); if (cmdSample == null) // Нет обработки { continue; } string assemblyNameWithPath = AddConfSections.CmdRunConfs[ii].AssemblyNameWithPath; // создаем имя cmdSample.AssemblyNameWithPath = assemblyNameWithPath; int num = AddConfSections.CmdRunConfs[ii].NumberExecution; Console.WriteLine($"Add: {subCom} - {assemblyNameWithPath}."); } } } Type tPr = typeof(CMDPropertySection); CMDPropertySection cmdProperties = config.GetSection("CMDProperties") as CMDPropertySection; if (cmdProperties != null) // получили секцию AddConfSections из конфигурации { if (subComs == null) // { subComs = new Dictionary <string, Dictionary <string, string> >(); } for (int ii = 0; ii < cmdProperties.CMDProperties.Count; ii++) { string subCom = cmdProperties.CMDProperties[ii].Subcommand; if (string.IsNullOrEmpty(subCom)) // сбой значения { continue; } else { Dictionary <string, string> properties; string val = cmdProperties.CMDProperties[ii].Value; string key = cmdProperties.CMDProperties[ii].NameProperty; if (!subComs.TryGetValue(subCom, out properties)) // нет в справочнике { // создаем properties = new Dictionary <string, string>(); subComs.Add(subCom, properties); } if (string.IsNullOrEmpty(key)) // сбой значения { continue; } else { properties.Add(key, val); Console.WriteLine($"Add: {key} - {val}."); rc = true; } } } } // Обработка секции CmdRunSpecifications Type tPS = typeof(CMDPropertySection); CMDRunSpecificationSection cmdSpecifications = config.GetSection("CMDRunSpecifications") as CMDRunSpecificationSection; if (cmdSpecifications != null) // получили секцию CmdRunSpecifications из конфигурации { if (subComs == null) // ??? нужно ли выполнять { subComs = new Dictionary <string, Dictionary <string, string> >(); } for (int ii = 0; ii < cmdSpecifications.CMDRunSpecifications.Count; ii++) { string subComLeft = cmdSpecifications.CMDRunSpecifications[ii].SubcommandLeft; if (string.IsNullOrEmpty(subComLeft)) // сбой значения { continue; } string subComRight = cmdSpecifications.CMDRunSpecifications[ii].SubcommandRight; if (string.IsNullOrEmpty(subComRight)) // сбой значения { continue; } string specification = cmdSpecifications.CMDRunSpecifications[ii].Specification; if (string.IsNullOrEmpty(specification)) // сбой значения { continue; } else { specification = specification.ToUpper(); CommandLineSample cmdSampleL = CommandLineService.GetOrAddCommand(subComLeft, false); if (cmdSampleL == null) // Нет обработки { continue; } CommandLineSample cmdSampleR = CommandLineService.GetOrAddCommand(subComRight, false); if (cmdSampleR == null) // Нет обработки { continue; } else { switch (specification) { case "XOR": cmdSampleL = cmdSampleL ^ cmdSampleR; break; case "OR": cmdSampleL = cmdSampleL | cmdSampleR; break; case "AND": cmdSampleL = cmdSampleL & cmdSampleR; break; default: continue; } } } } } Console.WriteLine("Expect Enter."); Console.ReadKey(); return(rc); }