private void ShowError(string errormessage) { Data.SendToErrorsLog(errormessage); foreach (var panel in _panels.Where(panel => panel != null)) { panel.ErrorMessage = errormessage; } }
private static void MyHandler(object sender, UnhandledExceptionEventArgs args) { var ex = (Exception)args.ExceptionObject; Data.SendToErrorsLog("Не обслуживаемая ошибка: " + ex.FullMessage()); if (args.IsTerminating) { Data.SendToErrorsLog("Приложение будет аварийно завершено"); } }
public void FromString(string value) { try { _values.Clear(); //read file to string array var allLines = value.Split(new[] { '\n' }); #region Local variables var sHeader = ""; var keys = new NameValueCollection(); #endregion //and restructure it in memory for faster access foreach (var sTmp in allLines.Select(s => s.Trim()).Where(sTmp => !string.IsNullOrEmpty(sTmp)).Where(sTmp => !sTmp.StartsWith(";"))) { //[header] if (sTmp.StartsWith("[") && sTmp.EndsWith("]")) { //add values to collection if (sHeader != "") { _values.Add(sHeader, new NameValueCollection(keys)); } //new header sHeader = sTmp.Substring(1, sTmp.Length - 2); keys.Clear(); continue; } if (sTmp.IndexOf('=') == -1) { keys.Add(sTmp, ""); } else { var sKeys = sTmp.Split(new[] { '=' }, 2); keys.Add(sKeys[0], sKeys[1]); } } for (var i = 0; i < keys.Count; i++) { WriteString(sHeader, keys.GetKey(i), keys.Get(i)); } } catch (Exception ex) { Data.SendToErrorsLog("Ошибка в FromString() класса MemIniFile: " + ex.FullMessage()); } }
public override string ToString() { try { var list = new List <string>(); foreach (string section in _values.Keys) { list.Add(string.Concat("[", section, "]")); var nv = (NameValueCollection)_values[section]; list.AddRange(from string key in nv.Keys select key + "=" + nv[key]); } return(String.Join("\n", list.ToArray())); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка в ToString() класса MemIniFile: " + ex.FullMessage()); return(""); } }
private static void WorkerDoWork(object sender, DoWorkEventArgs e) { var worker = (BackgroundWorker)sender; var arg = (FetchArg)e.Argument; var lastsecond = DateTime.Now.Second; var lastminute = -1; var lasthour = -1; while (!worker.CancellationPending) { Thread.Sleep(400); // разрузка процессоров try { var dt = DateTime.Now; if (lastsecond == dt.Second) { continue; } lastsecond = dt.Second; Data.FetchRisers(worker, arg); if (lastminute == dt.Minute) { continue; } lastminute = dt.Minute; if (lasthour == dt.Hour || dt.Minute != 0) { continue; } lasthour = dt.Hour; } catch (Exception ex) { var mess = ex.FullMessage(); Console.WriteLine(mess); Data.SendToErrorsLog("Ошибка в цикле опроса канала: " + mess); } } }
private void FormMain_FormClosing(object sender, FormClosingEventArgs e) { Data.SendToSystemLog(string.Format("Останов системы на станции {0}", Environment.MachineName)); var dt = DateTime.Now + new TimeSpan(0, 0, 0, 1); while (dt > DateTime.Now) { Application.DoEvents(); } //Код, выполняемый при остановке процесса try { if (_wcfEventService != null) { _wcfEventService.Stop(); } } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при остановке локального сервера подписки: " + ex.FullMessage()); } foreach (var worker in Workers.Where(worker => worker.IsBusy)) { worker.CancelAsync(); } dt = DateTime.Now + new TimeSpan(0, 0, 0, 1); while (dt > DateTime.Now) { Application.DoEvents(); } _fileLogsWatcher.Changed -= fileSystemLogWatcher_Changed; _fileLogsWatcher.Created -= fileSystemLogWatcher_Changed; _fileLogsWatcher.Dispose(); if (Data.RunningAsShell() || Data.MustWinLogOff) { WinLogOff(); } }
private void FormConfig_Load(object sender, EventArgs e) { try { cbSystemShell.Checked = Data.Config.ReadBool("GeneralFor" + Environment.UserName, "SystemShell", false); cbDisableTaskManager.Checked = _lastDisableTaskManagerState = Data.Config.ReadBool("GeneralFor" + Environment.UserName, "DisableTaskMgr", false); nudStartTaskPeriod.Value = Data.Config.ReadInteger("General", "StartTaskPeriod", 3000); nudStopTaskPeriod.Value = Data.Config.ReadInteger("General", "StopTaskPeriod", 3000); nudLogViewMessagesCount.Value = _lastWorklogMessagesCount = Data.Config.ReadInteger("General", "LogMessagesCount", 500); сbShowReadyAndAlarm.Checked = Data.Config.ReadBool("FillingPageCommon", "ShowReadyAndAlarm", false); cbUseSmartLevel.Checked = Data.Config.ReadBool("FillingPageCommon", "UseSmartLevel", true); nudSmartLevelDifferent.Value = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelDifferent", 3); nudSmartLevelQueueSize.Value = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelQueueSize", 15); nudDeleteLogsAfter.Value = Data.Config.ReadInteger("General", "DeleteLogsAfter", 90); nudDeleteTrendsAfter.Value = Data.Config.ReadInteger("General", "DeleteTrendsAfter", 14); nudMonitors.Value = _lastMonitors = Data.Config.ReadInteger("Station", "Monitors", 1); cbEnableLocalEventServer.Checked = Data.Config.ReadBool("DataEventServers", "EnableLocalEventServer", false); cbEventServer1.Checked = Data.Config.ReadBool("DataEventServers", "EnableEventServer1", false); tbEventServer1.Text = Data.Config.ReadString("DataEventServers", "AddressEventServer1", ""); cbEventServer2.Checked = Data.Config.ReadBool("DataEventServers", "EnableEventServer2", false); tbEventServer2.Text = Data.Config.ReadString("DataEventServers", "AddressEventServer2", ""); cbEventServer3.Checked = Data.Config.ReadBool("DataEventServers", "EnableEventServer3", false); tbEventServer3.Text = Data.Config.ReadString("DataEventServers", "AddressEventServer3", ""); cbEventServer4.Checked = Data.Config.ReadBool("DataEventServers", "EnableEventServer4", false); tbEventServer4.Text = Data.Config.ReadString("DataEventServers", "AddressEventServer4", ""); tbSelfIpAddress.Text = Data.Config.ReadString("DataEventServers", "SelfIpAddress", ""); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при загрузке конфигурации в окно редактирования: " + ex.FullMessage()); } btnApply.Enabled = false; }
/// <summary> /// Load ini to memory. Private /// </summary> /// <param name="name"></param> private void LoadIni(string name) { var trycount = 10; while (true) { try { _values.Clear(); //no file found, nothing to load if (!File.Exists(name)) { return; } //read file to string array var allLines = File.ReadAllLines(name); #region Local variables var sHeader = ""; var keys = new NameValueCollection(); #endregion //and restructure it in memory for faster access foreach (var sTmp in allLines.Select(s => s.Trim()).Where(sTmp => !string.IsNullOrEmpty(sTmp)) .Where(sTmp => !sTmp.StartsWith(";"))) { //[header] if (sTmp.StartsWith("[") && sTmp.EndsWith("]")) { //add values to collection if (sHeader != "") { _values.Add(sHeader, new NameValueCollection(keys)); } //new header sHeader = sTmp.Substring(1, sTmp.Length - 2); keys.Clear(); continue; } if (sTmp.IndexOf('=') == -1) { keys.Add(sTmp, ""); } else { var sKeys = sTmp.Split(new[] { '=' }, 2); keys.Add(sKeys[0], sKeys[1]); } } for (var i = 0; i < keys.Count; i++) { WriteString(sHeader, keys.GetKey(i), keys.Get(i)); } break; } catch (Exception ex) { trycount--; if (trycount <= 0) { Data.SendToErrorsLog("Ошибка в LoadIni() класса MemIniFile: " + ex.FullMessage()); } Thread.Sleep(500); } } }
private void FormMain_Load(object sender, EventArgs e) { #region Защита от повторного запуска var process = RunningInstance(); if (process != null) { Application.Exit(); return; } #endregion Width = 0; Height = 1; Data.Session = new MemIniFile(""); Data.FileToErrorsFullName = Path.ChangeExtension(Application.ExecutablePath, ".err"); Data.ResetErrorsLog(); var tasksFileName = Path.ChangeExtension(Application.ExecutablePath, ".tsk"); Data.Tasks = new MemIniFile(tasksFileName); var configFileName = Path.ChangeExtension(Application.ExecutablePath, ".ini"); Data.Config = new MemIniFile(configFileName); var currentPath = Application.StartupPath; var configFolder = Path.Combine(currentPath, "MultiFillingConfig"); if (!Directory.Exists(configFolder)) { try { Directory.CreateDirectory(configFolder); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при создании папки " + configFolder + ": " + ex.FullMessage()); Application.Exit(); return; } } Data.ConfigFolder = configFolder; #region импорт файла типов вагонов //var typeFile = Path.Combine(configFolder, "waggontypes.txt"); //if (File.Exists(typeFile)) //{ // TypesListKeeper.Clear(); // var n = 0; // foreach (var vals in File.ReadLines(typeFile).Select(line => line.Split(new[] { '\t' }))) // { // if (n > 0 && vals.Length == 5) // { // int diameter, throat, deflevel; // if (!string.IsNullOrWhiteSpace(vals[0]) && // int.TryParse(vals[1], out diameter) && // int.TryParse(vals[2], out throat) && // int.TryParse(vals[3], out deflevel)) // { // TypesListKeeper.Add(vals[0], diameter, throat, deflevel); // } // } // n++; // } // typeFile = Path.Combine(configFolder, "wagtypes.xml"); // TypesListKeeper.SaveTypesData(typeFile); //} #endregion TypeDataKeeper.LoadTypesData(Path.Combine(configFolder, "wagtypes.xml")); #region импорт и экспорт файла вагонов //var wagFile = Path.Combine(configFolder, "_waggons.txt"); //if (File.Exists(wagFile)) //{ // var filename = Path.Combine(configFolder, "waggons.txt"); // using (var stream = new FileStream(filename, FileMode.Append)) // { // using (var writer = new StreamWriter(stream)) // { // var n = 0; // foreach (var vals in File.ReadLines(wagFile).Select(line => line.Split(new[] {'\t'}))) // { // if (n > 0 && vals.Length == 5) // { // var number = vals[0]; // var ntype = vals[1]; // int factlevel; // if (!string.IsNullOrWhiteSpace(number) && // !string.IsNullOrWhiteSpace(ntype) && // int.TryParse(vals[2], out factlevel)) // { // var content = string.Format("{0}\t{1}\t{2}", number, ntype, factlevel); // writer.WriteLine(content); // writer.Flush(); // } // } // n++; // } // } // } //} #endregion var logFolder = Path.Combine(currentPath, "MultiFillingLogs"); if (!Directory.Exists(logFolder)) { try { Directory.CreateDirectory(logFolder); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при создании папки " + logFolder + ": " + ex.FullMessage()); Application.Exit(); return; } } Data.LogsFolder = logFolder; Data.SendToSystemLog(string.Format("Запуск системы на станции {0}", Environment.MachineName)); var dt = DateTime.Now + new TimeSpan(0, 0, 0, 3); while (dt > DateTime.Now) { Application.DoEvents(); } _fileLogsWatcher = new FileSystemWatcher { Path = logFolder, EnableRaisingEvents = true, Filter = "*.log", NotifyFilter = NotifyFilters.LastWrite, SynchronizingObject = this }; _fileLogsWatcher.Changed += fileSystemLogWatcher_Changed; _fileLogsWatcher.Created += fileSystemLogWatcher_Changed; var historyFolder = Path.Combine(currentPath, "MultiFillingHistory"); if (!Directory.Exists(historyFolder)) { try { Directory.CreateDirectory(historyFolder); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при создании папки " + historyFolder + ": " + ex.FullMessage()); Application.Exit(); return; } } Data.HistoryFolder = historyFolder; Data.SystemShell = Data.Config.ReadBool("GeneralFor" + Environment.UserName, "SystemShell", false); Data.StartTaskPeriod = Data.Config.ReadInteger("General", "StartTaskPeriod", 3000); Data.StopTaskPeriod = Data.Config.ReadInteger("General", "StopTaskPeriod", 3000); Data.DeleteLogsAfter = Data.Config.ReadInteger("General", "DeleteLogsAfter", 90); Data.DeleteTrendsAfter = Data.Config.ReadInteger("General", "DeleteTrendsAfter", 14); Data.ShowReadyAndAlarm = Data.Config.ReadBool("FillingPageCommon", "ShowReadyAndAlarm", false); Data.UseSmartLevel = Data.Config.ReadBool("FillingPageCommon", "UseSmartLevel", true); Data.SmartLevelDifferent = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelDifferent", 3); Data.SmartLevelQueueSize = Data.Config.ReadInteger("FillingPageCommon", "SmartLevelQueueSize", 15); // Загрузка конфигурации опроса try { LoadFetchConfiguration(); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при загрузке конфигурации опроса: " + ex.FullMessage()); } #region Построение рабочих панелей var monitors = Screen.AllScreens; _panels = new FormPanel[monitors.Length]; if (!Data.Config.KeyExists("Station", "Monitors")) { Data.Config.WriteInteger("Station", "Monitors", 1); Data.Config.UpdateFile(); } var screens = Data.Config.ReadInteger("Station", "Monitors", 1); for (var i = 0; i < monitors.Length; i++) { _panels[i] = new FormPanel(this, monitors[i].Primary, monitors[i].WorkingArea) { Visible = false, DisplayIndex = i + 1 }; _panels[i].Show(this); _panels[i].Refresh(); if (screens > 0 && i + 1 >= screens) { break; } } #endregion Data.StationNodes[0] = new StationNode { Name = "Станция 1", Index = 1 }; Data.StationNodes[1] = new StationNode { Name = "Станция 2", Index = 2 }; Data.StationNodes[2] = new StationNode { Name = "Станция 3", Index = 3 }; Data.StationNodes[3] = new StationNode { Name = "Станция 4", Index = 4 }; Data.EnableLocalEventServer = Data.Config.ReadBool("DataEventServers", "EnableLocalEventServer", false); // Запуск сервера событий if (Data.EnableLocalEventServer) { _wcfEventService = WcfEventService.EventService; try { _wcfEventService.Start(); } catch (Exception ex) { Data.SendToErrorsLog("Ошибка при запуске локального сервера событий: " + ex.FullMessage()); } // Подключаемся клиентом сами к себе для рассылки событий возможным клиентам Data.LocalEventClient = new EventClient.EventClient(); Data.LocalEventClient.Connect("localhost", 9901, new[] { "Fetching", "Logging", "Trending" }, PropertyUpdate, ShowError, ClientFileReceived, UpdateLocalConnectionStatus); } Data.SelfIpAddress = Data.Config.ReadString("DataEventServers", "SelfIpAddress", ""); //var selfIpAddresses = Dns.GetHostAddresses(Dns.GetHostName()); // Подключаемся клиентом к другим станциям for (var i = 1; i <= Data.StationNodes.Length; i++) { var enable = Data.Config.ReadBool("DataEventServers", "EnableEventServer" + i, false); Data.StationNodes[i - 1].Enable = enable; var addr = Data.Config.ReadString("DataEventServers", "AddressEventServer" + i, ""); if (!enable) { continue; } IPAddress address; if (IPAddress.TryParse(addr, out address)) { Data.StationNodes[i - 1].Address = address; if (addr.Equals(Data.SelfIpAddress)) { Data.StationNodes[i - 1].ItThisStation = true; Data.StationNodes[i - 1].Descriptor = "Эта станция"; } if (!Data.StationNodes[i - 1].ItThisStation) { var id = Data.ConnectToEventServer(addr, 9901, new[] { "Fetching", "Logging", "Trending" }, PropertyUpdate, ShowError, ClientFileReceived, UpdateConnectionStatus); Data.StationNodes[i - 1].ClientId = id; } } else { Data.SendToErrorsLog( string.Format("Ошибка в IP-адресе для сервера подписки {0} в файле конфигурации", i)); } } // ---- lock (Data.RiserNodes) { foreach (var riser in Data.RiserNodes.Values) { if (string.IsNullOrWhiteSpace(riser.Number)) { continue; } var riserName = string.Format("{0}_{1}_{2}_{3}_{4}", riser.Channel, riser.Overpass, riser.Way, riser.Product, riser.Riser); Data.UpdateRiserProperty(riserName, "Number", riser.Number); Data.UpdateRiserProperty(riserName, "Ntype", riser.Ntype); Data.UpdateRiserProperty(riserName, "FactHeight", riser.FactHeight.ToString("0")); Data.UpdateRiserProperty(riserName, "Setpoint", riser.Setpoint.ToString("0")); Data.UpdateRiserProperty(riserName, "FilledKind", ""); } } // Запуск таймера для фонового удаления старых архивов _timer.Enabled = true; }