private void btnCreate_Click(object sender, EventArgs e) { // создание каналов string logFileName = AppData.ExeDir + "ScadaAdminCreateCnls.txt"; bool logCreated; string msg; bool createOK = CreateCnls.CreateChannels(kpInfoList, chkInsertKPName.Checked, logFileName, out logCreated, out msg); if (msg != "") { if (createOK) { ScadaUtils.ShowInfo(msg); } else { AppUtils.ProcError(msg); } } if (logCreated) { Process.Start(logFileName); } }
/// <summary> /// Импорт КП /// </summary> public static DialogResult Import(DataTable tblKP, int commLineNum, Log errLog, out FrmImport frmImport) { frmImport = null; try { tblKP.DefaultView.RowFilter = "CommLineNum = " + commLineNum; tblKP.DefaultView.Sort = "KPNum"; if (tblKP.DefaultView.Count == 0) { ScadaUtils.ShowInfo(AppPhrases.NoImportData); return(DialogResult.Cancel); } else { // заполнение дерева импортируемых данных: только КП frmImport = new FrmImport(); frmImport.commLineNum = commLineNum; TreeView treeView = frmImport.TreeView; treeView.ShowRootLines = false; try { treeView.BeginUpdate(); treeView.Nodes.Clear(); foreach (DataRowView rowKP in tblKP.DefaultView) { TreeNode nodeKP = new TreeNode(Settings.KP.GetCaption((int)rowKP["KPNum"], rowKP["Name"])); nodeKP.Tag = rowKP; treeView.Nodes.Add(nodeKP); } } finally { treeView.EndUpdate(); } // отображение формы импорта return(frmImport.ShowDialog()); } } catch (Exception ex) { string errMsg = AppPhrases.PrepareImportFormError2 + ":\r\n" + ex.Message; errLog.WriteAction(errMsg); ScadaUtils.ShowError(errMsg); return(DialogResult.Abort); } finally { try { tblKP.DefaultView.RowFilter = ""; } catch { } } }
/// <summary> /// Поиск следующего совпадения /// </summary> private bool FindNext(ColumnInfo columnInfo, bool showMsg) { string findStr = columnInfo.IsText ? txtFind.Text : ""; object findObj = columnInfo.IsText ? null : cbFind.SelectedValue; bool ignoreCase = !chkCaseSensitive.Checked; bool wholeCellOnly = chkWholeCellOnly.Checked; DataGridViewCell curCell = gridView.CurrentCell; bool found = false; int cnt = 0; int colInd = columnInfo.Column.Index; int rowInd = curCell == null ? 0 : curCell.RowIndex; if (curCell != null && curCell.ColumnIndex == colInd) { rowInd++; } int rowCnt = gridView.RowCount; while (cnt < rowCnt && !found) { if (rowInd == rowCnt) { rowInd = 0; } DataGridViewCell cell = gridView[colInd, rowInd]; found = columnInfo.IsText ? IsMatched(cell, findStr, ignoreCase, wholeCellOnly) : IsMatched(cell, findObj); if (found) { completeMsg = AppPhrases.FindCompleted; try { gridView.CurrentCell = cell; } catch { /* невозможно покинуть текущую ячйку, т.к. её значение некорректно */ } } rowInd++; cnt++; } if (cnt == rowCnt && !found) { if (showMsg) { ScadaUtils.ShowInfo(completeMsg); } completeMsg = AppPhrases.ValueNotFound; } return(found); }
private void miDbBackup_Click(object sender, EventArgs e) { // резервное копирование файла базы конфигурации string msg; if (ImportExport.BackupSDF(settings.AppSett.BaseSDFFile, settings.AppSett.BackupDir, out msg)) { ScadaUtils.ShowInfo(msg); } else { AppUtils.ProcError(msg); } }
private void miDbBackup_Click(object sender, EventArgs e) { // резервное копирование файла базы конфигурации try { string workFileName = settings.AppSett.BaseSDFFile; string backupDir = settings.AppSett.BackupDir; if (File.Exists(workFileName)) { if (Directory.Exists(backupDir)) { bool wasConnected = AppData.Connected; string backupFileName = backupDir + Path.GetFileNameWithoutExtension(workFileName) + DateTime.Now.ToString(" yyyy-MM-dd HH-mm-ss") + ".sdf"; try { if (wasConnected) { AppData.Conn.Close(); // для сохранения изменений } File.Copy(workFileName, backupFileName, true); } finally { if (wasConnected) { AppData.Conn.Open(); } } ScadaUtils.ShowInfo(string.Format(AppPhrases.BackupCompleted, backupFileName)); } else { ScadaUtils.ShowError(AppPhrases.BackupDirNotExists); } } else { ScadaUtils.ShowError(AppPhrases.BaseSDFFileNotExists); } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.BackupError + ":\r\n" + ex.Message); } }
private void btnImport_Click(object sender, EventArgs e) { // импорт выбранной таблицы из формата DAT Tables.TableInfo tableInfo = cbTable.SelectedItem as Tables.TableInfo; if (AppData.Connected) { string logFileName = chkImportLog.Checked ? AppData.ExeDir + "ScadaAdminImport.txt" : ""; bool importOK; bool logCreated; string msg; if (tableInfo == null) { // импорт архива importOK = ImportExport.ImportArchive(txtFileName.Text, Tables.TableInfoList, logFileName, out logCreated, out msg); } else { // импорт таблицы int minID = gbIDs.Enabled && chkStartID.Checked ? Convert.ToInt32(numStartID.Value) : 0; int maxID = gbIDs.Enabled && chkFinalID.Checked ? Convert.ToInt32(numFinalID.Value) : int.MaxValue; int newMinID = gbIDs.Enabled && chkNewStartID.Checked ? Convert.ToInt32(numNewStartID.Value) : 0; importOK = ImportExport.ImportTable(txtFileName.Text, tableInfo, minID, maxID, newMinID, logFileName, out logCreated, out msg); } // отображение сообщения о результате импорта if (importOK) { ScadaUtils.ShowInfo(msg); } else { AppUtils.ProcError(msg); } // отображение журанала в блокноте if (logCreated) { Process.Start(logFileName); } } }
private void miDbPassToServer_Click(object sender, EventArgs e) { // перевод базы конфигурации в формат DAT try { if (AppData.Connected) { string baseDatDir = settings.AppSett.BaseDATDir; if (Directory.Exists(baseDatDir)) { // создание файла блокировки базы конфигурации string baseLockPath = baseDatDir + "baselock"; FileStream baseLockStream = new FileStream(baseLockPath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite); baseLockStream.Close(); try { // сохранение таблиц базы конфигурации в формате DAT BaseAdapter adapter = new BaseAdapter(); foreach (Tables.TableInfo tableInfo in Tables.TablesInfo) { DataTable table = tableInfo.GetTable(); adapter.FileName = baseDatDir + tableInfo.FileName; adapter.Update(table); } } finally { // удаление файла блокировки базы конфигурации File.Delete(baseLockPath); } ScadaUtils.ShowInfo(AppPhrases.DbPassCompleted); } else { ScadaUtils.ShowError(CommonPhrases.BaseDATDirNotExists); } } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.DbPassError + ":\r\n" + ex.Message); } }
private void miDbCompact_Click(object sender, EventArgs e) { // упаковка файла базы конфигурации try { if (AppData.Compact()) { ScadaUtils.ShowInfo(AppPhrases.CompactCompleted); } else { ScadaUtils.ShowError(AppPhrases.ConnectionUndefined); } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.CompactError + ":\r\n" + ex.Message); } }
private void miSettingsLanguage_Click(object sender, EventArgs e) { // создание и отображение формы выбора языка string prevCultureName = FrmLanguage.CultureName; FrmLanguage frmLanguage = new FrmLanguage(); if (frmLanguage.ShowDialog() == DialogResult.OK && prevCultureName != FrmLanguage.CultureName) { // запись культуры для выбранного языка в реестр string errMsg; if (Localization.WriteCulture(FrmLanguage.CultureName, out errMsg)) { ScadaUtils.ShowInfo(AppPhrases.LanguageChanged); } else { AppUtils.ProcError(errMsg); } } }
private void btnExport_Click(object sender, EventArgs e) { // экспорт выбранной таблицы в формат DAT Tables.TableInfo tableInfo = cbTable.SelectedItem as Tables.TableInfo; if (tableInfo != null && AppData.Connected) { int minID = gbIDs.Enabled && chkStartID.Checked ? Convert.ToInt32(numStartID.Value) : 0; int maxID = gbIDs.Enabled && chkFinalID.Checked ? Convert.ToInt32(numFinalID.Value) : int.MaxValue; string msg; if (ImportExport.ExportTable(tableInfo, txtFileName.Text, minID, maxID, out msg)) { ScadaUtils.ShowInfo(msg); } else { AppUtils.ProcError(msg); } } }
private void btnExport_Click(object sender, EventArgs e) { // экспорт выбранной таблицы в формат DAT try { Tables.TableInfo tableInfo = cbTable.SelectedItem as Tables.TableInfo; if (tableInfo != null && AppData.Connected) { string fileName = txtFileName.Text.Trim(); string directory = fileName == "" ? "" : Path.GetDirectoryName(fileName); if (directory == "") { ScadaUtils.ShowError(AppPhrases.ExportDirUndefied); } else { if (Directory.Exists(directory)) { BaseAdapter adapter = new BaseAdapter(); DataTable table = tableInfo.GetTable(); adapter.FileName = fileName; adapter.Update(table); ScadaUtils.ShowInfo(AppPhrases.ExportCompleted); } else { ScadaUtils.ShowError(AppPhrases.ExportDirNotExists); } } } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.ExportError + ":\r\n" + ex.Message); } }
private void miDbPassToServer_Click(object sender, EventArgs e) { if (AppData.Connected) { // резервное копирование файла базы конфигурации string msg; if (settings.AppSett.AutoBackupBase && !ImportExport.BackupSDF(settings.AppSett.BaseSDFFile, settings.AppSett.BackupDir, out msg)) { AppUtils.ProcError(msg); } // конвертирование базы конфигурации в формат DAT if (ImportExport.PassBase(Tables.TableInfoList, settings.AppSett.BaseDATDir, out msg)) { ScadaUtils.ShowInfo(msg); } else { AppUtils.ProcError(msg); } } }
private void btnExport_Click(object sender, EventArgs e) { // отправка команды экспорта int ctrlCnlNum; string cmdDataStr = cbDataSource.Text; if (sender == btnExportArcData) { ctrlCnlNum = ArcDataCtrlCnlNum; DateTime dateTime = dtpArcDataDate.Value.Date.Add(dtpArcDataTime.Value.TimeOfDay); cmdDataStr += "\n" + ScadaUtils.XmlValToStr(dateTime); } else if (sender == btnExportEvents) { ctrlCnlNum = EventsCtrlCnlNum; DateTime date = dtpEventsDate.Value.Date; cmdDataStr += "\n" + ScadaUtils.XmlValToStr(date); } else { ctrlCnlNum = CurDataCtrlCnlNum; } bool result; byte[] cmdData = Encoding.Default.GetBytes(cmdDataStr); if (ServerComm.SendBinaryCommand(0, ctrlCnlNum, cmdData, out result)) { ScadaUtils.ShowInfo(CommonPhrases.CmdSentSuccessfully); } else { ScadaUtils.ShowError(ServerComm.ErrMsg); } }
private void FrmMain_Load(object sender, EventArgs e) { // определение директории исполняемого файла приложения exeDir = ScadaUtils.NormalDir(Path.GetDirectoryName(Application.ExecutablePath)); // локализация приложения string langDir = exeDir + "lang\\"; string errMsg; if (Localization.LoadingRequired(langDir, "ScadaData")) { if (Localization.LoadDictionaries(langDir, "ScadaData", out errMsg)) { CommonPhrases.Init(); } else { ScadaUtils.ShowError(errMsg); } } if (Localization.LoadingRequired(langDir, "ScadaSchemeEditor")) { if (Localization.LoadDictionaries(langDir, "ScadaSchemeEditor", out errMsg)) { Localization.TranslateForm(this, "Scada.Scheme.Editor.FrmMain"); SchemePhrases.InitStatic(); openFileDialog.Filter = saveFileDialog.Filter = SchemePhrases.FileFilter; } else { ScadaUtils.ShowError(errMsg); } } // инициализация данных SchemeApp schemeApp = SchemeApp.InitSchemeApp(SchemeApp.WorkModes.Edit); schemeUrl = exeDir + "web\\ScadaScheme.html?editMode=true"; editorData = schemeApp.EditorData; editorData.SelectElement = SelectElement; editorData.SetFormTitle = SetFormTitle; log = schemeApp.Log; elemClipboard = null; schemeSvcHost = null; domainSvcHost = null; schemeExThread = null; // проверка запуска второй копии программы try { bool createdNew; mutex = new Mutex(true, "ScadaSchemeEditorMutex", out createdNew); if (!createdNew) { ScadaUtils.ShowInfo("SCADA-Редактор схем уже запущен.\nВторая копия будет закрыта."); Close(); return; } } catch (Exception ex) { log.WriteAction("Ошибка при проверке запуска второй копии программы: " + ex.Message, Log.ActTypes.Exception); } // запуск WCF-служб if (StartWCF()) { // создание и запуск потока для обмена данными со схемой schemeExThread = new Thread(SchemeExchange); schemeExThread.Start(); // настройка элементов управления miEditCut.Enabled = btnEditCut.Enabled = false; miEditCopy.Enabled = btnEditCopy.Enabled = false; miEditPaste.Enabled = btnEditPaste.Enabled = false; miSchemeCancelAddElem.Enabled = btnSchemeCancelAddElem.Enabled = false; miSchemeDelElem.Enabled = btnSchemeDelElem.Enabled = false; // создание новой схемы miFileNew_Click(null, null); } else { // блокировка элементов управления foreach (ToolStripItem item in miFile.DropDown.Items) { item.Enabled = item == miFileExit; } foreach (ToolStripItem item in miEdit.DropDown.Items) { item.Enabled = false; } foreach (ToolStripItem item in miScheme.DropDown.Items) { item.Enabled = false; } foreach (ToolStripItem item in toolMain.Items) { item.Enabled = false; } } }
/// <summary> /// Создать каналы /// </summary> private void CreateCnls() { writer = null; bool logCreated = false; string logFileName = AppData.ExeDir + "ScadaAdminCreateCnls.txt"; try { // создание журанала создания каналов writer = new StreamWriter(logFileName, false, Encoding.UTF8); logCreated = true; string title = DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.CreateCnlsTitle; writer.WriteLine(title); writer.WriteLine(new string('-', title.Length)); writer.WriteLine(); // определение используемых выбранными КП объектов пользовательского интерфейса КП List <KPView> usedKPViewList = new List <KPView>(); foreach (KPParams kpParams in kpParamsList) { if (kpParams.Selected) { KPView kpView = kpParams.KPView; if (kpView != null && !usedKPViewList.Contains(kpView)) { usedKPViewList.Add(kpView); } } } // формирование справочников используемых наименований SortedList <string, int> paramList = new SortedList <string, int>(); SortedList <string, int> unitList = new SortedList <string, int>(); SortedList <string, int> cmdValList = new SortedList <string, int>(); foreach (KPView kpView in usedKPViewList) { if (kpView.DefaultCnls != null) { foreach (KPView.InCnlProps inCnlProps in kpView.DefaultCnls) { string s = inCnlProps.ParamName; if (s != "" && !paramList.ContainsKey(s)) { paramList.Add(s, -1); } s = inCnlProps.UnitName; if (s != "" && !unitList.ContainsKey(s)) { unitList.Add(s, -1); } if (inCnlProps.CtrlCnlProps != null) { s = inCnlProps.CtrlCnlProps.CmdValName; if (s != "" && !cmdValList.ContainsKey(s)) { cmdValList.Add(s, -1); } } } } } // определение идентификаторов в справочниках writer.WriteLine(AppPhrases.CheckDicts); bool paramError = FindDictIDs(paramList, Tables.GetParamTable(), "ParamID", AppPhrases.ParamNotFound); bool unitError = FindDictIDs(unitList, Tables.GetUnitTable(), "UnitID", AppPhrases.UnitNotFound); bool cmdValError = FindDictIDs(cmdValList, Tables.GetCmdValTable(), "CmdValID", AppPhrases.CmdValsNotFound); if (paramError || unitError || cmdValError) { writer.WriteLine(AppPhrases.CreateCnlsImpossible); } else { writer.WriteLine(AppPhrases.CreateCnlsStart); // заполнение схем таблиц входных каналов и каналов управления DataTable tblInCnl = new DataTable("InCnl"); DataTable tblCtrlCnl = new DataTable("CtrlCnl"); Tables.FillTableSchema(tblInCnl); Tables.FillTableSchema(tblCtrlCnl); // получение таблицы форматов чисел DataTable tblFormat = Tables.GetFormatTable(); tblFormat.DefaultView.Sort = "ShowNumber, DecDigits"; // создание каналов для КП foreach (KPParams kpParams in kpParamsList) { if (kpParams.Selected) { int inCnlNum = kpParams.FirstInCnlNum; int ctrlCnlNum = kpParams.FirstCtrlCnlNum; foreach (KPView.InCnlProps inCnlProps in kpParams.KPView.DefaultCnls) { KPView.CtrlCnlProps ctrlCnlProps = inCnlProps.CtrlCnlProps; object lastCtrlCnlNum; if (ctrlCnlProps == null) { lastCtrlCnlNum = DBNull.Value; } else { // создание канала управления DataRow newCtrlCnlRow = tblCtrlCnl.NewRow(); newCtrlCnlRow["CtrlCnlNum"] = ctrlCnlNum; newCtrlCnlRow["Active"] = true; newCtrlCnlRow["Name"] = ctrlCnlProps.Name; newCtrlCnlRow["CmdTypeID"] = (int)ctrlCnlProps.CmdType; newCtrlCnlRow["ObjNum"] = kpParams.ObjNum; newCtrlCnlRow["KPNum"] = kpParams.KPNum; newCtrlCnlRow["CmdNum"] = ctrlCnlProps.CmdNum; newCtrlCnlRow["CmdValID"] = ctrlCnlProps.CmdValName == "" ? DBNull.Value : (object)cmdValList[ctrlCnlProps.CmdValName]; newCtrlCnlRow["FormulaUsed"] = ctrlCnlProps.FormulaUsed; newCtrlCnlRow["Formula"] = ctrlCnlProps.Formula; newCtrlCnlRow["EvEnabled"] = ctrlCnlProps.EvEnabled; newCtrlCnlRow["ModifiedDT"] = DateTime.Now; tblCtrlCnl.Rows.Add(newCtrlCnlRow); lastCtrlCnlNum = ctrlCnlNum; ctrlCnlNum++; } // создание входного канала DataRow newInCnlRow = tblInCnl.NewRow(); newInCnlRow["CnlNum"] = inCnlNum; newInCnlRow["Active"] = true; newInCnlRow["CnlNum"] = inCnlNum; newInCnlRow["Name"] = inCnlProps.Name; newInCnlRow["CnlTypeID"] = (int)inCnlProps.CnlType; newInCnlRow["ModifiedDT"] = DateTime.Now; newInCnlRow["ObjNum"] = kpParams.ObjNum; newInCnlRow["KPNum"] = kpParams.KPNum; newInCnlRow["Signal"] = inCnlProps.Signal; newInCnlRow["FormulaUsed"] = inCnlProps.FormulaUsed; newInCnlRow["Formula"] = inCnlProps.Formula; newInCnlRow["Averaging"] = inCnlProps.Averaging; newInCnlRow["ParamID"] = inCnlProps.ParamName == "" ? DBNull.Value : (object)paramList[inCnlProps.ParamName]; newInCnlRow["FormatID"] = DBNull.Value; if (inCnlProps.ShowNumber) { int ind = tblFormat.DefaultView.Find(new object[] { true, inCnlProps.DecDigits }); if (ind >= 0) { newInCnlRow["FormatID"] = tblFormat.DefaultView[ind]["FormatID"]; } else { writer.WriteLine(string.Format( AppPhrases.NumFormatNotFound, inCnlNum, inCnlProps.DecDigits)); } } else { int ind = tblFormat.DefaultView.Find(new object[] { false, DBNull.Value }); if (ind >= 0) { newInCnlRow["FormatID"] = tblFormat.DefaultView[ind]["FormatID"]; } else { writer.WriteLine(string.Format(AppPhrases.TextFormatNotFound, inCnlNum)); } } newInCnlRow["UnitID"] = inCnlProps.UnitName == "" ? DBNull.Value : (object)unitList[inCnlProps.UnitName]; newInCnlRow["CtrlCnlNum"] = lastCtrlCnlNum; newInCnlRow["EvEnabled"] = inCnlProps.EvEnabled; newInCnlRow["EvSound"] = inCnlProps.EvSound; newInCnlRow["EvOnChange"] = inCnlProps.EvOnChange; newInCnlRow["EvOnUndef"] = inCnlProps.EvOnUndef; newInCnlRow["LimLowCrash"] = double.IsNaN(inCnlProps.LimLowCrash) ? DBNull.Value : (object)inCnlProps.LimLowCrash; newInCnlRow["LimLow"] = double.IsNaN(inCnlProps.LimLow) ? DBNull.Value : (object)inCnlProps.LimLow; newInCnlRow["LimHigh"] = double.IsNaN(inCnlProps.LimHigh) ? DBNull.Value : (object)inCnlProps.LimHigh; newInCnlRow["LimHighCrash"] = double.IsNaN(inCnlProps.LimHighCrash) ? DBNull.Value : (object)inCnlProps.LimHighCrash; tblInCnl.Rows.Add(newInCnlRow); inCnlNum++; } } } // сохранение каналов в БД bool updateOk = UpdateCnls(tblCtrlCnl, AppPhrases.AddedCtrlCnlsCount); updateOk = UpdateCnls(tblInCnl, AppPhrases.AddedInCnlsCount) && updateOk; string msg = updateOk ? AppPhrases.CreateCnlsComplSucc : AppPhrases.CreateCnlsComplWithErr; writer.WriteLine(); writer.WriteLine(msg); if (updateOk) { ScadaUtils.ShowInfo(msg + AppPhrases.RefreshRequired); } else { AppData.ErrLog.WriteAction(msg, Log.ActTypes.Error); ScadaUtils.ShowError(msg + AppPhrases.RefreshRequired); } } } catch (Exception ex) { string errMsg = AppPhrases.CreateCnlsError + ":\r\n" + ex.Message; try { writer.WriteLine(errMsg); } catch { } AppUtils.ProcError(errMsg); } finally { try { writer.Close(); } catch { } } if (logCreated) { Process.Start(logFileName); } }
private void btnImport_Click(object sender, EventArgs e) { // импорт выбранной таблицы из формата DAT StreamWriter writer = null; bool writeLog = chkImportLog.Checked; bool logCreated = false; string logFileName = AppData.ExeDir + "ScadaAdminImport.txt"; try { Tables.TableInfo tableInfo = cbTable.SelectedItem as Tables.TableInfo; if (tableInfo != null && AppData.Connected) { string fileName = txtFileName.Text.Trim(); if (writeLog) { writer = new StreamWriter(logFileName, false, Encoding.Default); logCreated = true; string title = DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle; writer.WriteLine(title); writer.WriteLine(new string('-', title.Length)); writer.WriteLine(AppPhrases.ImportTable + tableInfo.Name + " (" + tableInfo.Header + ")"); writer.WriteLine(AppPhrases.ImportFile + fileName); writer.WriteLine(); } // загрузка импортируемой таблицы BaseAdapter baseAdapter = new BaseAdapter(); DataTable srcTable = new DataTable(); baseAdapter.FileName = fileName; try { baseAdapter.Fill(srcTable, true); } catch (Exception ex) { throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message); } if (writeLog) { writer.WriteLine(AppPhrases.SrcTableFields); writer.WriteLine(new string('-', AppPhrases.SrcTableFields.Length)); if (srcTable.Columns.Count > 0) { foreach (DataColumn column in srcTable.Columns) { writer.WriteLine(column.ColumnName + " (" + column.DataType + ")"); } } else { writer.WriteLine(AppPhrases.NoFields); } writer.WriteLine(); } // определение схемы таблицы БД DataTable destTable = new DataTable(tableInfo.Name); Tables.FillTableSchema(destTable); if (writeLog) { writer.WriteLine(AppPhrases.DestTableFields); writer.WriteLine(new string('-', AppPhrases.DestTableFields.Length)); if (destTable.Columns.Count > 0) { foreach (DataColumn column in destTable.Columns) { writer.WriteLine(column.ColumnName + " (" + column.DataType + ")"); } } else { writer.WriteLine(AppPhrases.NoFields); } writer.WriteLine(); } // установка контроля идентификаторов string firstColumnName = destTable.Columns.Count > 0 ? destTable.Columns[0].ColumnName : ""; bool firstColumnIsID = gbIDs.Enabled && (firstColumnName.EndsWith("ID") || firstColumnName.EndsWith("Num") || firstColumnName == "CnlStatus") && destTable.Columns[0].DataType == typeof(int); bool checkMinID = chkStartID.Checked && firstColumnIsID; bool checkMaxID = chkFinalID.Checked && firstColumnIsID; bool shiftID = chkNewStartID.Checked && firstColumnIsID; bool shiftDef = false; // смещение определено bool checkID = checkMaxID || checkMinID || shiftID; int minID = checkMinID ? Convert.ToInt32(numStartID.Value) : 0; int maxID = checkMaxID ? Convert.ToInt32(numFinalID.Value) : 0; int newStartID = shiftID ? Convert.ToInt32(numNewStartID.Value) : 0; int shift = 0; // заполнение таблицы БД foreach (DataRow row in srcTable.Rows) { DataRow newRow = destTable.NewRow(); bool rowIsOk = true; foreach (DataColumn column in destTable.Columns) { int ind = srcTable.Columns.IndexOf(column.ColumnName); if (ind >= 0 && column.DataType == srcTable.Columns[ind].DataType) { object val = row[ind]; if (ind == 0 && checkID && val != null && val != DBNull.Value) { // проверка идентификатора int id = (int)val; if (checkMinID && id < minID || checkMaxID && id > maxID) { rowIsOk = false; break; } if (shiftID && !shiftDef) { shift = newStartID - id; shiftDef = true; } newRow[column] = id + shift; } else { newRow[column] = val; } } } if (rowIsOk) { destTable.Rows.Add(newRow); } } // сохранение информации в БД int updRows = 0; int errRows = 0; DataRow[] rowsInError = null; try { SqlCeDataAdapter sqlAdapter = destTable.ExtendedProperties["DataAdapter"] as SqlCeDataAdapter; updRows = sqlAdapter.Update(destTable); } catch (Exception ex) { throw new Exception(AppPhrases.WriteDBError + ":\r\n" + ex.Message); } if (destTable.HasErrors) { rowsInError = destTable.GetErrors(); errRows = rowsInError.Length; } string msg; if (errRows == 0) { msg = string.Format(AppPhrases.ImportCompleted, updRows); ScadaUtils.ShowInfo(updRows > 0 ? msg + AppPhrases.RefreshRequired : msg); } else { msg = string.Format(AppPhrases.ImportCompletedWithErr, updRows, errRows); AppData.ErrLog.WriteAction(msg, Log.ActTypes.Error); ScadaUtils.ShowError(updRows > 0 ? msg + AppPhrases.RefreshRequired : msg); } if (writeLog) { writer.WriteLine(AppPhrases.ImportResult); writer.WriteLine(new string('-', AppPhrases.ImportResult.Length)); writer.WriteLine(msg); if (errRows > 0) { writer.WriteLine(); writer.WriteLine(AppPhrases.ImportErrors); writer.WriteLine(new string('-', AppPhrases.ImportErrors.Length)); foreach (DataRow row in rowsInError) { if (firstColumnIsID) { object objVal = row[0]; string strVal = objVal == null || objVal == DBNull.Value ? "NULL" : objVal.ToString(); writer.Write(firstColumnName + " = " + strVal + " : "); } writer.WriteLine(row.RowError); } } } } } catch (Exception ex) { string errMsg = AppPhrases.ImportError + ":\r\n" + ex.Message; try { if (writeLog) { writer.WriteLine(errMsg); } } catch { } AppUtils.ProcError(errMsg); } finally { try { writer.Close(); } catch { } } if (writeLog && logCreated) { Process.Start(logFileName); } }
private void btnClone_Click(object sender, EventArgs e) { // получение типа клонируемых данных bool cloneInCnls = rbInCnls.Checked; try { // получение клонируемых каналов string fieldName = cloneInCnls ? "CnlNum" : "CtrlCnlNum"; DataTable table = cloneInCnls ? Tables.GetInCnlTable() : Tables.GetCtrlCnlTable(); table.DefaultView.RowFilter = numStartNum.Text + " <= " + fieldName + " and " + fieldName + " <= " + numFinalNum.Text; List <DataRow> rows = new List <DataRow>(); // клонируемые строки for (int i = 0; i < table.DefaultView.Count; i++) { rows.Add(table.DefaultView[i].Row); } // клонирование int shift = Convert.ToInt32(numNewStartNum.Value - numStartNum.Value); object newObjNum = cbObj.SelectedValue; object newKPNum = cbKP.SelectedValue; bool objNumChanged = newObjNum == DBNull.Value || (int)newObjNum > 0; bool kpNumChanged = newKPNum == DBNull.Value || (int)newKPNum > 0; foreach (DataRow row in rows) { DataRow newRow = table.NewRow(); newRow.ItemArray = row.ItemArray; newRow[0] = (int)newRow[0] + shift; if (objNumChanged) { newRow["ObjNum"] = newObjNum; } if (kpNumChanged) { newRow["KPNum"] = newKPNum; } table.Rows.Add(newRow); } // сохранение информации в БД int updRows = 0; try { SqlCeDataAdapter adapter = table.ExtendedProperties["DataAdapter"] as SqlCeDataAdapter; adapter.ContinueUpdateOnError = false; updRows = adapter.Update(table); string infoMsg = (cloneInCnls ? AppPhrases.CloneInCnlsCompleted : AppPhrases.CloneCtrlCnlsCompleted) + "\r\n" + string.Format(AppPhrases.AddedCnlsCount, updRows); ScadaUtils.ShowInfo(updRows > 0 ? infoMsg + AppPhrases.RefreshRequired : infoMsg); } catch (Exception ex) { // определение номера канала, на котором произошла ошибка int cnlNum = -1; if (table != null && table.HasErrors) { try { cnlNum = (int)table.GetErrors()[0][fieldName] - shift; } catch { } } // формирование и вывод сообщения об ошибке string errMsg = (cloneInCnls ? AppPhrases.CloneInCnlsError : AppPhrases.CloneCtrlCnlsError) + ".\r\n" + string.Format(AppPhrases.AddedCnlsCount, updRows) + "\r\n" + (cnlNum < 0 ? CommonPhrases.ErrorWithColon : string.Format(AppPhrases.CloneCnlError, cnlNum)) + "\r\n" + Tables.TranlateErrorMessage(ex.Message, table); AppData.ErrLog.WriteAction(errMsg, Log.ActTypes.Exception); ScadaUtils.ShowError(updRows > 0 ? errMsg + AppPhrases.RefreshRequired : errMsg); } } catch (Exception ex) { AppUtils.ProcError((cloneInCnls ? AppPhrases.CloneInCnlsError : AppPhrases.CloneCtrlCnlsError) + ":\r\n" + ex.Message); } }
private void btnReplaceAll_Click(object sender, EventArgs e) { // замена всех значений ColumnInfo columnInfo = cbTableColumn.SelectedItem as ColumnInfo; if (frmTable != null && columnInfo != null) { // список строк, в которых выполнена замена List <DataRowView> replacedRows = new List <DataRowView>(); int cnt = 0; bool matchCell = true; bool updated; bool found; do { // замена bool replaced = ReplaceCellVal(columnInfo, matchCell, out updated); matchCell = false; if (replaced && updated) { cnt++; } // сохранить строку с заменённым значением DataGridViewCell curCell = gridView.CurrentCell; if (replaced) { if (curCell != null) { int rowInd = curCell.RowIndex; if (0 <= rowInd && rowInd < frmTable.Table.DefaultView.Count) { replacedRows.Add(frmTable.Table.DefaultView[rowInd]); } } } // поиск следующего заменяемого значения if (updated) { do { found = FindNext(columnInfo, false); if (found) { // проверка, что значение в найденной строке ещё не заменялось DataRowView rowView = null; if (gridView.CurrentCell != null) { int rowInd = gridView.CurrentCell.RowIndex; if (0 <= rowInd && rowInd < frmTable.Table.DefaultView.Count) { rowView = frmTable.Table.DefaultView[rowInd]; } } if (replacedRows.Contains(rowView)) { found = false; } } }while (curCell != gridView.CurrentCell && !found); } else { found = false; } }while (found); if (cnt > 0) { ScadaUtils.ShowInfo(string.Format(AppPhrases.ReplaceCount, cnt)); } else if (updated) { ScadaUtils.ShowInfo(completeMsg); } } }
/// <summary> /// Импорт линий связи и КП /// </summary> public static DialogResult Import(DataTable tblCommLine, DataTable tblKP, Log errLog, out FrmImport frmImport) { frmImport = null; try { if (tblCommLine.DefaultView.Count == 0) { ScadaUtils.ShowInfo(AppPhrases.NoImportData); return(DialogResult.Cancel); } else { // заполнение дерева импортируемых данных: линий связи и КП frmImport = new FrmImport(); TreeView treeView = frmImport.TreeView; try { treeView.BeginUpdate(); treeView.Nodes.Clear(); tblCommLine.DefaultView.Sort = "CommLineNum"; tblKP.DefaultView.Sort = "CommLineNum, KPNum"; int kpCnt = tblKP.DefaultView.Count; int kpInd = 0; foreach (DataRowView rowLine in tblCommLine.DefaultView) { int lineNum = (int)rowLine["CommLineNum"]; TreeNode nodeLine = new TreeNode(Settings.CommLine.GetCaption(lineNum, rowLine["Name"])); nodeLine.Tag = rowLine; treeView.Nodes.Add(nodeLine); DataRowView rowKP = kpInd < kpCnt ? tblKP.DefaultView[kpInd] : null; int kpLineNum = rowKP == null ? -1 : (int)rowKP["CommLineNum"]; while (0 <= kpLineNum && kpLineNum <= lineNum) { if (kpLineNum == lineNum) { TreeNode nodeKP = new TreeNode(Settings.KP.GetCaption((int)rowKP["KPNum"], rowKP["Name"])); nodeKP.Tag = rowKP; nodeLine.Nodes.Add(nodeKP); } kpInd++; rowKP = kpInd < kpCnt ? tblKP.DefaultView[kpInd] : null; kpLineNum = rowKP == null ? -1 : (int)rowKP["CommLineNum"]; } } } finally { treeView.EndUpdate(); } // отображение формы импорта return(frmImport.ShowDialog()); } } catch (Exception ex) { string errMsg = AppPhrases.PrepareImportFormError1 + ":\r\n" + ex.Message; errLog.WriteAction(errMsg); ScadaUtils.ShowError(errMsg); return(DialogResult.Abort); } }