Example #1
0
        /// <summary>
        /// Отобразить форму о программе, загрузив заставку и гиперссылку из файлов
        /// </summary>
        public static void ShowAbout()
        {
            if (frmAbout == null)
            {
                frmAbout = new FrmAbout();
                string errMsg;

                if (!ScadaUtils.LoadAboutForm(AppData.ExeDir + "About.jpg", AppData.ExeDir + "About.txt",
                                              frmAbout, frmAbout.pictureBox, frmAbout.lblLink, out link, out errMsg))
                {
                    frmAbout = null;
                    AppData.ErrLog.WriteAction(errMsg);
                    ScadaUtils.ShowError(errMsg);
                }
            }

            if (frmAbout != null)
            {
                frmAbout.ShowDialog();
            }
        }
Example #2
0
        private void FrmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            // закрытие всех дочерних форм
            PrepareCloseAll(false);
            bool cancel;

            winControl.CloseAllForms(out cancel);
            e.Cancel = cancel;

            if (!cancel)
            {
                // сохранение состояния формы
                if (WindowState == FormWindowState.Normal)
                {
                    settings.FormSt.Left      = Left;
                    settings.FormSt.Top       = Top;
                    settings.FormSt.Width     = Width;
                    settings.FormSt.Height    = Height;
                    settings.FormSt.Maximized = false;
                }
                else
                {
                    settings.FormSt.Left   = RestoreBounds.Left;
                    settings.FormSt.Top    = RestoreBounds.Top;
                    settings.FormSt.Width  = RestoreBounds.Width;
                    settings.FormSt.Height = RestoreBounds.Height;
                    if (WindowState == FormWindowState.Maximized)
                    {
                        settings.FormSt.Maximized = true;
                    }
                }
                settings.FormSt.ExplorerWidth = pnlLeft.Width;

                string errMsg;
                if (!settings.SaveFormState(out errMsg))
                {
                    ScadaUtils.ShowError(errMsg);
                }
            }
        }
Example #3
0
        /// <summary>
        /// Проверить корректность вещественного значения ячейки
        /// </summary>
        private bool ValidateCell(int colInd, int rowInd, object cellVal)
        {
            if (0 <= colInd && colInd < dataGridView.ColumnCount && 0 <= rowInd && rowInd < dataGridView.RowCount &&
                cellVal != null)
            {
                Type   valType = dataGridView.Columns[colInd].ValueType;
                string valStr  = cellVal.ToString();

                if (valType == typeof(int))
                {
                    int intVal;
                    if (!int.TryParse(valStr, out intVal))
                    {
                        ScadaUtils.ShowError(CommonPhrases.IntegerRequired);
                        return(false);
                    }
                }
                else if (valType == typeof(double))
                {
                    double doubleVal;
                    if (!double.TryParse(valStr, out doubleVal))
                    {
                        ScadaUtils.ShowError(CommonPhrases.RealRequired);
                        return(false);
                    }
                }
                else if (valType == typeof(DateTime))
                {
                    DateTime dtVal;
                    if (!DateTime.TryParse(valStr, out dtVal))
                    {
                        ScadaUtils.ShowError(CommonPhrases.DateTimeRequired);
                        return(false);
                    }
                }
            }

            return(true);
        }
Example #4
0
 /// <summary>
 /// Загрузить таблицу срезов
 /// </summary>
 private static bool LoadSrezTable(SrezAdapter srezAdapter, Log errLog, ref SrezTable srezTable)
 {
     try
     {
         srezAdapter.Fill(srezTable);
         return(true);
     }
     catch (Exception ex)
     {
         string errMsg = AppPhrases.LoadSrezTableError + ":\r\n" + ex.Message;
         if (errLog != null)
         {
             errLog.WriteAction(errMsg, Log.ActTypes.Exception);
         }
         ScadaUtils.ShowError(errMsg);
         return(false);
     }
     finally
     {
         Cursor.Current = Cursors.Default;
     }
 }
