private void FrmCloneCnls_Shown(object sender, EventArgs e) { // заполнение выпадающего списка объектов try { DataTable table = Tables.GetObjTable(); table.Rows.Add(-1, AppPhrases.NotReplace); table.Rows.Add(DBNull.Value, AppPhrases.Undefined); cbObj.DataSource = table; cbObj.DisplayMember = "Name"; cbObj.ValueMember = "ObjNum"; cbObj.SelectedValue = -1; } catch (Exception ex) { AppUtils.ProcError(AppPhrases.FillObjListError + ":\r\n" + ex.Message); } // заполнение выпадающего списка КП try { DataTable table = Tables.GetKPTable(); table.Rows.Add(-1, AppPhrases.NotReplace); table.Rows.Add(DBNull.Value, AppPhrases.Undefined); cbKP.DataSource = table; cbKP.DisplayMember = "Name"; cbKP.ValueMember = "KPNum"; cbKP.SelectedValue = -1; } catch (Exception ex) { AppUtils.ProcError(AppPhrases.FillKPListError + ":\r\n" + ex.Message); } }
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); ScadaUiUtils.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); ScadaUiUtils.ShowError(updRows > 0 ? errMsg + AppPhrases.RefreshRequired : errMsg); } } catch (Exception ex) { AppUtils.ProcError((cloneInCnls ? AppPhrases.CloneInCnlsError : AppPhrases.CloneCtrlCnlsError) + ":\r\n" + ex.Message); } }
/// <summary> /// Расчитать номера каналов /// </summary> private bool CalcCnls(out string errMsg) { bool hasChannels = false; bool hasErrors = false; errMsg = ""; try { // получение списка номеров существующих входных каналов if (inCnlNums == null) { inCnlNums = Tables.GetInCnlNums(); } int curInCnlInd = 0; int inCnlNumsCnt = inCnlNums.Count; // получение списка номеров существующих каналов управления if (ctrlCnlNums == null) { ctrlCnlNums = Tables.GetCtrlCnlNums(); } int curCtrlCnlInd = 0; int ctrlCnlNumsCnt = ctrlCnlNums.Count; // определение стартового входного канала int inCnlsStart = decimal.ToInt32(numInCnlsStart.Value); int inCnlsMultiple = decimal.ToInt32(numInCnlsMultiple.Value); int inCnlsShift = decimal.ToInt32(numInCnlsShift.Value); int inCnlsSpace = decimal.ToInt32(numInCnlsSpace.Value); int remainder = inCnlsStart % inCnlsMultiple; int curInCnlNum = remainder > 0 ? inCnlsStart - remainder : inCnlsStart; curInCnlNum += inCnlsShift; if (curInCnlNum < inCnlsStart) { curInCnlNum += inCnlsMultiple; } // определение стартового канала управления int ctrlCnlsStart = decimal.ToInt32(numCtrlCnlsStart.Value); int ctrlCnlsMultiple = decimal.ToInt32(numCtrlCnlsMultiple.Value); int ctrlCnlsShift = decimal.ToInt32(numCtrlCnlsShift.Value); int ctrlCnlsSpace = decimal.ToInt32(numCtrlCnlsSpace.Value); remainder = ctrlCnlsStart % ctrlCnlsMultiple; int curCtrlCnlNum = remainder > 0 ? ctrlCnlsStart - remainder : ctrlCnlsStart; curCtrlCnlNum += ctrlCnlsShift; if (curCtrlCnlNum < ctrlCnlsStart) { curCtrlCnlNum += ctrlCnlsMultiple; } // расчёт номеров каналов КП foreach (KPParams kpParams in kpParamsList) { if (kpParams.Selected) { // определение номеров входных каналов с учётом занятых существующими каналами номеров List <KPView.InCnlProps> defaultCnls = kpParams.KPView.DefaultCnls; int inCnlCnt = defaultCnls == null ? 0 : defaultCnls.Count; if (inCnlCnt > 0) { hasChannels = true; int firstInCnlNum; // номер первого входного канала КП int lastInCnlNum; // номер последнего входного канала КП int newInCnlInd; // новый индекс списка номеров входных каналов CalcFirstAndLastNums(curInCnlNum, curInCnlInd, inCnlNums, inCnlNumsCnt, inCnlCnt, inCnlsSpace, inCnlsMultiple, out firstInCnlNum, out lastInCnlNum, out newInCnlInd); if (lastInCnlNum > ushort.MaxValue) { hasErrors = true; kpParams.InCnlsError = true; kpParams.FirstInCnlNum = 0; kpParams.LastInCnlNum = 0; } else { kpParams.InCnlsError = false; kpParams.FirstInCnlNum = firstInCnlNum; kpParams.LastInCnlNum = lastInCnlNum; curInCnlInd = newInCnlInd; curInCnlNum = firstInCnlNum; do { curInCnlNum += inCnlsMultiple; }while (curInCnlNum - lastInCnlNum <= inCnlsSpace); } // определение номеров каналов управления с учётом занятых существующими каналами номеров int ctrlCnlCnt = kpParams.KPView.DefaultCtrlCnlCount; if (ctrlCnlCnt > 0) { int firstCtrlCnlNum; // номер первого канала управления КП int lastCtrlCnlNum; // номер последнего канала управления КП int newCtrlCnlInd; // новый индекс списка номеров каналов управления CalcFirstAndLastNums(curCtrlCnlNum, curCtrlCnlInd, ctrlCnlNums, ctrlCnlNumsCnt, ctrlCnlCnt, ctrlCnlsSpace, ctrlCnlsMultiple, out firstCtrlCnlNum, out lastCtrlCnlNum, out newCtrlCnlInd); if (lastCtrlCnlNum > ushort.MaxValue) { hasErrors = true; kpParams.CtrlCnlsError = true; kpParams.FirstCtrlCnlNum = 0; kpParams.LastCtrlCnlNum = 0; } else { kpParams.CtrlCnlsError = false; kpParams.FirstCtrlCnlNum = firstCtrlCnlNum; kpParams.LastCtrlCnlNum = lastCtrlCnlNum; curCtrlCnlInd = newCtrlCnlInd; curCtrlCnlNum = firstCtrlCnlNum; do { curCtrlCnlNum += ctrlCnlsMultiple; }while (curCtrlCnlNum - lastCtrlCnlNum <= ctrlCnlsSpace); } } } else { // номера каналов не назначаются, т.к. КП не поддерживает создание каналов kpParams.InCnlsError = false; kpParams.FirstInCnlNum = 0; kpParams.LastInCnlNum = 0; kpParams.CtrlCnlsError = false; kpParams.FirstCtrlCnlNum = 0; kpParams.LastCtrlCnlNum = 0; } // определение текста ячеек таблицы с номерами каналов kpParams.InCnls = kpParams.InCnlsError ? AppPhrases.DevCalcError : kpParams.FirstInCnlNum == 0 ? AppPhrases.DevHasNoCnls : kpParams.FirstInCnlNum == kpParams.LastInCnlNum ? kpParams.FirstInCnlNum.ToString() : kpParams.FirstInCnlNum.ToString() + " - " + kpParams.LastInCnlNum; kpParams.CtrlCnls = kpParams.CtrlCnlsError ? AppPhrases.DevCalcError : kpParams.FirstCtrlCnlNum == 0 ? AppPhrases.DevHasNoCnls : kpParams.FirstCtrlCnlNum == kpParams.LastCtrlCnlNum ? kpParams.FirstCtrlCnlNum.ToString() : kpParams.FirstCtrlCnlNum.ToString() + " - " + kpParams.LastCtrlCnlNum; } else { // номера каналов не назначаются, т.к. КП не выбран kpParams.InCnlsError = false; kpParams.FirstInCnlNum = 0; kpParams.LastInCnlNum = 0; kpParams.CtrlCnlsError = false; kpParams.FirstCtrlCnlNum = 0; kpParams.LastCtrlCnlNum = 0; kpParams.InCnls = ""; kpParams.CtrlCnls = ""; } } if (hasErrors) { errMsg = AppPhrases.CalcCnlNumsErrors; } else if (!hasChannels) { errMsg = AppPhrases.CreatedCnlsMissing; } btnCalc.Enabled = false; } catch (Exception ex) { hasErrors = true; AppUtils.ProcError(AppPhrases.CalcCnlNumsError + ":\r\n" + ex.Message); } return(hasChannels && !hasErrors); }
/// <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); } }
/// <summary> /// Заполнить таблицу КП /// </summary> private void FillKPGrid() { try { DataTable tblObj = Tables.GetObjTable(); tblObj.Rows.Add(DBNull.Value, AppPhrases.UndefinedItem); DataGridViewComboBoxColumn colObjNum = (DataGridViewComboBoxColumn)gvKPSel.Columns["colObjNum"]; colObjNum.DataSource = tblObj; colObjNum.DisplayMember = "Name"; colObjNum.ValueMember = "ObjNum"; DataTable tblKP = Tables.GetKPTable(); DataTable tblKPType = Tables.GetKPTypeTable(); foreach (DataRow rowKP in tblKP.Rows) { KPParams kpParams = new KPParams(); kpParams.KPNum = (int)rowKP["KPNum"]; kpParams.KPName = (string)rowKP["Name"]; kpParams.ObjNum = DBNull.Value; tblKPType.DefaultView.RowFilter = "KPTypeID = " + rowKP["KPTypeID"]; object dllFileName = tblKPType.DefaultView[0]["DllFileName"]; kpParams.DllFileName = dllFileName == null || dllFileName == DBNull.Value ? "" : (string)dllFileName; if (kpParams.DllFileName == "") { kpParams.Enabled = false; kpParams.Color = Color.Gray; kpParams.KPView = null; kpParams.Selected = false; kpParams.DllState = ""; } else { if (kpViewList.ContainsKey(kpParams.DllFileName)) { kpParams.KPView = kpViewList[kpParams.DllFileName]; if (kpParams.KPView == null) { kpParams.Enabled = false; kpParams.Color = Color.Red; kpParams.Selected = false; kpParams.DllState = AppPhrases.DllError; } else { kpParams.Enabled = true; kpParams.Color = Color.Black; kpParams.Selected = true; kpParams.DllState = AppPhrases.DllLoaded; } } else { kpParams.Enabled = false; kpParams.Color = Color.Gray; kpParams.KPView = null; kpParams.Selected = false; kpParams.DllState = AppPhrases.DllNotFound; } } kpParams.InCnlsError = false; kpParams.InCnls = ""; kpParams.CtrlCnlsError = false; kpParams.CtrlCnls = ""; kpParamsList.Add(kpParams); } gvKPSel.DataSource = kpParamsList; } catch (Exception ex) { AppUtils.ProcError(AppPhrases.FillKPGridError + ":\r\n" + ex.Message); } }
/// <summary> /// Импортировать таблицу /// </summary> private static void ImportTable(DataTable srcTable, Tables.TableInfo destTableInfo, int shiftID, StreamWriter writer, out int updRowCnt, out int errRowCnt, out string msg) { // определение режима импорта: только добавление строк или добавление/обновление string idColName = destTableInfo.IDColName; bool tryToUpdate = idColName != "" && srcTable.Columns.Contains(idColName); // получение таблицы, в которую производится импорт DataTable destTable; if (tryToUpdate) { // заполение столбцов и данных таблицы destTable = destTableInfo.GetTable(); } else { // заполение столбцов таблицы destTable = new DataTable(destTableInfo.Name); Tables.FillTableSchema(destTable); } // вывод заголовка и стобцов в журнал импорта if (writer != null) { writer.WriteLine(); AppUtils.WriteTitle(writer, string.Format(AppPhrases.ImportTableTitle, destTableInfo.Name + " (" + destTableInfo.Header + ")")); writer.WriteLine(); WriteColumns(writer, srcTable, AppPhrases.SrcTableColumns); WriteColumns(writer, destTable, AppPhrases.DestTableColumns); } // заполнение таблицы в формате SDF foreach (DataRowView srcRowView in srcTable.DefaultView) { DataRow srcRow = srcRowView.Row; DataRow destRow = null; if (tryToUpdate) { object curID = srcRow[idColName]; object newID = curID is int?(int)curID + shiftID : curID; int rowInd = destTable.DefaultView.Find(newID); // таблица отсортирована по ключу if (rowInd >= 0) { destRow = destTable.DefaultView[rowInd].Row; } } if (destRow == null) { destRow = destTable.NewRow(); destTable.Rows.Add(destRow); } foreach (DataColumn destColumn in destTable.Columns) { int ind = srcTable.Columns.IndexOf(destColumn.ColumnName); if (ind >= 0 && destColumn.DataType == srcTable.Columns[ind].DataType) { object val = srcRow[ind]; destRow[destColumn] = destColumn.ColumnName == idColName && shiftID > 0 ? (int)val /*ID*/ + shiftID : val; } } } // сохранение информации в базе конфигурации в формате SDF updRowCnt = 0; errRowCnt = 0; DataRow[] errRows = null; try { SqlCeDataAdapter sqlAdapter = destTable.ExtendedProperties["DataAdapter"] as SqlCeDataAdapter; updRowCnt = sqlAdapter.Update(destTable); } catch (Exception ex) { throw new Exception(AppPhrases.WriteDBError + ":\r\n" + ex.Message); } // обработка ошибок if (destTable.HasErrors) { errRows = destTable.GetErrors(); errRowCnt = errRows.Length; } msg = errRowCnt == 0 ? string.Format(AppPhrases.ImportTableCompleted, updRowCnt) : string.Format(AppPhrases.ImportTableCompletedWithErr, updRowCnt, errRowCnt); // вывод результата и ошибок в журнал импорта if (writer != null) { AppUtils.WriteTitle(writer, AppPhrases.ImportTableResult); writer.WriteLine(msg); if (errRowCnt > 0) { writer.WriteLine(); AppUtils.WriteTitle(writer, AppPhrases.ImportTableErrors); foreach (DataRow row in errRows) { if (idColName != "") { writer.Write(idColName + " = " + row[idColName] + " : "); } writer.WriteLine(row.RowError); } } } }
private void dataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e) { AppUtils.ProcError(CommonPhrases.GridDataError + ":\r\n" + e.Exception.Message); e.ThrowException = false; }
/// <summary> /// Импортировать все таблицы базы конфигурации из заданной директории /// </summary> public static bool ImportAllTables(string srcDir, List <Tables.TableInfo> destTableInfoList, string logFileName, out bool logCreated, out string msg) { // проверка аргументов метода if (srcDir == null) { throw new ArgumentNullException("srcDir"); } if (destTableInfoList == null) { throw new ArgumentNullException("destTableInfoList"); } if (logFileName == null) { throw new ArgumentNullException("logFileName"); } logCreated = false; StreamWriter writer = null; try { // создание журнала импорта и вывод параметров импорта writer = new StreamWriter(logFileName, false, Encoding.UTF8); logCreated = true; AppUtils.WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle); writer.WriteLine(AppPhrases.ImportSource + srcDir); // проверка существования импортируемой директории if (!Directory.Exists(srcDir)) { throw new DirectoryNotFoundException(AppPhrases.ImportDirNotExist); } // импорт таблиц, файлы которых существуют в заданной директории int totalUpdRowCnt = 0; int totalErrRowCnt = 0; int updRowCnt; int errRowCnt; srcDir = ScadaUtils.NormalDir(srcDir); foreach (Tables.TableInfo destTableInfo in destTableInfoList) { string srcFileName = srcDir + destTableInfo.FileName; if (File.Exists(srcFileName)) { // загрузка импортируемой таблицы в формате DAT BaseAdapter baseAdapter = new BaseAdapter(); DataTable srcTable = new DataTable(); baseAdapter.FileName = srcFileName; try { baseAdapter.Fill(srcTable, true); } catch (Exception ex) { throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message); } // импорт таблицы string s; ImportTable(srcTable, destTableInfo, 0, writer, out updRowCnt, out errRowCnt, out s); totalUpdRowCnt += updRowCnt; totalErrRowCnt += errRowCnt; } } msg = totalErrRowCnt == 0 ? string.Format(AppPhrases.ImportCompleted, totalUpdRowCnt) : string.Format(AppPhrases.ImportCompletedWithErr, totalUpdRowCnt, totalErrRowCnt); // вывод результата в журнал импорта writer.WriteLine(); AppUtils.WriteTitle(writer, AppPhrases.ImportResult); writer.WriteLine(msg); if (totalUpdRowCnt > 0) { msg += AppPhrases.RefreshRequired; } return(totalErrRowCnt == 0); } catch (Exception ex) { msg = AppPhrases.ImportAllTablesError + ":\r\n" + ex.Message; try { if (logCreated) { writer.WriteLine(msg); } } catch { } return(false); } finally { try { writer.Close(); } catch { } } }
/// <summary> /// Импортировать архив базы конфигурации (патч) /// </summary> public static bool ImportArchive(string srcFileName, List <Tables.TableInfo> destTableInfoList, string logFileName, out bool logCreated, out string msg) { // проверка аргументов метода if (srcFileName == null) { throw new ArgumentNullException("srcFileName"); } if (destTableInfoList == null) { throw new ArgumentNullException("destTableInfoList"); } if (logFileName == null) { throw new ArgumentNullException("logFileName"); } logCreated = false; StreamWriter writer = null; try { // создание журнала импорта и вывод параметров импорта writer = new StreamWriter(logFileName, false, Encoding.UTF8); logCreated = true; AppUtils.WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle); writer.WriteLine(AppPhrases.ImportSource + srcFileName); // проверка существования импортируемого файла if (!File.Exists(srcFileName)) { throw new FileNotFoundException(AppPhrases.ImportFileNotExist); } using (ZipFile zipFile = ZipFile.Read(srcFileName)) { // получение словаря всех файлов архива с именами в нижнем регистре Dictionary <string, ZipEntry> zipEntries = new Dictionary <string, ZipEntry>(zipFile.Count); foreach (ZipEntry zipEntry in zipFile) { string fileName = zipEntry.FileName.ToLowerInvariant(); if (fileName.StartsWith("basedat/", StringComparison.Ordinal) || fileName.StartsWith("basedat\\", StringComparison.Ordinal)) { fileName = fileName.Substring("basedat/".Length); zipEntries.Add(fileName, zipEntry); } } // импорт таблиц из тех, которые содержатся в архиве int totalUpdRowCnt = 0; int totalErrRowCnt = 0; int updRowCnt; int errRowCnt; foreach (Tables.TableInfo destTableInfo in destTableInfoList) { if (zipEntries.ContainsKey(destTableInfo.FileName)) { using (MemoryStream zipStream = new MemoryStream()) { // распаковка архива в поток в памяти ZipEntry zipEntry = zipEntries[destTableInfo.FileName]; zipEntry.Extract(zipStream); // загрузка импортируемой таблицы в формате DAT из потока BaseAdapter baseAdapter = new BaseAdapter(); DataTable srcTable = new DataTable(); baseAdapter.Stream = zipStream; baseAdapter.Stream.Position = 0; try { baseAdapter.Fill(srcTable, true); } catch (Exception ex) { throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message); } // импорт таблицы string s; ImportTable(srcTable, destTableInfo, 0, writer, out updRowCnt, out errRowCnt, out s); totalUpdRowCnt += updRowCnt; totalErrRowCnt += errRowCnt; } } } msg = totalErrRowCnt == 0 ? string.Format(AppPhrases.ImportCompleted, totalUpdRowCnt) : string.Format(AppPhrases.ImportCompletedWithErr, totalUpdRowCnt, totalErrRowCnt); // вывод результата в журнал импорта writer.WriteLine(); AppUtils.WriteTitle(writer, AppPhrases.ImportResult); writer.WriteLine(msg); if (totalUpdRowCnt > 0) { msg += AppPhrases.RefreshRequired; } return(totalErrRowCnt == 0); } } catch (Exception ex) { msg = AppPhrases.ImportArchiveError + ":\r\n" + ex.Message; try { if (logCreated) { writer.WriteLine(msg); } } catch { } return(false); } finally { try { writer.Close(); } catch { } } }
/// <summary> /// Импортировать таблицу базы конфигурации из файла формата DAT /// </summary> public static bool ImportTable(string srcFileName, Tables.TableInfo destTableInfo, int minID, int maxID, int newMinID, string logFileName, out bool logCreated, out string msg) { // проверка аргументов метода if (srcFileName == null) { throw new ArgumentNullException("srcFileName"); } if (destTableInfo == null) { throw new ArgumentNullException("destTableInfo"); } if (logFileName == null) { throw new ArgumentNullException("logFileName"); } logCreated = false; StreamWriter writer = null; try { // создание журнала импорта и вывод параметров импорта writer = new StreamWriter(logFileName, false, Encoding.UTF8); logCreated = true; AppUtils.WriteTitle(writer, DateTime.Now.ToString("G", Localization.Culture) + " " + AppPhrases.ImportTitle); writer.WriteLine(AppPhrases.ImportSource + srcFileName); // проверка существования импортируемого файла if (!File.Exists(srcFileName)) { throw new FileNotFoundException(AppPhrases.ImportFileNotExist); } // загрузка импортируемой таблицы в формате DAT BaseAdapter baseAdapter = new BaseAdapter(); DataTable srcTable = new DataTable(); baseAdapter.FileName = srcFileName; try { baseAdapter.Fill(srcTable, true); } catch (Exception ex) { throw new Exception(AppPhrases.LoadTableError + ":\r\n" + ex.Message); } // ограничение диапазона идентификаторов string idColName = destTableInfo.IDColName; if ((0 < minID || maxID < int.MaxValue) && idColName != "") { srcTable.DefaultView.RowFilter = string.Format("{0} <= {2} and {2} <= {1}", minID, maxID, idColName); } int shiftID = newMinID > 0 ? newMinID - minID : 0; // импорт таблицы int updRowCnt; int errRowCnt; ImportTable(srcTable, destTableInfo, shiftID, writer, out updRowCnt, out errRowCnt, out msg); if (updRowCnt > 0) { msg += AppPhrases.RefreshRequired; } return(errRowCnt == 0); } catch (Exception ex) { msg = AppPhrases.ImportTableError + ":\r\n" + ex.Message; try { if (logCreated) { writer.WriteLine(msg); } } catch { } return(false); } finally { try { writer.Close(); } catch { } } }
private void btnClone_Click(object sender, EventArgs e) { // getting the type of data being cloned bool cloneInCnls = rbInCnls.Checked; try { // getting cloned channels string fieldName = cloneInCnls ? "CnlNum" : "CtrlCnlNum"; var table = cloneInCnls ? Tables.GetInCnlTable() : Tables.GetCtrlCnlTable(); table.DefaultView.RowFilter = numStartNum.Text + " <= " + fieldName + " and " + fieldName + " <= " + numFinalNum.Text; var rows = new List <DataRow>(); // cloning strings for (var i = 0; i < table.DefaultView.Count; i++) { rows.Add(table.DefaultView[i].Row); } // cloning int shift = Convert.ToInt32(numNewStartNum.Value - numStartNum.Value); var newObjNum = cbObj.SelectedValue; var newKPNum = cbKP.SelectedValue; bool objNumChanged = newObjNum == DBNull.Value || (int)newObjNum > 0; bool kpNumChanged = newKPNum == DBNull.Value || (int)newKPNum > 0; foreach (var row in rows) { var 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); } // storing information in the database var updRows = 0; try { var 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); ScadaUiUtils.ShowInfo(updRows > 0 ? infoMsg + AppPhrases.RefreshRequired : infoMsg); } catch (Exception ex) { // determining the number of the channel on which the error occurred int cnlNum = -1; if (table.HasErrors) { try { cnlNum = (int)table.GetErrors()[0][fieldName] - shift; } catch { // ignored } } // generating and displaying an error message 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.TranslateErrorMessage(ex.Message, table); AppData.ErrLog.WriteAction(errMsg, Log.ActTypes.Exception); ScadaUiUtils.ShowError(updRows > 0 ? errMsg + AppPhrases.RefreshRequired : errMsg); } } catch (Exception ex) { AppUtils.ProcError((cloneInCnls ? AppPhrases.CloneInCnlsError : AppPhrases.CloneCtrlCnlsError) + ":\r\n" + ex.Message); } }
private void btnCreate_Click(object sender, EventArgs e) { // создание карты каналов bool useInCnls = rbInCnls.Checked; bool groupByObj = rbGroupByObj.Checked; StreamWriter writer = null; bool mapCreated = false; string mapFileName = AppData.ExeDir + "ScadaAdminCnlMap.txt"; try { writer = new StreamWriter(mapFileName, false, Encoding.UTF8); mapCreated = true; string title = DateTime.Now.ToString("G", Localization.Culture) + " " + (useInCnls ? (groupByObj ? AppPhrases.InCnlsByObjTitle : AppPhrases.InCnlsByKPTitle) : (groupByObj ? AppPhrases.CtrlCnlsByObjTitle : AppPhrases.CtrlCnlsByKPTitle)); writer.WriteLine(title); writer.WriteLine(new string('-', title.Length)); // получение таблицы элементов, по которым выполняется группировка DataTable tblItems = groupByObj ? Tables.GetObjTable() : Tables.GetKPTable(); string itemNameFormat = groupByObj ? AppPhrases.ObjectCaptionFormat : AppPhrases.KPCaptionFormat; // определение метода получения каналов GetCnlTableByItemNumDelegate getCnlTable = useInCnls ? (groupByObj ? new GetCnlTableByItemNumDelegate(Tables.GetInCnlTableByObjNum) : new GetCnlTableByItemNumDelegate(Tables.GetInCnlTableByKPNum)) : (groupByObj ? new GetCnlTableByItemNumDelegate(Tables.GetCtrlCnlTableByObjNum) : new GetCnlTableByItemNumDelegate(Tables.GetCtrlCnlTableByKPNum)); // формирование карты каналов foreach (DataRowView itemRowView in tblItems.DefaultView) { int itemNum = (int)itemRowView[0]; writer.WriteLine(string.Format(itemNameFormat, itemNum, itemRowView[1])); writer.WriteLine(MakeCnlsLine(getCnlTable(itemNum))); writer.WriteLine(); } if (groupByObj) { writer.WriteLine(AppPhrases.UndefinedObject); } else { writer.WriteLine(AppPhrases.UndefinedKP); } DataTable tblCnls = getCnlTable(0); if (tblItems.DefaultView.Count > 0 || tblCnls.DefaultView.Count > 0) { writer.WriteLine(MakeCnlsLine(tblCnls)); } else { writer.WriteLine(AppPhrases.NoChannels); } } catch (Exception ex) { string errMsg = AppPhrases.CreateCnlMapError + ":\r\n" + ex.Message; try { writer.WriteLine(errMsg); } catch { } AppUtils.ProcError(errMsg); } finally { try { writer.Close(); } catch { } } if (mapCreated) { Process.Start(mapFileName); } }
/// <summary> /// Perform an action associated with a tree node /// </summary> private void ExecNodeAction(TreeNode node) { var nodeInfo = node.Tag as NodeInfo; if (nodeInfo != null) { if (nodeInfo.Form == null) { FrmTable frmTable = null; var imageKey = "table.gif"; try { int param = -1; object[] paramArr = nodeInfo.Params; if (paramArr != null && paramArr.Length > 0 && paramArr[0] is int) { param = (int)paramArr[0]; } string nodeText = node.Text; switch (nodeInfo.NodeAction) { case NodeActions.Obj: frmTable = NewTableForm(nodeText, Tables.GetObjTable()); break; case NodeActions.CommLine: frmTable = NewTableForm(nodeText, Tables.GetCommLineTable()); break; case NodeActions.KP: frmTable = NewTableForm(nodeText, Tables.GetKPTable()); break; case NodeActions.InCnl: frmTable = NewTableForm(nodeText, Tables.GetInCnlTable()); frmTable.GridContextMenu = contextInCnls; break; case NodeActions.InCnlObj: frmTable = NewTableForm(CommonPhrases.InCnlTable + " - " + nodeText, Tables.GetInCnlTableByObjNum(param)); frmTable.GridContextMenu = contextInCnls; imageKey = "object.gif"; break; case NodeActions.InCnlKP: frmTable = NewTableForm(CommonPhrases.InCnlTable + " - " + nodeText, Tables.GetInCnlTableByKPNum(param)); frmTable.GridContextMenu = contextInCnls; imageKey = "kp.gif"; break; case NodeActions.CtrlCnl: frmTable = NewTableForm(nodeText, Tables.GetCtrlCnlTable()); break; case NodeActions.CtrlCnlObj: frmTable = NewTableForm(CommonPhrases.CtrlCnlTable + " - " + nodeText, Tables.GetCtrlCnlTableByObjNum(param)); imageKey = "object.gif"; break; case NodeActions.CtrlCnlKP: frmTable = NewTableForm(CommonPhrases.CtrlCnlTable + " - " + nodeText, Tables.GetCtrlCnlTableByKPNum(param)); imageKey = "kp.gif"; break; case NodeActions.Role: frmTable = NewTableForm(nodeText, Tables.GetRoleTable()); break; case NodeActions.User: frmTable = NewTableForm(nodeText, Tables.GetUserTable()); break; case NodeActions.Interface: frmTable = NewTableForm(nodeText, Tables.GetInterfaceTable()); break; case NodeActions.Right: frmTable = NewTableForm(nodeText, Tables.GetRightTable()); break; case NodeActions.CnlType: frmTable = NewTableForm(nodeText, Tables.GetCnlTypeTable()); break; case NodeActions.CmdType: frmTable = NewTableForm(nodeText, Tables.GetCmdTypeTable()); break; case NodeActions.EvType: frmTable = NewTableForm(nodeText, Tables.GetEvTypeTable()); break; case NodeActions.KPType: frmTable = NewTableForm(nodeText, Tables.GetKPTypeTable()); break; case NodeActions.Param: frmTable = NewTableForm(nodeText, Tables.GetParamTable()); break; case NodeActions.Unit: frmTable = NewTableForm(nodeText, Tables.GetUnitTable()); break; case NodeActions.CmdVal: frmTable = NewTableForm(nodeText, Tables.GetCmdValTable()); break; case NodeActions.Format: frmTable = NewTableForm(nodeText, Tables.GetFormatTable()); break; case NodeActions.Formula: frmTable = NewTableForm(nodeText, Tables.GetFormulaTable()); break; } } catch (Exception ex) { AppUtils.ProcError(ex.Message); frmTable = null; } if (frmTable != null) { frmTable.FormClosed += ChildFormClosed; nodeInfo.Form = frmTable; winControl.AddForm(frmTable, "", ilTree.Images[imageKey], node); } } else { winControl.ActivateForm(nodeInfo.Form); } SetItemsEnabledOnWindowAction(); } }
private void btnOk_Click(object sender, EventArgs e) { // validation of entered data var errors = new StringBuilder(); string errMsg; if (!AppUtils.ValidateInt(txtCnlNum.Text, 1, ushort.MaxValue, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectInCnlNum).AppendLine(errMsg); } if (txtName.Text == "") { errors.AppendLine(AppPhrases.IncorrectInCnlName).AppendLine(CommonPhrases.NonemptyRequired); } if (cbCnlType.SelectedValue == null) { errors.AppendLine(AppPhrases.IncorrectCnlType).AppendLine(CommonPhrases.NonemptyRequired); } if (txtSignal.Text != "" && !AppUtils.ValidateInt(txtSignal.Text, 1, int.MaxValue, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectSignal).AppendLine(errMsg); } string ctrlCnlNum = txtCtrlCnlNum.Text; if (ctrlCnlNum != "") { if (AppUtils.ValidateInt(ctrlCnlNum, 1, ushort.MaxValue, out errMsg)) { if (Tables.GetCtrlCnlName(int.Parse(ctrlCnlNum)) == "") { errors.AppendLine(AppPhrases.IncorrectCtrlCnlNum) .AppendLine(string.Format(AppPhrases.CtrlCnlNotExists, ctrlCnlNum)); } } else { errors.AppendLine(AppPhrases.IncorrectCtrlCnlNum).AppendLine(errMsg); } } if (txtLimLowCrash.Text != "" && !AppUtils.ValidateDouble(txtLimLowCrash.Text, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectLimLowCrash).AppendLine(errMsg); } if (txtLimLow.Text != "" && !AppUtils.ValidateDouble(txtLimLow.Text, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectLimLow).AppendLine(errMsg); } if (txtLimHigh.Text != "" && !AppUtils.ValidateDouble(txtLimHigh.Text, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectLimHigh).AppendLine(errMsg); } if (txtLimHighCrash.Text != "" && !AppUtils.ValidateDouble(txtLimHighCrash.Text, out errMsg)) { errors.AppendLine(AppPhrases.IncorrectLimHighCrash).AppendLine(errMsg); } errMsg = errors.ToString().TrimEnd(); if (errMsg == "") { // passing input channel properties to an editable table try { var dataRow = frmTable.Table.DefaultView[row.Index]; dataRow["Active"] = chkActive.Checked; dataRow["CnlNum"] = txtCnlNum.Text; dataRow["Name"] = txtName.Text; dataRow["CnlTypeID"] = cbCnlType.SelectedValue; dataRow["ModifiedDT"] = DateTime.Now; dataRow["ObjNum"] = cbObj.SelectedValue; dataRow["KPNum"] = cbKP.SelectedValue; dataRow["Signal"] = txtSignal.Text == "" ? DBNull.Value : (object)txtSignal.Text; dataRow["FormulaUsed"] = chkFormulaUsed.Checked; dataRow["Formula"] = txtFormula.Text == "" ? DBNull.Value : (object)txtFormula.Text; dataRow["Averaging"] = chkAveraging.Checked; dataRow["ParamID"] = cbParam.SelectedValue; dataRow["FormatID"] = cbFormat.SelectedValue; dataRow["UnitID"] = cbUnit.SelectedValue; dataRow["CtrlCnlNum"] = txtCtrlCnlNum.Text == "" ? DBNull.Value : (object)txtCtrlCnlNum.Text; dataRow["EvEnabled"] = chkEvEnabled.Checked; dataRow["EvSound"] = chkEvSound.Checked; dataRow["EvOnChange"] = chkEvOnChange.Checked; dataRow["EvOnUndef"] = chkEvOnUndef.Checked; dataRow["LimLowCrash"] = txtLimLowCrash.Text == "" ? DBNull.Value : (object)txtLimLowCrash.Text; dataRow["LimLow"] = txtLimLow.Text == "" ? DBNull.Value : (object)txtLimLow.Text; dataRow["LimHigh"] = txtLimHigh.Text == "" ? DBNull.Value : (object)txtLimHigh.Text; dataRow["LimHighCrash"] = txtLimHighCrash.Text == "" ? DBNull.Value : (object)txtLimHighCrash.Text; DialogResult = DialogResult.OK; } catch (Exception ex) { AppUtils.ProcError(AppPhrases.WriteInCnlPropsError + ":\r\n" + ex.Message); DialogResult = DialogResult.Cancel; } } else { ScadaUiUtils.ShowError(errMsg); } }
/// <summary> /// Group channels by creating the corresponding nodes in the explorer tree /// </summary> private void GroupCnls() { try { treeView.BeginUpdate(); nodInCnl.Nodes.Clear(); nodCtrlCnl.Nodes.Clear(); DataTable table; TreeNode node, clone; NodeInfo info; if (miViewGroupByObj.Checked) { // creating object nodes table = Tables.GetObjTable(); foreach (DataRow row in table.Rows) { var objID = (int)row["ObjNum"]; node = nodInCnl.Nodes.Add("InCnlObj" + objID, (string)row["Name"], "object.gif", "object.gif"); info = new NodeInfo(NodeActions.InCnlObj) { Params = new object[] { objID } }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeActions.CtrlCnlObj) { Params = new object[] { objID } }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } // creating a node with an undefined object node = nodInCnl.Nodes.Add("InCnlObjNull", AppPhrases.UndefObj, "object.gif", "object.gif"); info = new NodeInfo(NodeActions.InCnlObj) { Params = new object[] { null } }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeActions.CtrlCnlObj) { Params = new object[] { null } }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } else // miViewGroupKP.Checked { table = Tables.GetKPTable(); foreach (DataRow row in table.Rows) { var kpID = (int)row["KPNum"]; node = nodInCnl.Nodes.Add("InCnlKP" + kpID, (string)row["Name"], "kp.gif", "kp.gif"); info = new NodeInfo(NodeActions.InCnlKP) { Params = new object[] { kpID } }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeActions.CtrlCnlKP) { Params = new object[] { kpID } }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } // creating a node with an undefined KP node = nodInCnl.Nodes.Add("InCnlKPNull", AppPhrases.UndefKP, "kp.gif", "kp.gif"); info = new NodeInfo(NodeActions.InCnlKP) { Params = new object[] { null } }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeActions.CtrlCnlKP) { Params = new object[] { null } }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.CnlGroupError + ":\r\n" + ex.Message); } finally { treeView.EndUpdate(); } }
/// <summary> /// Display Input Channel Properties /// </summary> public DialogResult ShowInCnlProps(FrmTable frmTable) { // getting editable table and row this.frmTable = frmTable; try { gridView = frmTable.GridView; row = gridView.Rows[gridView.CurrentCell.RowIndex]; } catch { gridView = null; row = null; } // display properties of the selected input channel try { if (row == null) { throw new Exception(CommonPhrases.NoData); } chkActive.Checked = ObjToBool(row.Cells["Active"].Value); txtModifiedDT.Text = row.Cells["ModifiedDT"].FormattedValue.ToString(); txtCnlNum.Text = row.Cells["CnlNum"].FormattedValue.ToString(); txtName.Text = row.Cells["Name"].FormattedValue.ToString(); SetComboBoxVal(cbCnlType, "CnlTypeID"); SetComboBoxVal(cbObj, "ObjNum"); if (cbObj.SelectedValue != null) { txtObjNum.Text = cbObj.SelectedValue.ToString(); } SetComboBoxVal(cbKP, "KPNum"); if (cbKP.SelectedValue != null) { txtKPNum.Text = cbKP.SelectedValue.ToString(); } txtSignal.Text = row.Cells["Signal"].FormattedValue.ToString(); chkFormulaUsed.Checked = ObjToBool(row.Cells["FormulaUsed"].Value); txtFormula.Text = row.Cells["Formula"].FormattedValue.ToString(); SetComboBoxVal(cbParam, "ParamID"); SetComboBoxVal(cbFormat, "FormatID"); SetComboBoxVal(cbUnit, "UnitID"); var numObj = row.Cells["CtrlCnlNum"].Value; if (numObj is int) { var num = (int)numObj; txtCtrlCnlNum.Text = num.ToString(); txtCtrlCnlName.Text = Tables.GetCtrlCnlName(num); } chkEvEnabled.Checked = ObjToBool(row.Cells["EvEnabled"].Value); chkEvSound.Checked = ObjToBool(row.Cells["EvSound"].Value); chkEvOnChange.Checked = ObjToBool(row.Cells["EvOnChange"].Value); chkEvOnUndef.Checked = ObjToBool(row.Cells["EvOnUndef"].Value); txtLimLowCrash.Text = row.Cells["LimLowCrash"].FormattedValue.ToString(); txtLimLow.Text = row.Cells["LimLow"].FormattedValue.ToString(); txtLimHigh.Text = row.Cells["LimHigh"].FormattedValue.ToString(); txtLimHighCrash.Text = row.Cells["LimHighCrash"].FormattedValue.ToString(); return(ShowDialog()); } catch (Exception ex) { AppUtils.ProcError(AppPhrases.ShowInCnlPropsError + ":\r\n" + ex.Message); return(DialogResult.Cancel); } }
private void btnCreate_Click(object sender, EventArgs e) { // channel map creation bool useInCnls = rbInCnls.Checked; bool groupByObj = rbGroupByObj.Checked; StreamWriter writer = null; var mapCreated = false; string mapFileName = AppData.AppDirs.LogDir + "ScadaAdminCnlMap.txt"; try { writer = new StreamWriter(mapFileName, false, Encoding.UTF8); mapCreated = true; string title = DateTime.Now.ToString("G", Localization.Culture) + " " + (useInCnls ? (groupByObj ? AppPhrases.InCnlsByObjTitle : AppPhrases.InCnlsByKPTitle) : (groupByObj ? AppPhrases.CtrlCnlsByObjTitle : AppPhrases.CtrlCnlsByKPTitle)); writer.WriteLine(title); writer.WriteLine(new string('-', title.Length)); // getting the table of elements to be grouped var tblItems = groupByObj ? Tables.GetObjTable() : Tables.GetKPTable(); string itemNameFormat = groupByObj ? AppPhrases.ObjectCaptionFormat : AppPhrases.KPCaptionFormat; // determining the method of receiving channels var getCnlTable = useInCnls ? (groupByObj ? new GetCnlTableByItemNumDelegate(Tables.GetInCnlTableByObjNum) : new GetCnlTableByItemNumDelegate(Tables.GetInCnlTableByKPNum)) : (groupByObj ? new GetCnlTableByItemNumDelegate(Tables.GetCtrlCnlTableByObjNum) : new GetCnlTableByItemNumDelegate(Tables.GetCtrlCnlTableByKPNum)); // channel map generation foreach (DataRowView itemRowView in tblItems.DefaultView) { var itemNum = (int)itemRowView[0]; writer.WriteLine(string.Format(itemNameFormat, itemNum, itemRowView[1])); writer.WriteLine(MakeCnlsLine(getCnlTable(itemNum))); writer.WriteLine(); } if (groupByObj) { writer.WriteLine(AppPhrases.UndefinedObject); } else { writer.WriteLine(AppPhrases.UndefinedKP); } var tblCnls = getCnlTable(0); if (tblItems.DefaultView.Count > 0 || tblCnls.DefaultView.Count > 0) { writer.WriteLine(MakeCnlsLine(tblCnls)); } else { writer.WriteLine(AppPhrases.NoChannels); } } catch (Exception ex) { string errMsg = AppPhrases.CreateCnlMapError + ":\r\n" + ex.Message; try { writer.WriteLine(errMsg); } catch { // ignored } AppUtils.ProcError(errMsg); } finally { try { writer.Close(); } catch { // ignored } } if (mapCreated) { Process.Start(mapFileName); } }
/// <summary> /// Группировать каналы, создав соответствующие узлы дерева проводника /// </summary> private void GroupCnls() { try { treeView.BeginUpdate(); nodInCnl.Nodes.Clear(); nodCtrlCnl.Nodes.Clear(); DataTable table; TreeNode node, clone; NodeInfo info; if (miViewGroupByObj.Checked) { // создание узлов объектов table = Tables.GetObjTable(); foreach (DataRow row in table.Rows) { int objID = (int)row["ObjNum"]; node = nodInCnl.Nodes.Add("InCnlObj" + objID, (string)row["Name"], "object.gif", "object.gif"); info = new NodeInfo(NodeAction.InCnlObj); info.Params = new object[] { objID }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeAction.CtrlCnlObj); info.Params = new object[] { objID }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } // создание узла с неопределённым объектом node = nodInCnl.Nodes.Add("InCnlObjNull", AppPhrases.UndefObj, "object.gif", "object.gif"); info = new NodeInfo(NodeAction.InCnlObj); info.Params = new object[] { null }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeAction.CtrlCnlObj); info.Params = new object[] { null }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } else // miViewGroupKP.Checked { table = Tables.GetKPTable(); foreach (DataRow row in table.Rows) { int kpID = (int)row["KPNum"]; node = nodInCnl.Nodes.Add("InCnlKP" + kpID, (string)row["Name"], "kp.gif", "kp.gif"); info = new NodeInfo(NodeAction.InCnlKP); info.Params = new object[] { kpID }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeAction.CtrlCnlKP); info.Params = new object[] { kpID }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } // создание узла с неопределённым КП node = nodInCnl.Nodes.Add("InCnlKPNull", AppPhrases.UndefKP, "kp.gif", "kp.gif"); info = new NodeInfo(NodeAction.InCnlKP); info.Params = new object[] { null }; node.Tag = info; clone = node.Clone() as TreeNode; info = new NodeInfo(NodeAction.CtrlCnlKP); info.Params = new object[] { null }; clone.Tag = info; nodCtrlCnl.Nodes.Add(clone); } } catch (Exception ex) { AppUtils.ProcError(AppPhrases.CnlGroupError + ":\r\n" + ex.Message); } finally { treeView.EndUpdate(); } }