private int register(object connSett, bool active, string desc, bool bReq = false) { int id = -1, err = 0; //Блокировать доступ к словарю lock (this) //lock (m_objDictListeners) { //Проверить тип объекта с параметрами соединения if (connSett is ConnectionSettings == true) { //Проверить наличие уже установленного соединения // , и созданного объекта-потока для обработки запросов if ((m_dictDbInterfaces.ContainsKey(((ConnectionSettings)connSett).id) == true) && (bReq == false)) { try { id = m_dictDbInterfaces[((ConnectionSettings)connSett).id].ListenerRegister(); } catch (Exception e) { err = -1; } } else { ; } } else //Проверить тип объекта с параметрами соединения if (connSett is string == true) { } else { ; } //Проверить результат предыдущей операции if (err == 0) { if ((id < 0) && (m_dictDbInterfaces.ContainsKey(((ConnectionSettings)connSett).id) == false)) { string dbNameType = string.Empty; DbTSQLInterface.DB_TSQL_INTERFACE_TYPE dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.UNKNOWN; switch (((ConnectionSettings)connSett).port) { case -666: dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.ModesCentre; break; case 1433: dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.MSSQL; break; case 3306: dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.MySQL; break; case 1521: dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.Oracle; break; case -1221: dbType = DbTSQLInterface.DB_TSQL_INTERFACE_TYPE.Access; break; default: break; } dbNameType = dbType.ToString(); // switch (dbType) { case DbInterface.DB_TSQL_INTERFACE_TYPE.ModesCentre: //m_dictDbInterfaces.Add(((ConnectionSettings)connSett).id, new DbMCInterface (dbType, @"Интерфейс: " + dbNameType)); break; case DbInterface.DB_TSQL_INTERFACE_TYPE.MSSQL: case DbInterface.DB_TSQL_INTERFACE_TYPE.MySQL: case DbInterface.DB_TSQL_INTERFACE_TYPE.Oracle: case DbInterface.DB_TSQL_INTERFACE_TYPE.Access: m_dictDbInterfaces.Add(((ConnectionSettings)connSett).id, new DbTSQLInterface(dbType, @"Интерфейс: " + dbNameType + @"-БД" + @"; " + desc)); break; default: break; } try { if (active == true) { m_dictDbInterfaces[((ConnectionSettings)connSett).id].Start(); } else { ; } m_dictDbInterfaces[((ConnectionSettings)connSett).id].SetConnectionSettings(connSett, active); id = m_dictDbInterfaces[((ConnectionSettings)connSett).id].ListenerRegister(); } catch (Exception e) { Logging.Logg().Exception(e , @"DbSources::register () - ListenerRegister () - ConnectionSettings.ID=" + (connSett as ConnectionSettings).id , Logging.INDEX_MESSAGE.NOT_SET); err = -1; } } else { ; // m_dictDbInterfaces[((ConnectionSettings)connSett).id].Name = desc; } } else { ; } if (err == 0) { return(registerListener(ListenerIdLocal, ((ConnectionSettings)connSett).id, id, active, out err)); } else { return(err); } } }
void MessageBox(string msg, MessageBoxButtons btn = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Error) { //MessageBox.Show(this, msg, "ќшибка", MessageBoxButtons.OK, MessageBoxIcon.Error); Logging.Logg().Error(msg); }
public ConnectionSettingsError Validate() { if (port > 0) { try { IPAddress ip = IPAddress.Parse(server); if (IPAddress.TryParse(server, out ip) == false) { //MessageBox.Show("Неправильный ip-адрес.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.WrongIp); } } catch (Exception e) { Logging.Logg().Exception(e, @"ConnectionSettings::Validate() - ...", Logging.INDEX_MESSAGE.NOT_SET); } } if (port > 65535) { //MessageBox.Show("Порт должен лежать в пределах [0:65535].", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.WrongPort); } if (dbName == "") { //MessageBox.Show("Не задано имя базы данных.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.WrongDbName); } if (dbName.IndexOf('\'') >= 0 || dbName.IndexOf('\"') >= 0 || dbName.IndexOf('\\') >= 0 || dbName.IndexOf('/') >= 0 || dbName.IndexOf('?') >= 0 || dbName.IndexOf('<') >= 0 || dbName.IndexOf('>') >= 0 || dbName.IndexOf('*') >= 0 || dbName.IndexOf('|') >= 0 || dbName.IndexOf(':') >= 0 || dbName.IndexOf(';') >= 0) { //MessageBox.Show("Недопустимый символ в имени базы.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.IllegalSymbolDbName); } if (userName.IndexOf('\'') >= 0 || userName.IndexOf('\"') >= 0 || userName.IndexOf('\\') >= 0 || userName.IndexOf('/') >= 0 || userName.IndexOf('?') >= 0 || userName.IndexOf('<') >= 0 || userName.IndexOf('>') >= 0 || userName.IndexOf('*') >= 0 || userName.IndexOf('|') >= 0 || userName.IndexOf(':') >= 0 || userName.IndexOf(';') >= 0) { //MessageBox.Show("Недопустимый символ в имени пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.IllegalSymbolUserName); } if (password.IndexOf('\'') >= 0 || password.IndexOf('\"') >= 0 || password.IndexOf('\\') >= 0 || password.IndexOf('/') >= 0 || password.IndexOf('?') >= 0 || password.IndexOf('<') >= 0 || password.IndexOf('>') >= 0 || password.IndexOf('*') >= 0 || password.IndexOf('|') >= 0 || password.IndexOf(':') >= 0 || password.IndexOf(';') >= 0) { //MessageBox.Show("Недопустимый символ в пароле пользователя.", "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); return(ConnectionSettingsError.IllegalSymbolPassword); } //if (DbTSQLInterface.Select(this, "SELECT * FROM TEC_LIST").Rows.Count > 0) // return ConnectionSettingsError.NotConnect; //else // ; return(ConnectionSettingsError.NoError); }
private void DbInterface_ThreadFunction(object data) { object request; bool result; bool reconnection /* = false*/; while (threadIsWorking) { sem.WaitOne(); lock (lockConnectionSettings) // атомарно читаю и сбрасываю флаг, чтобы при параллельной смене настроек не сбросить повторно выставленный флаг { reconnection = needReconnect; needReconnect = false; } if (reconnection == true) { Disconnect(); connected = false; if ((threadIsWorking == true) && (Connect() == true)) { connected = true; } else { needReconnect = true; // выставлять флаг можно без блокировки } } else { ; } if (connected == false) // не удалось подключиться - не пытаемся получить данные { continue; } else { ; } //Logging.Logg().Debug("DbInterface::DbInterface_ThreadFunction () - m_listListeners.Count = " + m_listListeners.Count); lock (lockListeners) { foreach (KeyValuePair <int, DbInterfaceListener> pair in m_dictListeners) { //lock (lockListeners) //{ if (pair.Value.listenerActive == false) { continue; } else { ; } request = pair.Value.requestDB; if ((request == null) || (!(request.ToString().Length > 0))) { continue; } else { ; } //} //Logging.Logg().Debug("DbInterface::DbInterface_ThreadFunction () - GetData(...) - request = " + request); try { result = GetData(pair.Value.dataTable, request); } catch (DbException e) { Logging.Logg().Exception(e, "DbInterface::DbInterface_ThreadFunction () - result = GetData(...) - request = " + request, Logging.INDEX_MESSAGE.NOT_SET); result = false; } //Logging.Logg().Debug("DbInterface::DbInterface_ThreadFunction () - result = GetData(...) - result = " + result); //lock (lockListeners) //{ if (pair.Value.listenerActive == false) { continue; } else { ; } //Logging.Logg().Debug("DbInterface::DbInterface_ThreadFunction () - result = GetData(...) - pair.Value.listenerActive = " + pair.Value.listenerActive); if (request == pair.Value.requestDB) { pair.Value.dataPresent = result; pair.Value.dataError = !result; //if (result == true) //{ // pair.Value.dataPresent = true; //} //else //{ // pair.Value.dataError = true; //} pair.Value.requestDB = null; } else { ; } //Logging.Logg().Debug("DbInterface::DbInterface_ThreadFunction () - result = GetData(...) - pair.Value.dataPresent = " + pair.Value.dataPresent + @", pair.Value.dataError = " + pair.Value.dataError.ToString ()); //} } } } try { if (!(WaitHandle.WaitAny(new WaitHandle[] { sem }, 0) == 0)) { sem.Release(1); } else { ; } } catch (Exception e) { Logging.Logg().Exception(e, "DbInterface::DbInterface_ThreadFunction () - выход...", Logging.INDEX_MESSAGE.NOT_SET); } Disconnect(); }
void MessageBox(string msg, MessageBoxButtons btn = MessageBoxButtons.OK, MessageBoxIcon icon = MessageBoxIcon.Error) { //MessageBox.Show(this, msg, "Ошибка", MessageBoxButtons.OK, MessageBoxIcon.Error); Logging.Logg().Error(msg, Logging.INDEX_MESSAGE.NOT_SET); }
private static void logging_open_db(DbConnection conn) { string s = ConnectionStringToLog(conn.ConnectionString); Logging.Logg().Debug(MessageDbOpen + " (" + s + ")", Logging.INDEX_MESSAGE.NOT_SET, true); }
private static void logging_close_db(DbConnection conn) { string s = ConnectionStringToLog(conn.ConnectionString); Logging.Logg().Debug(MessageDbClose + " (" + s + ")", Logging.INDEX_MESSAGE.NOT_SET); }
/// <summary> /// Потоковая функция /// </summary> /// <param name="data">Параметр при старте потоковой функции</param> private void ThreadStates(object data) { int /*StatesMachine*/ currentState; bool bRes = false; int requestIsOk = 0 , responseIsOk = 0; INDEX_WAITHANDLE_REASON reason = INDEX_WAITHANDLE_REASON.SUCCESS; while (!(threadStateIsWorking < 0)) { bRes = false; bRes = semaState.WaitOne(); try { _indexCurState = 0; lock (m_lockState) { if (states.Count == 0) { continue; } else { ; } currentState = states[_indexCurState]; newState = false; } while (true) { requestIsOk = responseIsOk = 0; reason = INDEX_WAITHANDLE_REASON.SUCCESS; bool error = true; int dataPresent = -1; object objRes = null; for (int i = 0; i < DbInterface.MAX_RETRY && (!(dataPresent == 0)) && (newState == false); i++) { if (error) { requestIsOk = StateRequest(currentState); if (!(requestIsOk == 0)) { break; } else { ; } } else { ; } error = false; for (int j = 0; j < DbInterface.MAX_WAIT_COUNT && (!(dataPresent == 0)) && (error == false) && (newState == false); j++) { System.Threading.Thread.Sleep(DbInterface.WAIT_TIME_MS); dataPresent = StateCheckResponse(currentState, out error, out objRes); } } if (requestIsOk == 0) { if ((dataPresent == 0) && (error == false) && (newState == false)) { responseIsOk = StateResponse(currentState, objRes); } else { responseIsOk = -1; } if (responseIsOk == -102) { //Для алгоритма сигнализации 'TecView::SuccessThreadRDGValues () - ...' reason = INDEX_WAITHANDLE_REASON.BREAK; } else if (((!(responseIsOk == 0)) || (!(dataPresent == 0)) || (error == true)) && (newState == false)) { if (responseIsOk < 0) { reason = StateErrors(currentState, requestIsOk, responseIsOk); lock (m_lockState) { if (newState == false) { states.Clear(); break; } else { ; } } } else { StateWarnings(currentState, requestIsOk, responseIsOk); } } else { ; } } else { //14.04.2015 ??? //StateErrors(currentState, requestIsOk, -1); lock (m_lockState) { if (newState == false) { states.Clear(); break; } else { ; } } } _indexCurState++; lock (m_lockState) { if (_indexCurState == states.Count) { break; } else { ; } if (newState) { break; } else { ; } currentState = states[_indexCurState]; } } //Закончена обработка всех событий completeHandleStates(reason); //Текущий индекс вне дипазона _indexCurState = -1; } catch (Exception e) { Logging.Logg().Exception(e, Logging.INDEX_MESSAGE.NOT_SET, @"HHandler::ThreadStates () - ..."); } } //Освободить ресурс ядра ОС if (bRes == false) { try { semaState.Release(1); } catch (Exception e) { //System.Threading.SemaphoreFullException Logging.Logg().Exception(e, Logging.INDEX_MESSAGE.NOT_SET, "HHandler::ThreadStates () - semaState.Release(1)"); } } else { ; } }
/// <summary> /// Потоковая функция очереди обработки объектов с событиями /// </summary> /// <param name="par"></param> private void ThreadQueue(object par) { bool bRes = false; ItemQueue itemQueue = null; while (!(threadQueueIsWorking < 0)) { bRes = false; //Ожидать когда появятся объекты для обработки bRes = semaQueue.WaitOne(); while (true) { lock (m_lockQueue) { if (m_queue.Count == 0) { //Прерват, если обработаны все объекты break; } else { ; } } //Получить объект очереди событий itemQueue = Peek; lock (m_lockState) { //Очистить все состояния ClearStates(); //Добавить все состояния в родительский класс addStates(itemQueue); } //Обработать все состояния Run(@"HHandler::ThreadQueue ()"); //Ожидать обработки всех состояний m_waitHandleState[(int)INDEX_WAITHANDLE_REASON.SUCCESS].WaitOne(System.Threading.Timeout.Infinite, true); lock (m_lockQueue) { //Удалить объект очереди событий (обработанный) m_queue.Dequeue(); } } } //Освободить ресурс ядра ОС //??? "везде" 'true' if (bRes == false) { try { semaQueue.Release(1); } catch (Exception e) { //System.Threading.SemaphoreFullException Logging.Logg().Exception(e, "HHandler::ThreadQueue () - semaState.Release(1)", Logging.INDEX_MESSAGE.NOT_SET); } } else { ; } }
/// <summary> /// Загрузить плюгИн с указанным наименованием /// </summary> /// <param name="name">Наименование плюгИна</param> /// <param name="iRes">Результат загрузки (код ошибки)</param> /// <returns>Загруженный плюгИн</returns> protected PlugInBase load(string name, out int iRes) { PlugInBase plugInRes = null; Assembly ass = null; iRes = -1; Type objType = null; try { #if _SEPARATE_APPDOMAIN if (isInitPluginAppDomain == false) { initPluginDomain(); } else { ; } #endif ass = #if _SEPARATE_APPDOMAIN m_proxyAppDomain.GetAssembly #else Assembly.LoadFrom #endif (Environment.CurrentDirectory + @"\" + name + @".dll"); if (!(ass == null)) { objType = ass.GetType(name + ".PlugIn"); } else { ; } } catch (Exception e) { Logging.Logg().Exception(e, @"FormMain::loadPlugin () ... LoadFrom () ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET); } if (!(objType == null)) { try { plugInRes = ((PlugInBase)Activator.CreateInstance(objType)); plugInRes.Host = (IPlugInHost)this; //Вызов 'Register' iRes = 0; } catch (Exception e) { iRes = -2; Logging.Logg().Exception(e, @"FormMain::loadPlugin () ... CreateInstance ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET); } } else { Logging.Logg().Error(@"FormMain::loadPlugin () ... Assembly.GetType()=null ... plugIn.Name = " + name, Logging.INDEX_MESSAGE.NOT_SET); } return(plugInRes); }