Example #5
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            // проверка существования файла шаблона устройства
            if (!File.Exists(appDirs.ConfigDir + txtDevTemplate.Text))
            {
                ScadaUtils.ShowError(KpPhrases.TemplNotExists);
                return;
            }

            // изменение свойств КП в соответствии с элементами управления
            if (kpProps.Modified)
            {
                kpProps.CustomParams["TransMode"] = (string)cbTransMode.GetSelectedItem(
                    new Dictionary <int, object>()
                {
                    { 0, "RTU" }, { 1, "ASCII" }, { 2, "TCP" }
                });
                kpProps.CmdLine = txtDevTemplate.Text;
            }

            DialogResult = DialogResult.OK;
        }
Example #6
0
        /// <summary>
        /// Выполнить действия при запуске линии связи
        /// </summary>
        public override void OnCommLineStart()
        {
            // определение, является ли КП основным на линии связи
            // основным автоматически считается первый КП на линии связи
            object primaryObj;

            if (CommonProps.TryGetValue("KpSmsPrimary", out primaryObj))
            {
                primary   = false;
                phonebook = null;
            }
            else
            {
                primary = true;
                CommonProps.Add("KpSmsPrimary", Caption);

                // загрузка телефонного справочника
                string fileName = AppDirs.ConfigDir + Phonebook.DefFileName;
                if (File.Exists(fileName))
                {
                    WriteToLog(Localization.UseRussian ?
                               "Загрузка телефонного справочника" :
                               "Loading phone book");
                    phonebook = new Phonebook();
                    string errMsg;
                    if (!phonebook.Load(fileName, out errMsg))
                    {
                        ScadaUtils.ShowError(errMsg);
                    }
                }
                else
                {
                    phonebook = null;
                    WriteToLog(Localization.UseRussian ?
                               "Телефонный справочник отсутствует" :
                               "Phone book is missing");
                }
            }
        }
Example #7
0
        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, "ScadaWebConfig"))
            {
                if (Localization.LoadDictionaries(langDir, "ScadaWebConfig", out errMsg))
                {
                    Localization.TranslateForm(this, "ScadaWebConfig.FrmMain");
                    WebPhrases.Init();
                    AppPhrases.Init();
                    folderBrowserDialog.Description = AppPhrases.ChooseConfigDir;
                    openFileDialog.Title            = AppPhrases.ChooseViewFile;
                    openFileDialog.Filter           = AppPhrases.FileFilter;
                }
                else
                {
                    ScadaUtils.ShowError(errMsg);
                }
            }
        }
