/// <summary> /// Получает значение параметра из ini-файла. /// Если такого параметра нет, то он создается с переданным /// значением по умолчанию /// </summary> private object GetAdditionalParamFromINI(iniFile iniSettings, string section, string key, Type typeOfValue, string defVal) { try { return(IniReadValue(iniSettings, section, key, typeOfValue, true)); } catch { iniSettings.IniWriteValue(section, key, defVal); return(IniReadValue(iniSettings, section, key, typeOfValue)); } }
/// <summary> /// Получает настройку из ini файла, преобразуя значение к заданному типу /// <PARAM name="iniSettings">Файл ini</PARAM> /// <PARAM name="section">Секция</PARAM> /// <PARAM name="key">Ключ</PARAM> /// <PARAM name="typeOfValue">Тип значения</PARAM> /// <PARAM name="exceptIfEmpty">Вызывать исключение, если получено пустое значение параметра</PARAM> /// </summary> private object IniReadValue(iniFile iniSettings, string section, string key, Type typeOfValue, bool exceptIfEmpty = false) { string iniValue = iniSettings.IniReadValue(section, key); if (exceptIfEmpty && String.IsNullOrEmpty(iniValue)) { throw new Exception("Не удалось прочитать значения параметра \"" + section + ":" + key + "\""); } if (typeOfValue == typeof(int)) { if (String.IsNullOrEmpty(iniValue)) { iniValue = "0"; } } else if (typeOfValue == typeof(bool)) { if (iniValue == "0") { iniValue = "false"; } else if (iniValue == "1") { iniValue = "true"; } } try { return(Convert.ChangeType(iniValue, typeOfValue)); } catch { throw new Exception("Не удалось прочитать значения параметра \"" + section + ":" + key + "\""); } }
/// <summary> /// Проверяет существование скриптов /// <PARAM name="runPath">Путь исполняемого файла</PARAM> /// </summary> private bool CheckScriptsSettings(string runPath) { bool scrOK = true; string fileExtention = ""; string dirBaseName = runPath + "scripts\\"; if (Directory.Exists(dirBaseName)) { string[] cmdFiles = Directory.GetFiles(dirBaseName, "*.os*"); string iniFileName = dirBaseName + "scripts.ini"; iniFile iniSettings = new iniFile(iniFileName); string wl_users = (string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), ""); foreach (string cmdFile in cmdFiles) { string commandName = Path.GetFileNameWithoutExtension(cmdFile); commandName = commandName.Replace(" ", ""); try { StreamReader reader = File.OpenText(cmdFile); string commandDescr = reader.ReadLine(); commandDescr.Trim(); if (commandDescr.StartsWith(@"//")) { commandDescr = commandDescr.Substring(3); } if (commandDescr != null) { string commandCode = reader.ReadToEnd(); reader.Close(); if (!String.IsNullOrEmpty(commandCode)) { Command scriptCmd = new Command(); commandName = "/" + commandName; scriptCmd.Type = commandTypes.commandOScript; scriptCmd.ID = commandName; scriptCmd.Description = commandDescr; scriptCmd.Code = commandCode; scriptCmd.ConnectionString = cmdFile; scriptCmd.AllowUsers = GetWhiteListOfUsers(wl_users); fileExtention = Path.GetExtension(cmdFile); if (fileExtention.ToLower() == ".os_b") { scriptCmd.KeyboardCommand = true; } else { scriptCmd.KeyboardCommand = false; } if (scriptCmd.KeyboardCommand) { commandName += "_keyb"; } this.commands.Add(commandName.ToLower(), scriptCmd); } else { Logger.Write(cmdFile + ": файл не содержит кода команды", true); } } else { Logger.Write(cmdFile + ": файл не содержит записей", true); } } catch { Logger.Write(cmdFile + ": не удалось прочитать файл", true); } } } else { try { Directory.CreateDirectory(dirBaseName); Logger.Write("Создан каталог \"scripts\""); } catch { Logger.Write("Не удалось создать каталог \"scripts\""); scrOK = false; } } return(scrOK); }
/// <summary> /// Загружает настройки для каждой базы данных из каталога databases /// <PARAM name="databases">Массив с именами каталогов</PARAM> /// </summary> private bool GetDbSettings(string[] databases) { this.bases = new List <DBStruct>(); foreach (string dir in databases) { string dbName = new DirectoryInfo(dir).Name; dbName = dbName.Replace(" ", ""); dbName = dbName.Replace("_", ""); string dirName = Service.CheckPath(dir); string fileName = dirName + "database.ini"; if (File.Exists(fileName)) { iniFile iniSettings = new iniFile(fileName); bool baseOK = true; string conString = ""; string wl_users = ""; int dbVersion = 0; try { conString = (string)IniReadValue(iniSettings, "Base", "ConnectionString", typeof(string)); dbVersion = (int)IniReadValue(iniSettings, "Base", "Version", typeof(int)); wl_users = (string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), ""); } catch (Exception e) { Logger.Write(fileName + ": " + e.Message, true); baseOK = false; } if (baseOK) { if (String.IsNullOrEmpty(conString)) { Logger.Write(fileName + ": не указана строка соединения с базой данных", true); baseOK = false; } if (dbVersion == 0) { Logger.Write(fileName + ": не указана версия 1С для базы данных", true); baseOK = false; } else if (!(82 <= dbVersion && dbVersion <= 83)) { Logger.Write(fileName + ": указана неизвестная версия 1С", true); baseOK = false; } if (baseOK) { List <DBCommand> baseCommands = GetDbCommands(dirName); if (baseCommands.Count > 0) { DBStruct newBase = new DBStruct(); newBase.Name = dbName; newBase.ConnectionString = conString; newBase.Version = dbVersion; newBase.Commands = baseCommands; newBase.AllowUsers = GetWhiteListOfUsers(wl_users); this.bases.Add(newBase); foreach (DBCommand cmd in baseCommands) { string commandID = "/" + dbName + "_" + cmd.Name; Command baseCmd = new Command(); baseCmd.Type = commandTypes.command1C; baseCmd.ID = commandID; baseCmd.Description = cmd.Description; baseCmd.Code = cmd.Code; baseCmd.Version = newBase.Version; baseCmd.ConnectionString = newBase.ConnectionString; baseCmd.KeyboardCommand = cmd.KeyboardCommand; baseCmd.AllowUsers = newBase.AllowUsers; if (cmd.KeyboardCommand) { commandID += "_keyb"; } this.commands.Add(commandID.ToLower(), baseCmd); } } else { Logger.Write(dirName + ": нет ни одной команды для выполнения", true); } } } } else { Logger.Write(dirName + ": не найден файл \"database.ini\"", true); } } return(bases.Count > 0); }
/// <summary> /// Проверяет существование файла ini с настройками. /// При необходимости создает его. /// <PARAM name="runPath">Путь исполняемого файла</PARAM> /// </summary> private bool CheckMainINI(string runPath) { bool iniOK = false; string fileName = runPath + "settings.ini"; iniFile iniSettings = new iniFile(fileName); if (File.Exists(fileName)) { try { this.botToken = (string)IniReadValue(iniSettings, "Main", "BotToken", typeof(string)); this.interval = (int)IniReadValue(iniSettings, "Main", "Interval", typeof(int)); this.debug = (bool)IniReadValue(iniSettings, "Debug", "Enabled", typeof(bool)); this.safeMode1C = (bool)GetAdditionalParamFromINI(iniSettings, "SafeMode1C", "Enabled", typeof(bool), "1"); this.buttonsShowStart = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "ShowStartButton", typeof(bool), "0"); this.buttonsHideKeyboard = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "HideButtonsAfterMessage", typeof(bool), "1"); this.buttonsNumRows = (int)GetAdditionalParamFromINI(iniSettings, "Buttons", "NumRowsOfButtons", typeof(int), "2"); this.buttonsUsePic = (bool)GetAdditionalParamFromINI(iniSettings, "Buttons", "UsePictures", typeof(bool), "1"); this.allowUsers = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "Users", typeof(string), "")); this.screenOwners = GetWhiteListOfUsers((string)GetAdditionalParamFromINI(iniSettings, "WhiteList", "ScreenOwners", typeof(string), "")); this.oscriptPath = (string)GetAdditionalParamFromINI(iniSettings, "Environment", "OneScriptPath", typeof(string), ""); try { // Старая версия ini-файла с одним прокси string host = (string)IniReadValue(iniSettings, "Proxy", "Server", typeof(string), true); if ((bool)GetAdditionalParamFromINI(iniSettings, "Proxy", "UseProxy", typeof(bool), "1")) { ProxyClient proxy = null; if ((int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Type", typeof(int), "0") == 0) { proxy = new HttpProxyClient(); } else { proxy = new Socks5ProxyClient(); } proxy.Host = host; proxy.Port = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Port", typeof(int), "0"); proxy.Username = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Username", typeof(string), ""); proxy.Password = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Password", typeof(string), ""); this.proxies.Add(proxy); } } catch { // Новая версия, где может быть несколько прокси int countProxies = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "CountProxy", typeof(int), "0"); int idxProxy = 0; while (idxProxy < countProxies) { ProxyClient proxy = null; if ((int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Type" + (idxProxy + 1), typeof(int), "0") == 0) { proxy = new HttpProxyClient(); } else { proxy = new Socks5ProxyClient(); } proxy.Host = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Server" + (idxProxy + 1), typeof(string), ""); proxy.Port = (int)GetAdditionalParamFromINI(iniSettings, "Proxy", "Port" + (idxProxy + 1), typeof(int), "0"); proxy.Username = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Username" + (idxProxy + 1), typeof(string), ""); proxy.Password = (string)GetAdditionalParamFromINI(iniSettings, "Proxy", "Password" + (idxProxy + 1), typeof(string), ""); this.proxies.Add(proxy); idxProxy++; } } if (!String.IsNullOrEmpty(botToken)) { if (this.interval == 0) { this.interval = 1; } iniOK = true; } else { Logger.Write("Settings.ini: не заполнен токен бота", true); } } catch (Exception e) { Logger.Write("Ошибка Settings.ini: " + e.Message, true); } } else { try { iniSettings.IniWriteValue("Main", "BotToken", ""); iniSettings.IniWriteValue("Main", "Interval", "1"); iniSettings.IniWriteValue("Proxy", "UseProxy", "0"); iniSettings.IniWriteValue("Proxy", "Server", ""); iniSettings.IniWriteValue("Proxy", "Port", ""); iniSettings.IniWriteValue("Proxy", "Username", ""); iniSettings.IniWriteValue("Proxy", "Password", ""); iniSettings.IniWriteValue("Proxy", "Type", "0"); iniSettings.IniWriteValue("Debug", "Enabled", "0"); iniSettings.IniWriteValue("SafeMode1C", "Enabled", "1"); iniSettings.IniWriteValue("Buttons", "ShowStartButton", "0"); iniSettings.IniWriteValue("Buttons", "HideButtonsAfterMessage", "1"); iniSettings.IniWriteValue("Buttons", "NumRowsOfButtons", "2"); iniSettings.IniWriteValue("WhiteList", "Users", ""); iniSettings.IniWriteValue("OneScriptPath", "Environment", ""); Logger.Write("Создан файл настроек \"settings.ini\""); } catch { Logger.Write("Не удалось создать файл \"settings.ini\"", true); } } return(iniOK); }