Ejemplo n.º 1
0
        /// <summary>
        /// Creates channels based on the prototypes.
        /// </summary>
        private bool CreateChannels()
        {
            try
            {
                List <KPView.InCnlPrototype>   inCnlPrototypes   = ctrlCnlCreate1.CnlPrototypes.InCnls;
                List <KPView.CtrlCnlPrototype> ctrlCnlPrototypes = ctrlCnlCreate1.CnlPrototypes.CtrlCnls;
                int?   objNum    = ctrlCnlCreate2.ObjNum;
                int    kpNum     = ctrlCnlCreate1.SelectedDevice.KPNum;
                string cnlPrefix = appData.AppSettings.ChannelOptions.PrependDeviceName ?
                                   ctrlCnlCreate1.SelectedDevice.Name + " - " : "";
                int inCnlNum      = ctrlCnlCreate3.StartInCnl;
                int ctrlCnlNum    = ctrlCnlCreate3.StartOutCnl;
                int inCnlsAdded   = 0;
                int ctrlCnlsAdded = 0;
                BaseTable <InCnl>   inCnlTable   = project.ConfigBase.InCnlTable;
                BaseTable <CtrlCnl> ctrlCnlTable = project.ConfigBase.CtrlCnlTable;
                BaseTable <Format>  formatTable  = project.ConfigBase.FormatTable;
                DictIndexes         dictIndexes  = new DictIndexes(project.ConfigBase);

                // create output channels
                foreach (KPView.CtrlCnlPrototype ctrlCnlPrototype in ctrlCnlPrototypes)
                {
                    ctrlCnlPrototype.CtrlCnlNum = ctrlCnlNum;

                    CtrlCnl ctrlCnl = new CtrlCnl
                    {
                        CtrlCnlNum  = ctrlCnlNum++,
                        Active      = ctrlCnlPrototype.Active,
                        Name        = cnlPrefix + ctrlCnlPrototype.CtrlCnlName,
                        CmdTypeID   = ctrlCnlPrototype.CmdTypeID,
                        ObjNum      = objNum,
                        KPNum       = kpNum,
                        CmdNum      = ctrlCnlPrototype.CmdNum > 0 ? (int?)ctrlCnlPrototype.CmdNum : null,
                        CmdValID    = dictIndexes.GetID(dictIndexes.CmdValByName, ctrlCnlPrototype.CmdVal),
                        FormulaUsed = ctrlCnlPrototype.FormulaUsed,
                        Formula     = ctrlCnlPrototype.Formula,
                        EvEnabled   = ctrlCnlPrototype.EvEnabled
                    };

                    if (ctrlCnl.Name.Length > ColumnLength.Name)
                    {
                        ctrlCnl.Name = ctrlCnl.Name.Substring(0, ColumnLength.Name);
                    }

                    ctrlCnlTable.AddItem(ctrlCnl);
                    ctrlCnlsAdded++;

                    if (ctrlCnlNum > ushort.MaxValue)
                    {
                        break;
                    }
                }

                if (ctrlCnlsAdded > 0)
                {
                    ctrlCnlTable.Modified = true;
                }

                // create input channels
                foreach (KPView.InCnlPrototype inCnlPrototype in inCnlPrototypes)
                {
                    int formatID = inCnlPrototype.ShowNumber ?
                                   Math.Min(inCnlPrototype.DecDigits, BaseValues.Formats.MaxFixedID) :
                                   BaseValues.Formats.EnumText;

                    InCnl inCnl = new InCnl
                    {
                        CnlNum      = inCnlNum++,
                        Active      = inCnlPrototype.Active,
                        Name        = cnlPrefix + inCnlPrototype.CnlName,
                        CnlTypeID   = inCnlPrototype.CnlTypeID,
                        ObjNum      = objNum,
                        KPNum       = kpNum,
                        Signal      = inCnlPrototype.Signal > 0 ? (int?)inCnlPrototype.Signal : null,
                        FormulaUsed = inCnlPrototype.FormulaUsed,
                        Formula     = inCnlPrototype.Formula,
                        Averaging   = inCnlPrototype.Averaging,
                        ParamID     = dictIndexes.GetID(dictIndexes.ParamByName, inCnlPrototype.ParamName),
                        FormatID    = formatTable.PkExists(formatID) ? (int?)formatID : null,
                        UnitID      = dictIndexes.GetID(dictIndexes.UnitByName, inCnlPrototype.UnitName),
                        CtrlCnlNum  = inCnlPrototype.CtrlCnlProps?.CtrlCnlNum,
                        EvEnabled   = inCnlPrototype.EvEnabled,
                        EvSound     = inCnlPrototype.EvSound,
                        EvOnChange  = inCnlPrototype.EvOnChange,
                        EvOnUndef   = inCnlPrototype.EvOnUndef,
                        LimLowCrash = double.IsNaN(inCnlPrototype.LimLowCrash) ?
                                      null : (double?)inCnlPrototype.LimLowCrash,
                        LimLow = double.IsNaN(inCnlPrototype.LimLow) ?
                                 null : (double?)inCnlPrototype.LimLow,
                        LimHigh = double.IsNaN(inCnlPrototype.LimHigh) ?
                                  null : (double?)inCnlPrototype.LimHigh,
                        LimHighCrash = double.IsNaN(inCnlPrototype.LimHighCrash) ?
                                       null : (double?)inCnlPrototype.LimHighCrash
                    };

                    if (inCnl.Name.Length > ColumnLength.Name)
                    {
                        inCnl.Name = inCnl.Name.Substring(0, ColumnLength.Name);
                    }

                    inCnlTable.AddItem(inCnl);
                    inCnlsAdded++;

                    if (inCnlNum > ushort.MaxValue)
                    {
                        break;
                    }
                }

                if (inCnlsAdded > 0)
                {
                    inCnlTable.Modified = true;
                }

                ScadaUiUtils.ShowInfo(string.Format(AppPhrases.CreateCnlsComplete, inCnlsAdded, ctrlCnlsAdded));
                return(true);
            }
            catch (Exception ex)
            {
                appData.ProcError(ex, AppPhrases.CreateCnlsError);
                return(false);
            }
        }