Example #8
0
        /// <summary>
        /// Загрузить настройки из файлов
        /// </summary>
        private void LoadSettings()
        {
            StringBuilder sbErr = new StringBuilder();
            string        errMsg;

            SetSettingsUnchanged();

            // загрузка настроек соединения
            if (!commSettings.LoadFromFile(configDir + CommSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            // загрузка настроек отображения
            if (!webSettings.LoadFromFile(configDir + WebSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            // загрузка настроек представлений
            if (!viewSettings.LoadFromFile(configDir + ViewSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            // отображение настроек
            SettingsToControls();

            if (sbErr.Length > 0)
            {
                ScadaUtils.ShowError(sbErr.ToString().TrimEnd());
            }

            loadedCommSettings = commSettings.Clone();
            loadedWebSettings  = webSettings.Clone();
            loadedViewSettings = viewSettings.Clone();
            loadedRegKey       = regKey;
        }
Example #9
0
        /// <summary>
        /// Сохраненить изменения
        /// </summary>
        private bool SaveChanges(bool saveAs)
        {
            // определение имени файла
            string newFileName = "";

            if (saveAs || fileName == "")
            {
                if (saveFileDialog.ShowDialog() == DialogResult.OK)
                {
                    newFileName = saveFileDialog.FileName;
                }
            }
            else
            {
                newFileName = fileName;
            }

            if (newFileName == "")
            {
                return(false);
            }
            else
            {
                // сохранение шаблона устройства
                string errMsg;
                if (devTemplate.SaveTemplate(newFileName, out errMsg))
                {
                    Modified = false;
                    fileName = newFileName;
                    return(true);
                }
                else
                {
                    ScadaUtils.ShowError(errMsg);
                    return(false);
                }
            }
        }
Example #10
0
        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);
            }
        }
Example #11
0
        /// <summary>
        /// Загрузить директорию конфигурации из файла
        /// </summary>
        private void LoadConfigDir()
        {
            // установка директории конфигурации по умолчанию
            configDir = DefaultConfigDir;

            // загрузка директории конфигурации
            try
            {
                string fileName = exeDir + SettingsFileName;
                if (!File.Exists(fileName))
                {
                    throw new FileNotFoundException(string.Format(CommonPhrases.NamedFileNotFound, fileName));
                }

                XmlDocument xmlDoc = new XmlDocument();
                xmlDoc.Load(fileName);

                XmlNodeList paramNodeList = xmlDoc.DocumentElement.SelectNodes("Param");
                foreach (XmlElement paramElem in paramNodeList)
                {
                    if (paramElem.GetAttribute("name").Trim().ToLower() == "configdir")
                    {
                        configDir = ScadaUtils.NormalDir(paramElem.GetAttribute("value"));
                    }
                }
            }
            catch (Exception ex)
            {
                ScadaUtils.ShowError(AppPhrases.LoadConfigDirError + ":\n" + ex.Message);
            }

            // вывод директории конфигурации
            txtConfigDir.Text = configDir;

            // определение директории веб-приложения
            webAppDir = configDir.EndsWith(@"\config\") ? configDir.Substring(0, configDir.Length - 7) : "";
        }
Example #12
0
        /// <summary>
        /// Сохранить настройки в файлах
        /// </summary>
        private void SaveSettings()
        {
            StringBuilder sbErr = new StringBuilder();
            string        errMsg;

            // сохранение настроек доступа к данным
            if (commSettingsChanged && !commSettings.SaveToFile(configDir + CommSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            // сохранение настроек отображения
            if (webSettingsChanged && !webSettings.SaveToFile(configDir + WebSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            // сохранение настроек представлений
            if (viewSettingsChanged && !viewSettings.SaveToFile(configDir + ViewSettings.DefFileName, out errMsg))
            {
                sbErr.AppendLine(errMsg);
            }

            if (sbErr.Length > 0)
            {
                ScadaUtils.ShowError(sbErr.ToString().TrimEnd());
            }
            else
            {
                SetSettingsUnchanged();
                loadedCommSettings = commSettings.Clone();
                loadedWebSettings  = webSettings.Clone();
                loadedViewSettings = viewSettings.Clone();
                loadedRegKey       = regKey;
            }
        }
Example #13
0
        /// <summary>
        /// Сохранить табличное представление
        /// </summary>
        private bool SaveTableView(bool saveAs)
        {
            bool result = false;

            if (fileName == "")
            {
                saveFileDialog.FileName = DefFileName;
                saveAs = true;
            }
            else
            {
                saveFileDialog.FileName = fileName;
            }

            if (!saveAs || saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                if (saveAs)
                {
                    fileName = saveFileDialog.FileName;
                }

                string errMsg;
                if (tableView.SaveToFile(fileName, out errMsg))
                {
                    SetModified(false);
                    SetFormTitle();
                    result = true;
                }
                else
                {
                    ScadaUtils.ShowError(errMsg);
                }
            }

            return(result);
        }
Example #14
0
        private void FrmDBExportConfig_Load(object sender, EventArgs e)
        {
            // локализация модуля
            string errMsg;

            if (!Localization.UseRussian)
            {
                if (Localization.LoadDictionaries(appDirs.LangDir, "ModDBExport", out errMsg))
                {
                    Localization.TranslateForm(this, "Scada.Server.Modules.DBExport.FrmDBExportConfig");
                }
                else
                {
                    ScadaUtils.ShowError(errMsg);
                }
            }

            // настройка элементов управления
            lblInstruction.Top = treeView.Top;

            // загрузка конфигурации
            config = new Config(appDirs.ConfigDir);
            if (File.Exists(config.FileName) && !config.Load(out errMsg))
            {
                ScadaUtils.ShowError(errMsg);
            }

            // создание копии конфигурации
            configCopy = config.Clone();

            // отображение конфигурации
            ConfigToControls();

            // снятие признака изменения конфигурации
            Modified = false;
        }
Example #15
0
        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);
            }
        }
Example #16
0
 private void dgvItems_DataError(object sender, DataGridViewDataErrorEventArgs e)
 {
     ScadaUtils.ShowError(CommonPhrases.GridDataError + ":\n" + e.Exception.Message);
     e.ThrowException = false;
 }
Example #17
0
        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;
                }
            }
        }
Example #18
0
        /// <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);
            }
        }
Example #19
0
 public static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
 {
     ScadaUtils.ShowError(e.Exception.Message);
 }
Example #20
0
        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);
            }
        }
Example #21
0
        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);
            }
        }
Example #22
0
        /// <summary>
        /// Отобразить форму настроек приложения
        /// </summary>
        public static void Show(TableView.Item item, DataTable tblInCnl, DataTable tblCtrlCnl,
                                DataTable tblObj, DataTable tblKP)
        {
            if (item == null)
            {
                throw new ArgumentNullException("item");
            }
            if (tblInCnl == null)
            {
                throw new ArgumentNullException("tblInCnl");
            }
            if (tblCtrlCnl == null)
            {
                throw new ArgumentNullException("tblCtrlCnl");
            }
            if (tblObj == null)
            {
                throw new ArgumentNullException("tblObj");
            }
            if (tblKP == null)
            {
                throw new ArgumentNullException("tblKP");
            }

            // создание и перевод формы
            FrmItemInfo frmItemInfo = new FrmItemInfo();

            Localization.TranslateForm(frmItemInfo, "ScadaTableEditor.FrmItemInfo");

            // получение информации о входном канале
            if (item.CnlNum > 0)
            {
                string cnlNumStr = item.CnlNum.ToString();
                frmItemInfo.txtInCnlNum.Text = cnlNumStr;

                try
                {
                    DataView view = new DataView(tblInCnl);
                    view.RowFilter = "CnlNum = " + cnlNumStr;

                    if (view.Count > 0)
                    {
                        DataRowView rowView = view[0];
                        frmItemInfo.txtInCnlName.Text = (string)rowView["Name"];

                        int objNum = (int)rowView["ObjNum"];
                        if (objNum > 0)
                        {
                            frmItemInfo.txtInCnlObjNum.Text  = objNum.ToString();
                            frmItemInfo.txtInCnlObjName.Text = GetObjName(objNum, tblObj);
                        }

                        int kpNum = (int)rowView["KPNum"];
                        if (kpNum > 0)
                        {
                            frmItemInfo.txtInCnlKPNum.Text  = kpNum.ToString();
                            frmItemInfo.txtInCnlKPName.Text = GetKPName(kpNum, tblKP);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ScadaUtils.ShowError(AppPhrases.GetInCnlError + ":\n" + ex.Message);
                }
            }

            // получение информации о канале управления
            if (item.CtrlCnlNum > 0)
            {
                string ctrlCnlNumStr = item.CtrlCnlNum.ToString();
                frmItemInfo.txtCtrlCnlNum.Text = ctrlCnlNumStr;

                try
                {
                    DataView view = new DataView(tblCtrlCnl);
                    view.RowFilter = "CtrlCnlNum = " + ctrlCnlNumStr;

                    if (view.Count > 0)
                    {
                        DataRowView rowView = view[0];
                        frmItemInfo.txtCtrlCnlName.Text = (string)rowView["Name"];

                        int objNum = (int)rowView["ObjNum"];
                        if (objNum > 0)
                        {
                            frmItemInfo.txtCtrlCnlObjNum.Text  = objNum.ToString();
                            frmItemInfo.txtCtrlCnlObjName.Text = GetObjName(objNum, tblObj);
                        }

                        int kpNum = (int)rowView["KPNum"];
                        if (kpNum > 0)
                        {
                            frmItemInfo.txtCtrlCnlKPNum.Text  = kpNum.ToString();
                            frmItemInfo.txtCtrlCnlKPName.Text = GetKPName(kpNum, tblKP);
                        }
                    }
                }
                catch (Exception ex)
                {
                    ScadaUtils.ShowError(AppPhrases.GetCtrlCnlError + ":\n" + ex.Message);
                }
            }

            // отображение формы
            frmItemInfo.ShowDialog();
        }
Example #23
0
        private void btnDelete_Click(object sender, EventArgs e)
        {
            // удаление набора или представления
            if (selViewSet == null && selViewInfo == null)
            {
                ScadaUtils.ShowError(AppPhrases.ChooseViewToDelete);
            }
            else
            {
                if (selViewInfo == null)
                {
                    // удаление набора таблиц
                    int ind = viewSettings.ViewSetList.IndexOf(selViewSet);
                    viewSettings.ViewSetList.RemoveAt(ind);
                    tvTableSets.Nodes.RemoveAt(ind);

                    // определение выбранного набора таблиц
                    if (--ind < 0)
                    {
                        ind = 0;
                    }

                    if (ind < viewSettings.ViewSetList.Count)
                    {
                        selViewSet = viewSettings.ViewSetList[ind];
                        tvTableSets.SelectedNode = tvTableSets.Nodes[ind];
                    }
                    else
                    {
                        selViewSet = null;
                        tvTableSets.SelectedNode = null;

                        txtName.Text          = "";
                        txtName.Enabled       = false;
                        lblDir.Visible        = true;
                        lblFile.Visible       = false;
                        txtDirOrFile.Text     = "";
                        txtDirOrFile.Enabled  = false;
                        btnSelectView.Visible = false;
                    }
                }
                else
                {
                    // удаление представления
                    int tableInd = selViewSet.Items.IndexOf(selViewInfo);
                    selViewSet.Items.RemoveAt(tableInd);
                    int      tableSetInd  = viewSettings.ViewSetList.IndexOf(selViewSet);
                    TreeNode nodeTableSet = tvTableSets.Nodes[tableSetInd];
                    nodeTableSet.Nodes.RemoveAt(tableInd);

                    // определение выбранного представления
                    if (--tableInd < 0)
                    {
                        tableInd = 0;
                    }

                    if (tableInd < selViewSet.Count)
                    {
                        selViewInfo = selViewSet[tableInd];
                        tvTableSets.SelectedNode = nodeTableSet.Nodes[tableInd];
                    }
                    else
                    {
                        selViewInfo = null;
                        tvTableSets.SelectedNode = nodeTableSet;
                    }
                }

                viewSets_Changed();
            }
        }
Example #24
0
        /// <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);
            }
        }