Ejemplo n.º 2
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
                {
                    ScadaUiUtils.ShowError(errMsg);
                }
            }

            if (Localization.LoadingRequired(langDir, "ScadaSchemeEditor"))
            {
                if (Localization.LoadDictionaries(langDir, "ScadaSchemeEditor", out errMsg))
                {
                    Translator.TranslateForm(this, "Scada.Scheme.Editor.FrmMain");
                    SchemePhrases.InitStatic();
                    openFileDialog.Filter = saveFileDialog.Filter = SchemePhrases.FileFilter;
                }
                else
                {
                    ScadaUiUtils.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)
                {
                    ScadaUiUtils.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;
                }
            }
        }
Ejemplo n.º 3
0
        private void FrmMain_Load(object sender, EventArgs e)
        {
#if DEBUG
            System.Diagnostics.Debugger.Launch();
#endif

            // инициализация общих данных приложения
            appData.Init(Path.GetDirectoryName(Application.ExecutablePath), this);

            // локализация
            LocalizeForm();
            LocalizeAttributes();

            // проверка существования второй копии приложения
            if (SecondInstanceExists())
            {
                ScadaUiUtils.ShowInfo(AppPhrases.CloseSecondInstance);
                Close();
                log.WriteAction(Localization.UseRussian ?
                                "Вторая копия Редактора схем закрыта." :
                                "The second instance of Scheme Editor has been closed.");
                return;
            }

            // загрузка настроек приложения
            string errMsg;
            if (!settings.Load(appData.AppDirs.ConfigDir + Settings.DefFileName, out errMsg))
            {
                log.WriteError(errMsg);
                ScadaUiUtils.ShowError(errMsg);
            }

            // загрузка компонентов
            appData.LoadComponents();

            // настройка элментов управления
            lvCompTypes.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
            lblStatus.Text = "";
            FillComponentTypes();

            // создание новой схемы
            InitScheme();

            // загрузка состояния формы
            FormState formState = new FormState();
            if (formState.Load(appData.AppDirs.ConfigDir + FormState.DefFileName, out errMsg))
            {
                ImageEditor.ImageDir       = formState.ImageDir;
                ofdScheme.InitialDirectory = formState.SchemeDir;
            }
            else
            {
                log.WriteError(errMsg);
                ScadaUiUtils.ShowError(errMsg);
            }
            formState.Apply(this);
            UpdateFormStateDTO();

            // запуск механизма редактора схем
            if (appData.StartEditor())
            {
                // открытие браузера со страницей редактора
                OpenBrowser();
            }
            else
            {
                ScadaUiUtils.ShowInfo(string.Format(AppPhrases.FailedToStartEditor, log.FileName));
                Close();
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Импорт линий связи и КП
        /// </summary>
        public static DialogResult Import(DataTable tblCommLine, DataTable tblKP, Log errLog, out FrmImport frmImport)
        {
            frmImport = null;

            try
            {
                if (tblCommLine.DefaultView.Count == 0)
                {
                    ScadaUiUtils.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);
                ScadaUiUtils.ShowError(errMsg);

                return(DialogResult.Abort);
            }
        }
Ejemplo n.º 5
0
        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);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Loads a scheme template if possible.
        /// </summary>
        private void LoadSchemeTemplate(bool showMsg)
        {
            // display empty data
            changing = true;
            cbTitleComponent.DataSource = null;
            bsBindings.DataSource       = null;

            if (string.IsNullOrEmpty(interfaceDir))
            {
                if (showMsg)
                {
                    ScadaUiUtils.ShowWarning(AppPhrases.UnableLoadTemplate);
                }
            }
            else
            {
                string templateFileName = Path.Combine(interfaceDir, txtTemplateFileName.Text);

                if (File.Exists(templateFileName))
                {
                    if (SchemeParser.Parse(templateFileName, out List <ComponentItem> components,
                                           out List <ComponentBindingItem> newComponentBindings, out string errMsg))
                    {
                        // merge bindings
                        foreach (ComponentBindingItem bindingItem in newComponentBindings)
                        {
                            if (templateBindings.ComponentBindings.TryGetValue(bindingItem.CompID,
                                                                               out ComponentBinding binding))
                            {
                                bindingItem.InCnlNum   = binding.InCnlNum;
                                bindingItem.CtrlCnlNum = binding.CtrlCnlNum;
                            }
                        }

                        templateBindings.ComponentBindings.Clear();
                        newComponentBindings.ForEach(x => { templateBindings.ComponentBindings[x.CompID] = x; });

                        // fill the component combo box
                        components.Sort();
                        cbTitleComponent.ValueMember   = "ID";
                        cbTitleComponent.DisplayMember = "DisplayName";
                        cbTitleComponent.DataSource    = components;
                        cbTitleComponent.SelectedValue = templateBindings.TitleCompID;

                        // display bindings
                        bsBindings.DataSource = templateBindings.ComponentBindings.Values;

                        if (showMsg)
                        {
                            ScadaUiUtils.ShowInfo(AppPhrases.TemplateLoaded);
                        }
                    }
                    else
                    {
                        bsBindings.DataSource = null;
                        ScadaUiUtils.ShowError(errMsg);
                    }
                }
                else if (showMsg)
                {
                    ScadaUiUtils.ShowWarning(string.Format(AppPhrases.TemplateNotFound, templateFileName));
                }
            }

            changing = false;
        }
Ejemplo n.º 7
0
        private void btnReplaceAll_Click(object sender, EventArgs e)
        {
            // replace all values
            var columnInfo = cbTableColumn.SelectedItem as ColumnInfo;

            if (frmTable != null && columnInfo != null)
            {
                // list of lines that are replaced
                var replacedRows = new List <DataRowView>();

                var  cnt       = 0;
                var  matchCell = true;
                bool updated;
                bool found;

                do
                {
                    // replacement
                    bool replaced = ReplaceCellVal(columnInfo, matchCell, out updated);
                    matchCell = false;
                    if (replaced && updated)
                    {
                        cnt++;
                    }

                    // save string with replaced value
                    var curCell = gridView.CurrentCell;
                    if (replaced)
                    {
                        if (curCell != null)
                        {
                            int rowInd = curCell.RowIndex;
                            if (0 <= rowInd && rowInd < frmTable.Table.DefaultView.Count)
                            {
                                replacedRows.Add(frmTable.Table.DefaultView[rowInd]);
                            }
                        }
                    }

                    // search for the next replacement value
                    if (updated)
                    {
                        do
                        {
                            found = FindNext(columnInfo, false);
                            if (found)
                            {
                                // check that the value in the found string has not yet been replaced
                                DataRowView rowView = null;
                                if (gridView.CurrentCell != null)
                                {
                                    int rowInd = gridView.CurrentCell.RowIndex;
                                    if (0 <= rowInd && rowInd < frmTable.Table.DefaultView.Count)
                                    {
                                        rowView = frmTable.Table.DefaultView[rowInd];
                                    }
                                }

                                if (replacedRows.Contains(rowView))
                                {
                                    found = false;
                                }
                            }
                        } while (curCell != gridView.CurrentCell && !found);
                    }
                    else
                    {
                        found = false;
                    }
                } while (found);

                if (cnt > 0)
                {
                    ScadaUiUtils.ShowInfo(string.Format(AppPhrases.ReplaceCount, cnt));
                }
                else if (updated)
                {
                    ScadaUiUtils.ShowInfo(completeMsg);
                }
            }
        }