Example #25
0
        private void btnOk_Click(object sender, EventArgs e)
        {
            // проверка введённых данных
            StringBuilder 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 == "")
            {
                // передача свойств входного канала в редактируемую таблицу
                try
                {
                    DataRowView 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
            {
                ScadaUtils.ShowError(errMsg);
            }
        }
Example #26
0
        private void btnSelectView_Click(object sender, EventArgs e)
        {
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                // определение наименования, имени файла и типа представления
                string fname = openFileDialog.FileName;
                string ext   = Path.GetExtension(fname);

                string viewFile    = "";
                string viewTitle   = "";
                int    viewTypeInd = 0;

                if (ext == ".tbl" || ext == ".ofm" || ext == ".sch" || ext == ".fcs")
                {
                    string dir = selViewSet == null ? "" : ScadaUtils.NormalDir(selViewSet.Directory);
                    int    pos = dir == "" ? -1 : fname.IndexOf(dir);
                    viewFile = pos >= 0 ? fname.Substring(pos + dir.Length) : Path.GetFileName(fname);

                    if (ext == ".sch")
                    {
                        viewTypeInd = 1;
                    }
                    else if (ext == ".fcs")
                    {
                        viewTypeInd = 2;
                    }

                    try
                    {
                        using (StreamReader reader = new StreamReader(fname, Encoding.Default))
                        {
                            if (ext == ".ofm")
                            {
                                string line = reader.ReadLine();
                                pos       = line.IndexOf(": ");
                                viewTitle = pos >= 0 ? line.Substring(pos + 2) : line;
                            }
                            else
                            {
                                reader.ReadLine();
                                string line = reader.ReadLine();
                                pos = line.IndexOf("title=\"");
                                if (pos >= 0)
                                {
                                    int quotPos = line.LastIndexOf("\"");
                                    viewTitle = line.Substring(pos + 7, quotPos - pos - 7);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        ScadaUtils.ShowError(AppPhrases.ParseViewTitleError + ":\n" + ex.Message);
                    }
                }
                else if (ext == ".aspx" || ext == ".htm" || ext == ".html")
                {
                    int pos = webAppDir == "" ? -1 : fname.IndexOf(webAppDir);
                    viewFile    = pos >= 0 ? fname.Substring(pos + webAppDir.Length).Replace('\\', '/') : fname;
                    viewTypeInd = 3;
                }

                txtDirOrFile.Text    = viewFile;
                txtName.Text         = viewTitle;
                cbType.SelectedIndex = viewTypeInd;
            }
        }
Example #27
0
 /// <summary>
 /// Обработать ошибку, записав информацию в журнал и отобразив сообщение
 /// </summary>
 public static void ProcError(string message)
 {
     AppData.ErrLog.WriteAction(message, Log.ActTypes.Exception);
     ScadaUtils.ShowError(message);
 }
Example #28
0
        private void FrmMain_Load(object sender, EventArgs e)
        {
            // локализация приложения
            string langDir = AppData.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, "ScadaAdmin"))
            {
                if (Localization.LoadDictionaries(langDir, "ScadaAdmin", out errMsg))
                {
                    Localization.TranslateForm(this, "ScadaAdmin.FrmMain", null, contextExpolorer, contextInCnls);
                    AppPhrases.Init();
                    winControl.MessageText     = AppPhrases.SelectTable;
                    winControl.SaveReqCaption  = AppPhrases.SaveReqCaption;
                    winControl.SaveReqQuestion = AppPhrases.SaveReqQuestion;
                    winControl.SaveReqYes      = AppPhrases.SaveReqYes;
                    winControl.SaveReqNo       = AppPhrases.SaveReqNo;
                    winControl.SaveReqCancel   = AppPhrases.SaveReqCancel;
                }
                else
                {
                    ScadaUtils.ShowError(errMsg);
                }
            }

            // инициализация дерева проводника
            InitTreeView();

            // установка начального состояния разрешений элементов
            SetItemsEnabledOnConnect();
            SetItemsEnabledOnWindowAction();

            // загрузка состояния формы
            settings = new Settings();
            settings.LoadFormState();
            if (settings.FormSt.IsEmpty)
            {
                WindowState = FormWindowState.Maximized;
            }
            else
            {
                Left          = settings.FormSt.Left;
                Top           = settings.FormSt.Top;
                Width         = settings.FormSt.Width;
                Height        = settings.FormSt.Height;
                WindowState   = settings.FormSt.Maximized ? FormWindowState.Maximized : FormWindowState.Normal;
                pnlLeft.Width = settings.FormSt.ExplorerWidth;
            }
        }