Ejemplo n.º 1
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            using (var rec = new RecDao(Different.GetInfoTaskDir() + @"General\Config.accdb",
                                        "SELECT SysSubTabl.SubParamRowSource FROM SysTabl INNER JOIN SysSubTabl ON SysTabl.ParamId = SysSubTabl.ParamId " +
                                        "WHERE ((SysTabl.ParamValue='Приемник') AND (SysSubTabl.SubParamName='OPCServerName'));"))
                while (rec.Read())
                {
                    var set = rec.GetString("SubParamRowSource").ToPropertyHashSet();
                    foreach (var s in set.Values)
                    {
                        if (!OpcServerName.Items.Contains(s))
                        {
                            OpcServerName.Items.Add(s);
                        }
                    }
                }
            OpcServerName.Items.Add("Matrikon.OPC.Simulation.1");

            using (var sys = new SysTabl(Different.GetInfoTaskDir() + @"Controller\ControllerData.accdb"))
            {
                OpcServerName.Text = sys.SubValue("DebugWriteOPC", "OpcServerName");
                Node.Text          = sys.SubValue("DebugWriteOPC", "Node");
                OpcTag.Text        = sys.SubValue("DebugWriteOPC", "OpcTag");
                DataType.Text      = sys.SubValue("DebugWriteOPC", "DataType");
                TagValue.Text      = sys.SubValue("DebugWriteOPC", "TagValue");
            }
        }
Ejemplo n.º 2
0
        private void UpdateParams(DaoDb db)
        {
            AddEvent("Обновление таблиц CalcParams и Projects по ячейкам отчета");
            using (var rpr = new RecDao(db, "Projects"))
                while (rpr.Read())
                {
                    string pr = rpr.GetString("ProjectCode2");
                    if (pr.IsEmpty())
                    {
                        pr = rpr.GetString("Project");
                    }
                    Projects[pr].PropsToRecordset(rpr);
                }

            using (var rp = new RecDao(db, "CalcParams"))
                if (rp.HasRows())
                {
                    rp.MoveFirst();
                    while (!rp.EOF)
                    {
                        var proj  = Projects[rp.GetString("Project")];
                        var code  = rp.GetString("Code");
                        var param = proj.Params[code];
                        param.PropsToRecordset(rp);
                        rp.MoveNext();
                    }
                }
        }
Ejemplo n.º 3
0
 //Подготовка сигналов
 public void Prepare()
 {
     try
     {
         if (CloneFile.IsEmpty())
         {
             return;
         }
         Logger.AddEvent("Установка отметок для считываемых сигналов");
         _signalsId.Clear();
         _signalsStrId.Clear();
         using (var rec = new RecDao(CloneFile, "SELECT SignalId, FullCode, Otm FROM Signals"))
             while (rec.Read())
             {
                 string code = rec.GetString("FullCode");
                 if (!ProviderSignals.ContainsKey(code))
                 {
                     rec.Put("Otm", false);
                 }
                 else
                 {
                     rec.Put("Otm", true);
                     (ProviderSignals[code].DataType.LessOrEquals(DataType.Real) ? _signalsId : _signalsStrId)
                     .Add(rec.GetInt("SignalId"), ProviderSignals[code]);
                 }
             }
     }
     catch (Exception ex)
     {
         Logger.AddError("Ошибка при подготовке сигналов", ex);
     }
 }
Ejemplo n.º 4
0
        //Формирование списка параметров для записи в архив и запись их в CalcParamsArchive
        private void SaveArchive()
        {
            try
            {
                using (var db = new DaoDb(_projectFile))
                {
                    foreach (var cp in CalcParamsId.Values)
                    {
                        if (cp.Inputs.Count == 0 && cp.CalcOn && cp.ErrMess == "")
                        {
                            new ParamArchive(cp);
                        }
                    }

                    var old = new SetS();
                    var add = new SetS();
                    using (var rec = new RecDao(db, "CalcParamsArchive", RecordsetTypeEnum.dbOpenTable))
                        while (rec.Read())
                        {
                            var code = rec.GetString("FullCode");
                            if (ArchiveParams.ContainsKey(code))
                            {
                                old.Add(code);
                            }
                            else
                            {
                                rec.Put("Del", true);
                            }
                        }
                    db.Execute("DELETE * FROM CalcParamsArchive WHERE Del=True");

                    foreach (var ap in ArchiveParams.Keys)
                    {
                        if (!old.Contains(ap))
                        {
                            add.Add(ap);
                        }
                    }
                    using (var rec = new RecDao(db, "CalcParamsArchive", RecordsetTypeEnum.dbOpenTable))
                    {
                        while (rec.Read())
                        {
                            ArchiveParams[rec.GetString("FullCode")].ToRecordset(rec, false);
                        }
                        foreach (var p in add.Keys)
                        {
                            ArchiveParams[p].ToRecordset(rec, true);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка сохранения архивных параметров", ex);
            }
        }
Ejemplo n.º 5
0
 //Чтение значений
 public override void GetValues()
 {
     try
     {
         DateTime beg = BeginRead.AddMinutes(-BeginRead.Minute).AddSeconds(-BeginRead.Second - 1);
         DateTime en  = EndRead.AddSeconds(1);
         using (var db = new DaoDb(_db))
         {
             foreach (var tableName in _objects.Keys)
             {
                 Logger.AddEvent("Чтение значений из таблицы " + tableName + "_ARCHIVE");
                 using (var rec = new RecDao(db, "SELECT * FROM " + tableName + "_ARCHIVE " +
                                             "WHERE (TYPE = 0) AND (Время >= " + beg.ToAccessString() + ") AND (Время <= " + en.ToAccessString() + ")"))
                     while (rec.Read())
                     {
                         int id = rec.GetInt("PARENT_ID");
                         if (_objectsId.ContainsKey(id))
                         {
                             var ob = _objectsId[id];
                             foreach (var sigCode in ob.Signals.Keys)
                             {
                                 ob.Signals[sigCode].AddMoment(rec.GetTime("Время"), rec.GetDouble(sigCode));
                             }
                         }
                     }
             }
             foreach (var tableName in _totals.Keys)
             {
                 Logger.AddEvent("Чтение значений из таблицы " + tableName + "_TOTALS");
                 using (var rec = new RecDao(db, "SELECT * FROM " + tableName + "_TOTALS " +
                                             "WHERE (Время >= " + beg.ToAccessString() + ") AND (Время <= " + en.ToAccessString() + ")"))
                     while (rec.Read())
                     {
                         int id = rec.GetInt("PARENT_ID");
                         if (_totalsId.ContainsKey(id))
                         {
                             var ob = _totalsId[id];
                             foreach (var sigCode in ob.Signals.Keys)
                             {
                                 ob.Signals[sigCode].AddMoment(rec.GetTime("Время"), rec.GetDouble(sigCode));
                             }
                         }
                     }
             }
         }
     }
     catch (Exception ex)
     {
         Logger.AddError("Ошибка при чтении данных из файла программы Пролог", ex);
     }
 }
Ejemplo n.º 6
0
        //Чтение списка сигналов из клона
        private void PrepareForClone(string cloneFile)
        {
            try
            {
                AddEvent("Чтение свойств клона");
                if (!DaoDb.Check(cloneFile, new[] { "Objects", "Signals", "MomentsValues" }))
                {
                    AddError("Недопустимый файл клона");
                }
                else
                {
                    using (var db = new DaoDb(cloneFile))
                    {
                        using (var sys = new SysTabl(db))
                        {
                            if (_form != null)
                            {
                                _form.CalcName.Text = sys.Value("CloneDescription");
                            }
                            _cloneInf = sys.Value("CloneInf");
                            RunSource(sys.SubValue("Source", "ProviderCode"), sys.SubValue("Source", "ProviderName"), sys.SubValue("Source", "ProviderInf"));
                        }

                        AddEvent("Чтение списка сигналов клона");
                        _source.ClearSignals();
                        int n = 0;
                        using (var rec = new RecDao(db, "SELECT SignalId, FullCode, DataType, Inf FROM Signals WHERE ConstValue Is Null"))
                            while (rec.Read())
                            {
                                _source.AddSignal(rec.GetString("Inf"), rec.GetString("FullCode"), rec.GetString("DataType").ToDataType(), rec.GetInt("SignalId"));
                                n++;
                            }
                        AddEvent("Сигналы клона прочитаны", n + " сигналов");

                        //db.Execute("DELETE * FROM MomentsValues");
                        //db.Execute("DELETE * FROM Intervals");
                        using (var rec = new RecDao(db, "Intervals"))
                        {
                            rec.AddNew();
                            rec.Put("TimeBegin", _timeBegin);
                            rec.Put("TimeEnd", _timeEnd);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка при подготовке клона", ex);
            }
        }
Ejemplo n.º 7
0
 private void FormGroupReports_Load(object sender, EventArgs e)
 {
     using (var db = new DaoDb(General.ReporterFile))
     {
         using (var sys = new SysTabl(db))
         {
             BeginPeriod.Text = sys.SubValue("FormGroupReports", "BeginPeriod");
             EndPeriod.Text   = sys.SubValue("FormGroupReports", "EndPeriod");
         }
         using (var rec = new RecDao(db, "SELECT * FROM GroupReports ORDER BY GroupCode"))
             while (rec.Read())
             {
                 EditItem(rec);
             }
     }
 }
Ejemplo n.º 8
0
        //Отметка используемых провайдеров и ручного ввода
        private void SaveUsedProviders()
        {
            try
            {
                using (var db = new DaoDb(_projectFile))
                {
                    using (var rec = new RecDao(db, "Providers"))
                        while (rec.Read())
                        {
                            switch (rec.GetString("ProviderType").ToProviderType())
                            {
                            case ProviderType.Communicator:
                                rec.Put("IsUsed", true);
                                break;

                            case ProviderType.Source:
                            case ProviderType.Receiver:
                                rec.Put("IsUsed", UsedProviders.Contains(rec.GetString("ProviderName")));
                                break;

                            case ProviderType.Archive:
                                rec.Put("IsUsed", UsedProviders.Contains("Archive"));
                                break;
                            }
                        }

                    using (var sys = new SysTabl(db))
                    {
                        sys.PutSubValue("ArchiveOptions", "IsAbsolute", IsAbsolute ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsPeriodic", IsPeriodic ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsMoments", IsMoments ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsPrevAbs", IsPrevAbs ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsLastBase", IsLastBase ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsLastHour", IsLastHour ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsLastDay", IsLastDay ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsManyBase", IsManyBase ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsManyHour", IsManyHour ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsManyDay", IsManyDay ? "True" : "False");
                        sys.PutSubValue("ArchiveOptions", "IsManyMoments", IsManyMoments ? "True" : "False");
                    }
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка сохранения признаков использования провайдеров и ручного ввода", ex);
            }
        }
Ejemplo n.º 9
0
 //Загрузить данные подтаблиц всех уровней
 public void LoadValues()
 {
     TablValues = new TablValues(MaxLevel);
     for (int i = 0; i <= MaxLevel; i++)
     {
         using (var rec = new RecDao(_db, "SELECT * FROM " + TablName(i)))
             while (rec.Read())
             {
                 var row = new TablRow(this, i, rec);
                 if (i < MaxLevel)
                 {
                     TablValues.Rows[i].Add(row.Id, row);
                 }
                 var parent = i == 0 ? (SubRows)TablValues : TablValues.Rows[i - 1][row.ParentId];
                 parent.AddRow(row);
                 row.Parent = parent;
             }
     }
 }
Ejemplo n.º 10
0
 private static void CopySubProp(int tid, DaoDb tdb, int id, DaoDb db)
 {
     using (var rec = new RecDao(tdb, "SELECT * FROM SysSubTabl WHERE ParamId=" + tid))
     {
         db.Execute("DELETE * FROM SysSubTabl WHERE ParamId=" + id);
         using (var res = new RecDao(db, "SELECT * FROM SysSubTabl WHERE ParamId=" + id))
             while (rec.Read())
             {
                 res.AddNew();
                 res.Put("ParamId", id);
                 res.Put("SubParamNum", rec.GetInt("SubParamNum"));
                 res.Put("SubParamType", rec.GetString("SubParamType"));
                 res.Put("SubParamName", rec.GetString("SubParamName"));
                 res.Put("SubParamValue", rec.GetString("SubParamValue"));
                 res.Put("SubParamDescription", rec.GetString("SubParamDescription"));
                 res.Put("SubParamTag", rec.GetString("SubParamTag"));
                 res.Put("SubParamRowSource", rec.GetString("SubParamRowSource"));
             }
     }
 }
Ejemplo n.º 11
0
        private void button8_Click(object sender, EventArgs e)
        {
            string   s    = @"d:\Calc\Projects\Курган\Electro.accdb";
            string   sql  = "SELECT Objects.*, Signals.* FROM Objects INNER JOIN Signals ON Objects.ObjectId = Signals.ObjectId";
            var      db   = new DaoDb(s);
            var      recd = new RecDao(db, sql);
            var      reca = new ReaderAdo(db, sql);
            DateTime d    = DateTime.Now;

            while (recd.Read())
            {
                string f = recd.GetString("FullCode");
                f = recd.GetString("CodeSignal");
                f = recd.GetString("NameSignal");
            }
            recd.Dispose();
            MessageBox.Show(DateTime.Now.Subtract(d).ToString());
            reca.Dispose();
            db.Dispose();
        }
Ejemplo n.º 12
0
 //Чтение списка колонок
 private void ReadColumnsList()
 {
     try
     {
         _columnsParams.Clear();
         _columnsVed.Clear();
         using (var rec = new RecDao(_project.File, "SELECT * FROM VedColumns " + (_allTasks ? "" : ("WHERE Task='" + _task + "'")) + " ORDER BY ColumnNum"))
         {
             while (rec.Read())
             {
                 var col = new VedColumn(rec);
                 _columns.Add(col);
                 if (col.SourceType == ColumnSourceType.ParamChar ||
                     col.SourceType == ColumnSourceType.SignalChar ||
                     col.SourceType == ColumnSourceType.ResultValue)
                 {
                     _columnsParams.Add(col.Code, col);
                 }
                 if ((col.SourceType == ColumnSourceType.ParamValue ||
                      col.SourceType == ColumnSourceType.SubValue) &&
                     (col.LinVedView != VedView.None || col.GroupVedView != VedView.None))
                 {
                     _columnsVed.Add(col.Code, col);
                 }
             }
             if (!_task.IsEmpty())
             {
                 using (var rect = new RecDao(rec.DaoDb, "SELECT Tasks.TaskDescription, Tasks.TaskTag FROM Tasks WHERE Task='" + _task + "'"))
                     if (rect.HasRows())
                     {
                         _taskDescription = rect.GetString("TaskDescription");
                         _taskTag         = rect.GetString("TaskTag");
                     }
             }
         }
     }
     catch (Exception ex)
     {
         AddError("Ошибка загрузки списка колонок", ex, "", _project.Code);
     }
 }
Ejemplo n.º 13
0
        //Загрузка параметров из шаблона
        private void LoadParams()
        {
            AddEvent("Загрузка генерирующих параметров");
            var parsingCondition = new ParsingCondition();
            var parsingGenerator = new ParsingGenerator();

            using (var rec = new RecDao(_templateFile, "SELECT * FROM CalcParams WHERE GenOn=True"))
                using (var recs = new RecDao(rec.DaoDb, "SELECT CalcSubParams.* FROM CalcSubParams INNER JOIN CalcParams ON CalcParams.CalcParamId = CalcSubParams.OwnerId WHERE (CalcParams.GenOn = True) AND (CalcSubParams.GenOn = True)"))
                {
                    while (rec.Read())
                    {
                        var par = new GenParam(rec, parsingCondition, parsingGenerator);
                        Params.Add(par.CalcParamId, par);
                    }
                    while (recs.Read())
                    {
                        var par   = new GenSubParam(recs, parsingCondition, parsingGenerator);
                        var owner = Params[par.OwnerId];
                        owner.SubParams.Add(par);
                        par.Owner = owner;
                    }
                }
        }
Ejemplo n.º 14
0
        //Список совместимых кодов провайдеров для выбранного кода провайдера
        public static List <string> JointProviderCodes(this string code)
        {
            var list = new List <string> {
                code
            };

            using (var rec = new RecDao(Different.GetInfoTaskDir() + @"General\Config.accdb", "SysTabl"))
            {
                if (code == "CloneSource")
                {
                    while (rec.Read())
                    {
                        if (rec.GetString("ParamValue") == "Источник" && rec.GetString("ParamName") != "CloneSource")
                        {
                            list.Add(rec.GetString("ParamName"));
                        }
                    }
                }
                else
                {
                    rec.FindFirst("ParamName", code);
                    if (!rec.NoMatch())
                    {
                        var set = rec.GetString("ParamTag").ToPropertyDicS()["JointProviders"].ToPropertyHashSet();
                        foreach (var c in set.Values)
                        {
                            rec.FindFirst("ParamName", c);
                            if (!rec.NoMatch())
                            {
                                list.Add(c);
                            }
                        }
                    }
                }
            }
            return(list);
        }
Ejemplo n.º 15
0
        //Запись используемых сигналов в SignalsInUse
        private void SaveInUse()
        {
            try
            {
                using (var db = new DaoDb(_projectFile))
                {
                    var old = new SetS();
                    using (var rec = new RecDao(db, "SignalsInUse"))
                    {
                        while (rec.Read())
                        {
                            var code = rec.GetString("FullCode");
                            if ((Signals.ContainsKey(code) && Signals[code].InUse) || HandSignals.ContainsKey(code))
                            {
                                old.Add(code);
                                rec.Put("Del", false);
                            }
                            else
                            {
                                rec.Put("Del", true);
                            }
                        }
                    }
                    db.Execute("DELETE * FROM SignalsInUse WHERE Del=True");
                    var add = new SetS();
                    var use = from s in SignalsList where s.InUse select s;
                    SignalsInUseCount = use.Count();
                    foreach (var s in use)
                    {
                        if (!old.Contains(s.FullCode))
                        {
                            add.Add(s.FullCode);
                        }
                        if (s.InUseSource)
                        {
                            UsedProviders.Add(s.SourceName);
                        }
                        if (s.InUseReceiver)
                        {
                            UsedProviders.Add(s.ReceiverName);
                        }
                    }
                    if (HandSignals.Count > 0 && HandInputSource != null)
                    {
                        UsedProviders.Add(HandInputSource);
                    }
                    foreach (var hand in HandSignals.Values)
                    {
                        if (!old.Contains(hand.FullCode))
                        {
                            add.Add(hand.FullCode);
                        }
                    }

                    using (var rec = new RecDao(db, "SignalsInUse"))
                    {
                        while (rec.Read())
                        {
                            var    s   = rec.GetString("FullCode");
                            Signal sig = Signals.ContainsKey(s) ? Signals[s] : HandSignals[s];
                            sig.ToRecordset(rec, false);
                        }
                        foreach (var s in add.Keys)
                        {
                            Signal sig = Signals.ContainsKey(s) ? Signals[s] : HandSignals[s];
                            sig.ToRecordset(rec, true);
                        }
                    }
                    using (var rec = new RecDao(db, "GraficsList"))
                        while (rec.Read())
                        {
                            rec.Put("UsedUnits", UsingParamsString(Grafics[rec.GetString("Code")].UsingParams));
                        }
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка сохранения сигналов или графиков", ex);
            }
        }
Ejemplo n.º 16
0
        //Запись в таблицу PrevParams
        private void SavePrevs()
        {
            try
            {
                using (var db = new DaoDb(_projectFile))
                {
                    var old = new SetS();
                    var add = new SetS();
                    using (var rec = new RecDao(db, "PrevParams"))
                        while (rec.Read())
                        {
                            var code = rec.GetString("FullCode");
                            if (Prevs.ContainsKey(code) && Prevs[code].Id != 0)
                            {
                                old.Add(code);
                                rec.Put("Del", false);
                            }
                            else
                            {
                                rec.Put("Del", true);
                            }
                        }
                    db.Execute("DELETE * FROM PrevParams WHERE Del=True");

                    foreach (var prev in Prevs.Keys)
                    {
                        if (!old.Contains(prev))
                        {
                            add.Add(prev);
                        }
                    }
                    if (Prevs.Count > 0)
                    {
                        using (var rec = new RecDao(db, "PrevParams"))
                        {
                            while (rec.Read())
                            {
                                Prevs[rec.GetString("FullCode")].ToRecordset(rec, false);
                            }
                            foreach (var p in add.Keys)
                            {
                                Prevs[p].ToRecordset(rec, true);
                            }
                        }
                    }

                    foreach (var p in Prevs.Values)
                    {
                        IsPrevAbs     |= p.PrevAbs;
                        IsLastBase    |= p.LastBase;
                        IsLastHour    |= p.LastHour;
                        IsLastDay     |= p.LastDay;
                        IsManyBase    |= p.ManyBase;
                        IsManyHour    |= p.ManyHour;
                        IsManyDay     |= p.ManyDay;
                        IsManyMoments |= p.ManyMoments;
                    }
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка сохранения параметров фунций Пред", ex);
            }
        }
Ejemplo n.º 17
0
        //Получает в память список актуальный список параметров из файла данных, проекта и архива и обновляет список параметров в файле данных
        //Возвращает true, если параметры были обновлены
        public bool UpdateParams()
        {
            if (DataChangeTime >= ProjectChangeTime && DataChangeTime >= ArchiveChangeTime)
            {
                return(false);
            }
            var dataParams    = new DicS <ArchiveParam>();
            var projectParams = new DicS <ArchiveParam>();
            var archiveParams = new DicS <ArchiveParam>();

            try
            {
                if (!File.IsEmpty())
                {
                    Book.AddEvent("Получение списка параметров из проекта", CodeFinal);
                    const string stSql = "SELECT CalcParamsArchive.FullCode As Code, CalcParams.Code AS CodeParam, CalcSubParams.Code AS CodeSubParam, CalcParams.Name, CalcSubParams.Name AS SubName, " +
                                         "CalcParamsArchive.DataType, CalcParams.CalcParamType, CalcParamsArchive.SuperProcessType, CalcParams.Comment, CalcSubParams.Comment AS SubComment, " +
                                         "CalcParamsArchive.Units, CalcParams.Task, CalcParamsArchive.Min, CalcParamsArchive.Max, CalcParamsArchive.DecPlaces, CalcParams.Tag " +
                                         "FROM CalcParams INNER JOIN (CalcSubParams RIGHT JOIN CalcParamsArchive ON CalcSubParams.CalcParamId = CalcParamsArchive.CalcSubParamId) ON CalcParams.CalcParamId = CalcParamsArchive.CalcParamId;";
                    using (var rec = new ReaderAdo(File, stSql))
                        while (rec.Read())
                        {
                            var ap = new ArchiveParam(rec);
                            projectParams.Add(ap.FullCode, ap);
                        }

                    if (CalcMode == CalcModeType.Internal)
                    {
                        Book.AddEvent("Получение параметров ручного ввода из проекта", CodeFinal);
                        using (var rec = new ReaderAdo(File, "SELECT CalcParams.Code, CalcParams.Code AS CodeParam, CalcParams.Name, CalcParams.ResultType AS DataType, CalcParams.Units, CalcParams.Task, CalcParams.CalcParamType, CalcParams.Comment, CalcParams.SuperProcessType, CalcParams.Min, CalcParams.Max, CalcParams.DecPlaces, CalcParams.Tag " +
                                                       "FROM CalcParams WHERE CalcParamType Is Not Null"))
                            while (rec.Read())
                            {
                                var ap = new ArchiveParam(rec);
                                projectParams.Add(ap.FullCode, ap);
                            }
                    }
                }
                if (Archive != null && CalcMode != CalcModeType.Internal)
                {
                    Book.AddEvent("Получение списка параметров из архива", CodeFinal);
                    foreach (var ap in Archive.ReadParams(Code, ReportType.Calc))
                    {
                        archiveParams.Add(ap.FullCode, ap);
                    }
                }

                var dic1 = ProjectChangeTime >= ArchiveChangeTime ? projectParams : archiveParams;
                var dic2 = ProjectChangeTime < ArchiveChangeTime ? projectParams : archiveParams;

                Book.AddEvent("Обновление параметров в файле данных", CodeFinal);
                using (var rec = new RecDao(Book.DataFile, "SELECT * FROM CalcParams WHERE Project='" + CodeFinal + "'"))
                {
                    while (rec.Read())
                    {
                        var ap = new ArchiveParam(rec);
                        dataParams.Add(ap.FullCode, ap);
                        if (!dic1.ContainsKey(ap.FullCode) && !dic2.ContainsKey(ap.FullCode))
                        {
                            rec.Put("SysField", "Del");
                        }
                        else
                        {
                            rec.Put("SysField", "");
                            if (dic1.ContainsKey(ap.FullCode))
                            {
                                dic1[ap.FullCode].ToRecordset(rec, CodeFinal);
                            }
                            else
                            {
                                dic2[ap.FullCode].ToRecordset(rec, CodeFinal);
                            }
                            rec.Put("FromProject", projectParams.ContainsKey(ap.FullCode));
                            rec.Put("FromArchive", archiveParams.ContainsKey(ap.FullCode));
                        }
                    }

                    Book.AddEvent("Добавление недостающих параметров в файл данных", CodeFinal);
                    foreach (var ap in dic1.Values)
                    {
                        if (!dataParams.ContainsKey(ap.FullCode))
                        {
                            dataParams.Add(ap.FullCode, ap);
                            ap.ToRecordset(rec, CodeFinal, true);
                            rec.Put("FromProject", projectParams.ContainsKey(ap.FullCode));
                            rec.Put("FromArchive", archiveParams.ContainsKey(ap.FullCode));
                        }
                    }
                    foreach (var ap in dic2.Values)
                    {
                        if (!dataParams.ContainsKey(ap.FullCode))
                        {
                            ap.ToRecordset(rec, CodeFinal, true);
                            rec.Put("FromProject", projectParams.ContainsKey(ap.FullCode));
                            rec.Put("FromArchive", archiveParams.ContainsKey(ap.FullCode));
                        }
                    }

                    using (var rep = new RecDao(rec.DaoDb, "SELECT LastChange FROM Projects WHERE (ProjectCode2='" + CodeFinal + "') OR (ProjectCode2 Is Null AND Project = '" + CodeFinal + "')"))
                        rep.Put("LastChange", ProjectChangeTime >= ArchiveChangeTime ? ProjectChangeTime : ArchiveChangeTime);
                }
            }
            catch (Exception ex)
            {
                Book.AddError("Ошибка при обновлении спиcка параметров", ex, CodeFinal);
            }
            return(true);
        }
Ejemplo n.º 18
0
        //Компиляция проекта, возвращает количество ошибок компиляции
        public string CompileProject()
        {
            //OnlyOn = true;
            CountsToZero();
            if (State == State.Project || State == State.Empty)//Если не загружены, то загружаем сигналы
            {
                string s = LoadSignals();
                if (s != "")
                {
                    return(s);
                }
            }
            else
            {
                foreach (var sig in SignalsList)
                {
                    sig.InUse         = false;
                    sig.InUseSource   = false;
                    sig.InUseReceiver = false;
                }
            }
            StartAtom(Atom.CompileProject);
            if (State == State.Closed)
            {
                AddError("Копилятор уже был закрыт");
            }
            else
            {
                try
                {
                    //Обнуления поля Expr и т.п.
                    using (var daodb = new DaoDb(_projectFile))
                    {
                        //daodb.Execute("UPDATE CalcParams SET CalcParams.Expr = Null, CalcParams.ErrMess = Null, CalcParams.UsedUnits = Null, CalcParams.CalcNumber = 0;");
                        foreach (string tab in new[] { "CalcParams", "CalcSubParams" })
                        {
                            using (var rec = new RecDao(daodb, tab))
                                while (rec.Read())
                                {
                                    rec.Put("Expr", (string)null);
                                    try { rec.Put("UsedUnits", (string)null); } catch { }
                                    rec.Put("CalcNumber", 0);
                                    rec.Put("ErrMess", (string)null);
                                    rec.Update();
                                }
                        }
                        CalcParams.Clear();
                        CalcParamsId.Clear();
                        CalcParamsAll.Clear();
                        Grafics.Clear();
                        ArchiveParams.Clear();
                        Prevs.Clear();
                        HandSignals.Clear();
                        CalcParamNumber = 0;

                        Procent = 10;
                        AddEvent("Загрузка графиков");
                        using (var rec = new RecDao(daodb, "SELECT GraficsList.Code, GraficsList.Dimension FROM GraficsList"))
                            while (rec.Read())
                            {
                                var gr = new Grafic(rec.GetString("Code"), rec.GetInt("Dimension"));
                                Grafics.Add(gr.Code, gr);
                            }

                        Procent = 15;
                        AddEvent("Загрузка параметров");
                        string spar = OnlyOn ? "WHERE (CalcOn = True) And (TaskOn = True)" : "";
                        using (var rec = new RecDao(daodb, "SELECT CalcParams.* FROM CalcParams " + spar + " ORDER BY CalcParamId"))
                            while (rec.Read())
                            {
                                new CalcParam(rec, this);
                            }

                        Procent = 25;
                        AddEvent("Загрузка подпараметров");
                        string ssub = OnlyOn ? "WHERE (CalcParams.CalcOn = True) And (CalcParams.TaskOn = True) And (CalcSubParams.CalcOn = True)" : "";
                        using (var rec = new RecDao(daodb, "SELECT CalcSubParams.* FROM CalcParams INNER JOIN CalcSubParams ON CalcParams.CalcParamId = CalcSubParams.OwnerId " + ssub))
                            while (rec.Read())
                            {
                                new CalcParam(rec, this, true);
                            }

                        Procent = 35;
                        AddEvent("Разбор выражений");
                        foreach (var cp in CalcParamsId.Values)
                        {
                            cp.Parse();
                        }

                        IsPrevAbs     = false;
                        IsLastBase    = false;
                        IsLastHour    = false;
                        IsLastDay     = false;
                        IsManyBase    = false;
                        IsManyHour    = false;
                        IsManyDay     = false;
                        IsManyMoments = false;

                        Procent = 45;
                        AddEvent("Компиляция выражений");
                        foreach (var cp in CalcParamsId.Values)
                        {
                            if (cp.Stage == CompileStage.NotStarted)
                            {
                                cp.Compile(null);
                            }

                            /*foreach (var d in cp.MethodsId.Values)
                             *  if (d.Stage == CompileStage.NotStarted)
                             *      d.Compile(null);*/
                        }

                        FindCycleLinks();

                        ErrorsCount   = 0;
                        UsedProviders = new SetS();
                        IsAbsolute    = false;
                        IsPeriodic    = false;
                        IsMoments     = false;

                        Procent = 60;
                        AddEvent("Сохранение результатов компиляции параметров");
                        using (var rec = new RecDao(daodb, "SELECT CalcParams.* FROM CalcParams " + spar + " ORDER BY CalcParamId"))
                            SaveCompile(rec, false);

                        Procent = 70;
                        AddEvent("Сохранение результатов компиляции подпараметров");
                        using (var rec = new RecDao(daodb, "SELECT CalcSubParams.* FROM CalcParams INNER JOIN CalcSubParams ON CalcParams.CalcParamId = CalcSubParams.OwnerId " + ssub + " ORDER BY CalcParams.CalcParamId;"))
                            SaveCompile(rec, true);
                    }

                    Procent = 80;
                    AddEvent("Сохранение списка используемых сигналов и графиков");
                    SaveInUse();

                    Procent = 90;
                    AddEvent("Сохранение архивных параметров");
                    SaveArchive();

                    Procent = 96;
                    AddEvent("Сохранение параметров функций Пред");
                    SavePrevs();

                    Procent = 99;
                    SaveUsedProviders();
                    using (var sys = new SysTabl(_projectFile))
                    {
                        sys.PutSubValue("CompileStatus", "LastTimeCompile", DateTime.Now.ToString());
                        sys.PutSubValue("CompileStatus", "ErrorsCount", ErrorsCount.ToString());
                    }
                }
                catch (Exception ex)
                {
                    AddError("Ошибка компилятора", ex);
                }
            }
            return(FinishAtom(State.Compiled, State.Signals, "Проект: " + _code + ";  Ошибок: " + ErrorsCount + ";" + Different.NewLine
                              + "Параметров: " + CalcParamsId.Count + "; Архивных параметров:" + ArchiveParams.Count + ";  Сигналов: " + SignalsInUseCount));
        }
Ejemplo n.º 19
0
        //Проверка таблицы сигналов
        public string CheckSignals(bool onlyInUse = false)
        {
            StartAtom(Atom.CheckSignals);
            CountsToZero();
            var objectsId = new DicI <ObjectSignal>();
            var signals   = new DicS <Signal>();

            _objects.Clear();
            try
            {
                if (State == State.Closed)
                {
                    AddError("Копилятор уже был закрыт");
                }
                else if (State == State.Empty)
                {
                    AddError("Проект не загружен");
                }
                else
                {
                    //using (var reco = new RecDao(_projectFile, "SELECT CodeObject, NameObject, TagObject, ObjectId, CommName, ErrMess FROM Objects ORDER BY ObjectId"))
                    using (var reco = new RecDao(_objectsFile, "SELECT CodeObject, NameObject, TagObject, ObjectId, CommName, ErrMess FROM Objects ORDER BY ObjectId")) //ab\
                    {
                        Procent = 10;
                        while (reco.Read())
                        {
                            var ob = new ObjectSignal(reco, true);
                            objectsId.Add(ob.Id, ob);
                            if (!_objects.ContainsKey(ob.Code))
                            {
                                _objects.Add(ob.Code, ob);
                            }
                            else
                            {
                                ob.ErrMess += "Повтор кода объекта (" + ob.Code + "); ";
                                reco.Put("ErrMess", ob.ErrMess);
                                _objects[ob.Code].ErrMess += "Повтор кода объекта (" + ob.Code + "); ";
                            }
                        }
                        Procent = 25;
                        using (var recs = new RecDao(reco.DaoDb, "SELECT ObjectId, Signals.Default, CodeSignal, NameSignal, Units, Signals.DataType, ConstValue, Signals.SourceName, Signals.ReceiverName, Signals.Inf, Signals.FullCode AS FullCode, Signals.ErrMess" + (!onlyInUse ? "" : ", SignalsInUse.FullCode AS FullCodeInUse")
                                                     + " FROM Signals" + (!onlyInUse ? "" : " LEFT JOIN SignalsInUse ON Signals.FullCode=SignalsInUse.FullCode ")))
                        {
                            Procent = 35;
                            while (recs.Read())
                            {
                                var sig = new Signal(recs, objectsId, true);
                                if (onlyInUse)
                                {
                                    sig.InUse = !recs.GetString("FullCodeInUse").IsEmpty();
                                }
                                objectsId[sig.ObjectId].InUse |= sig.InUse;
                                if (signals.ContainsKey(sig.FullCode))
                                {
                                    sig.ErrMess += "Повтор полного кода сигнала (" + sig.FullCode + "); ";
                                }
                                else
                                {
                                    signals.Add(sig.FullCode, sig);
                                }
                                if (sig.ErrMess != "")
                                {
                                    recs.Put("ErrMess", sig.ErrMess, true);
                                    if (sig.InUse || !onlyInUse)
                                    {
                                        SignalsErrorsCount++;
                                    }
                                    objectsId[sig.ObjectId].ErrorInSignals = true;
                                }
                            }
                        }
                        Procent = 80;
                        reco.MoveFirst();
                        while (!reco.EOF)
                        {
                            var ob = objectsId[reco.GetInt("ObjectId")];
                            if (ob.DefalutsCount == 0)
                            {
                                ob.ErrMess += "Объект не содержит сигналов по умолчанию; ";
                            }
                            if (ob.DefalutsCount >= 2)
                            {
                                ob.ErrMess += "Объект содержит более одного сигнала по умолчанию; ";
                            }
                            if (ob.ErrorInSignals)
                            {
                                ob.ErrMess += "Ошибки в сигналах; ";
                            }
                            if (ob.ErrMess != "")
                            {
                                reco.Put("ErrMess", ob.ErrMess);
                                if (!onlyInUse || ob.InUse)
                                {
                                    ObjectsErrorsCount++;
                                }
                            }
                            reco.MoveNext();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                return(ex.MessageError("Ошибка при проверке сигналов"));
            }
            return(FinishAtom(State.Project, State.Project, "Проект: " + _code + "; Объектов с ошибками: " + ObjectsErrorsCount + "; Сигналов с ошибками: " + SignalsErrorsCount));
        }
Ejemplo n.º 20
0
        public string LoadValues(string stSql, double[] x)
        {
            try
            {
                //обнуляем наш компонент
                foreach (var series in chart1.Series)
                {
                    Colorz.FreeColor(series.Color);
                }
                chart1.Series.Clear();
                //chart1.ChartAreas[0].AxisX.ScaleView.ZoomReset(0);
                //chart1.ChartAreas[0].AxisX.Interval = double.NaN;
                //chart1.ChartAreas[0].AxisY.ScaleView.ZoomReset(0);
                //chart1.ChartAreas[0].AxisY.Interval = double.NaN;
                if (x.Count() == 1)
                {
                    if (!checkBoxAutoScale.Checked)
                    {
                        checkBoxAutoScale.Checked = true;
                    }
                    else
                    {
                        ScaleToAuto();
                    }
                }

                if (stSql == "")
                {
                    stSql = _currentStSQL;
                }
                else
                {
                    _currentStSQL = stSql;
                }

                using (var reader = new RecDao(ConnectionString, stSql))
                {
                    Cursor = Cursors.WaitCursor;
                    while (reader.Read())
                    {
                        string substLegend = "";   //вормируется из таблицы и данного массива
                        string realLegend  = "";   //вормируется из таблицы
                        //считаем, что в x есть элемент хотя бы один (не имеющий смысла), т.к. пустой массив из аксеса плохо передается
                        for (int i = 1; i <= x.Count() - 1; i++)
                        {
                            realLegend  += reader.GetDouble("X" + (_dim - i + 1)) + "-";
                            substLegend += x[i] + "-";
                        }
                        for (int i = 3; i <= _dim - x.Count() + 1; i++)
                        {
                            realLegend  += reader.GetDouble("X" + i) + "-";
                            substLegend += reader.GetDouble("X" + i) + "-";
                        }
                        if (realLegend.Equals(substLegend))    //фильтр строк
                        {
                            if (substLegend.Length > 0)
                            {
                                substLegend = substLegend.Substring(0, substLegend.Length - 1);
                            }
                            //Сформировали легенду для конкретной точки. Дальше фасуем ее по сериям

                            bool chart1SeriesContainsLegend = false;
                            foreach (var se in chart1.Series)
                            {
                                if (se.Name == substLegend)
                                {
                                    chart1SeriesContainsLegend = true;
                                }
                            }
                            if (!chart1SeriesContainsLegend)
                            {
                                var s = new Series
                                {
                                    Name              = substLegend,
                                    BorderWidth       = 2,
                                    MarkerStyle       = MarkerStyle.Circle,
                                    MarkerSize        = 10,
                                    MarkerBorderColor = Color.WhiteSmoke
                                };
                                try
                                {
                                    s.Color = Colorz.GetColor();
                                }
                                catch (Exception ex)
                                {
                                    Error =
                                        new ErrorCommand(
                                            "Не удалось загрузить параметр. Превышено максимальное число параметров (80)",
                                            ex);
                                    return(ErrorMessage);
                                }
                                switch (_graphicType)
                                {
                                case GraphicType.Graphic:
                                    s.ChartType = SeriesChartType.Line;
                                    break;

                                case GraphicType.Graphic0:
                                    s.ChartType = SeriesChartType.StepLine;
                                    break;

                                case GraphicType.Diagram:
                                    s.ChartType = SeriesChartType.Point;
                                    break;
                                }
                                chart1.Series.Add(s);
                            }
                            if (substLegend == "")
                            {
                                substLegend = chart1.Series[0].Name;
                            }
                            chart1.Series[substLegend].Points.AddXY(reader.GetDouble("X2"), reader.GetDouble("X1"));
                        }
                    }
                    Cursor = Cursors.Default;
                }
                //chart1.Refresh();
                //if (!checkBoxAutoScale.Checked) checkBoxAutoScale.Checked = true;
                //else ScaleToAuto();
                return("");
            }
            catch (Exception e)
            {
                Cursor = Cursors.Default;
                Error  = new ErrorCommand("Проблема с загрузкой значений в параметр (LoadValues)", e);
                //MessageBox.Show(e.Message + "\n===\n" + e.StackTrace);
                return(ErrorMessage);
            }
            //throw new Exception();
            //return "";
        }
Ejemplo n.º 21
0
        //Загружет списки проектов и провайдеров для потока
        public void ReadSetup()
        {
            try
            {
                Projects.Clear();
                ProjectsList.Clear();
                foreach (var provider in ProvidersDic.Values)
                {
                    var pi = provider.ProviderInstance;
                    if (pi != null)
                    {
                        if (ApplicationType == ApplicationType.Controller && General.ProvidersQueues.ContainsKey(pi.Hash))
                        {
                            General.ProvidersQueues.Remove(pi.Hash);
                        }
                        pi.Dispose();
                    }
                }

                ProvidersDic.Clear();
                Sources.Clear();
                Receivers.Clear();
                Imitators.Clear();
                Archive   = null;
                ArchivePr = null;

                using (var rec = new RecDao(General.ControllerFile, "SELECT * FROM Projects WHERE ThreadId =" + Id + " ORDER BY Project"))
                    while (rec.Read())
                    {
                        var proj = new Project(rec, this);
                        if (!Command.IsError && !Projects.ContainsKey(proj.Code))
                        {
                            Projects.Add(proj.Code, proj);
                            ProjectsList.Add(proj);
                            AddEvent("Добавлен проект", proj.Code + ", " + proj.File);
                            proj.ReadProviders();//Чтение списка провайдеров
                        }
                    }
                MakeProviders();
                MakeProjectString();
            }
            catch (Exception ex)
            {
                AddError("Ошибка загрузки списка проектов. Необходимо повторить настройку", ex);
            }
            Procent = 70;

            try //Список провайдеров
            {
                AddEvent("Чтение настроек провайдеров");
                using (var rec = new RecDao(General.ControllerFile, "SELECT * FROM Providers WHERE ThreadId =" + Id))
                    while (rec.Read())
                    {
                        var name = rec.GetString("ProviderName");
                        if (ProvidersDic.ContainsKey(name))
                        {
                            var prov = ProvidersDic[name];
                            prov.Code = rec.GetString("ProviderCode");
                            prov.Inf  = rec.GetString("ProviderInf");
                            prov.Otm  = rec.GetBool("Otm");
                        }
                    }
                foreach (var prov in ProvidersDic.Values)
                {
                    if (prov.Otm)
                    {
                        prov.ProviderInstance = General.RunProvider(prov.Code, prov.Name, prov.Inf, this);
                        if (prov.ProviderInstance != null)
                        {
                            switch (prov.Type.ToProviderType())
                            {
                            case ProviderType.Archive:
                                Archive   = (IArchive)prov.ProviderInstance;
                                ArchivePr = prov;
                                break;

                            case ProviderType.Source:
                                Sources.Add(prov.Name, (ISource)prov.ProviderInstance);
                                break;

                            case ProviderType.Imitator:
                                var ims = (Imitator)prov.ProviderInstance;
                                Imitators.Add(prov.Name, ims);
                                var pname = prov.Name.Substring(0, prov.Name.Length - 4);
                                if (Projects.ContainsKey(pname))
                                {
                                    Projects[pname].Imitator = ims;
                                }
                                else
                                {
                                    AddError("Недопустимое имя провайдера имитатора", null, prov.Name);
                                }
                                break;

                            case ProviderType.Receiver:
                                Receivers.Add(prov.Name, (IReceiver)prov.ProviderInstance);
                                break;
                            }
                            if (ApplicationType == ApplicationType.Controller)
                            {
                                string hash = prov.ProviderInstance.Hash;
                                if (!General.ProvidersQueues.ContainsKey(hash))
                                {
                                    General.ProvidersQueues.Add(hash, new Queue <int>());
                                }
                                prov.ProviderQueue = General.ProvidersQueues[hash];
                            }
                        }
                    }
                }
                MakeProviders();
            }
            catch (Exception ex)
            {
                AddError("Ошибка при чтении настроек провайдеров", ex);
            }
        }
Ejemplo n.º 22
0
        //Обновление списка проектов в файле данных отчета
        private IEnumerable <ReportProjectForData> MakeProjectsList()
        {
            AddEvent("Обновление списка проектов");
            var plist = new DicS <ReportProjectForData>();

            try
            {
                using (var rec = new RecDao(General.ReporterFile, "SELECT Reports.Report, Projects.* FROM Reports INNER JOIN Projects ON Reports.ReportId = Projects.ReportId WHERE Report='" + Code + "'"))
                    while (rec.Read())
                    {
                        var p = new ReportProjectForData(this, rec);
                        plist.Add(p.CodeFinal, p);
                    }

                foreach (var pr in SysPage.GetProjects().Values)
                {
                    if (plist.ContainsKey(pr.CodeFinal))
                    {
                        plist[pr.CodeFinal].CalcMode = pr.CalcMode;
                    }
                }
                foreach (var pr in plist.Values)
                {
                    pr.GetChangeTime();
                }
                using (var db = new DaoDb(DataFile))
                {
                    var dic = new SetS();
                    using (var rec = new RecDao(db, "SELECT * FROM Projects"))
                    {
                        while (rec.Read())
                        {
                            var code = rec.GetString("Project");
                            if (code != "Сохранение" && code != "Системные")
                            {
                                if (!plist.ContainsKey(code))
                                {
                                    rec.Put("SysField", "Del");
                                }
                                else
                                {
                                    dic.Add(code);
                                    rec.Put("SysField", "");
                                    plist[code].DataChangeTime = rec.GetTime("LastChange");
                                    plist[code].ToRecordset(rec, false);
                                }
                            }
                        }
                        foreach (var p in plist.Values)
                        {
                            if (!dic.Contains(p.Code))
                            {
                                p.ToRecordset(rec, true);
                            }
                        }
                    }
                    db.Execute("DELETE Cells.* FROM Projects INNER JOIN (CalcParams INNER JOIN Cells ON CalcParams.ParamId = Cells.ParamId) ON Projects.Project = CalcParams.Project WHERE Projects.SysField='Del';");
                    db.Execute("DELETE CalcParams.* FROM Projects INNER JOIN CalcParams ON Projects.Project = CalcParams.Project WHERE Projects.SysField='Del';");
                    db.Execute("DELETE * FROM Projects WHERE Projects.SysField='Del'");
                }
            }
            catch (Exception ex)
            {
                AddError("Ошибка при работе с ReporterData, архивом или файлом данных отчета", ex);
            }
            return(plist.Values);
        }
Ejemplo n.º 23
0
 //Запись значений ручного ввода, beg - начало периода расчета
 public void WriteHandInput(DateTime beg, DateTime en)
 {
     if (IsHandInput)
     {
         try
         {
             Book.AddEvent("Сохрание значений ручного ввода из ячеек", CodeFinal);
             var pars = new DicS <ReportHandParam>();
             foreach (var param in Params.Values)
             {
                 if (param.HandInputCell != null)
                 {
                     pars.Add(param.FullCode,
                              new ReportHandParam(param, GeneralRep.ActiveBook.ValueFromCell(param.HandInputCell)));
                 }
             }
             using (var db = new DaoDb(_handInputFile))
             {
                 using (
                     var rec = new RecDao(db,
                                          "SELECT Objects.CodeObject, MomentsValues.Time FROM (Objects INNER JOIN Signals ON Objects.ObjectId = Signals.ObjectId) INNER JOIN MomentsValues ON Signals.SignalId = MomentsValues.SignalId " +
                                          "WHERE (Time >= " + beg.ToAccessString() + ") AND (Time < " + en.ToAccessString() + ")"))
                     while (rec.Read())
                     {
                         if (pars.ContainsKey(rec.GetString("CodeObject")))
                         {
                             rec.Put("Time", Different.MaxDate);
                         }
                     }
                 using (
                     var rec = new RecDao(db,
                                          "SELECT Objects.CodeObject, MomentsStrValues.Time FROM (Objects INNER JOIN Signals ON Objects.ObjectId = Signals.ObjectId) INNER JOIN MomentsStrValues ON Signals.SignalId = MomentsStrValues.SignalId " +
                                          "WHERE (Time >= " + beg.ToAccessString() + ") AND (Time < " + en.ToAccessString() + ")"))
                     while (rec.Read())
                     {
                         if (pars.ContainsKey(rec.GetString("CodeObject")))
                         {
                             rec.Put("Time", Different.MaxDate);
                         }
                     }
                 db.Execute("DELETE * FROM MomentsValues WHERE Time=" + Different.MaxDate.ToAccessString());
                 db.Execute("DELETE * FROM MomentsStrValues WHERE Time=" + Different.MaxDate.ToAccessString());
                 using (
                     var rec = new RecDao(db,
                                          "SELECT Objects.CodeObject, Objects.ObjectId, Signals.CodeSignal, Signals.SignalId FROM Objects INNER JOIN Signals ON Objects.ObjectId = Signals.SignalId")
                     )
                     while (rec.Read())
                     {
                         var code = rec.GetString("CodeObject");
                         if (pars.ContainsKey(code))
                         {
                             pars[code].ObjectId = rec.GetInt("ObjectId");
                             pars[code].SignalId = rec.GetInt("SignalId");
                         }
                     }
                 using (var reco = new RecDao(db, "Objects"))
                     using (var recs = new RecDao(db, "Signals"))
                         foreach (var param in pars.Values)
                         {
                             if (param.ObjectId == 0)
                             {
                                 var ap  = param.ReportParam.ArchiveParam;
                                 var par = ap.FirstParam;
                                 reco.AddNew();
                                 reco.Put("CodeObject", par.Code);
                                 reco.Put("NameObject", par.Name);
                                 param.ObjectId = reco.GetInt("ObjectId");
                                 reco.Update();
                                 recs.AddNew();
                                 recs.Put("ObjectId", param.ObjectId);
                                 recs.Put("CodeSignal", "Руч");
                                 recs.Put("NameSignal", "Ручной ввод");
                                 recs.Put("FullCode", par.Code + ".Руч");
                                 recs.Put("Default", true);
                                 recs.Put("DataType", ap.DataType.ToRussian());
                                 recs.Put("Units", ap.Units);
                                 recs.Put("Min", ap.Min);
                                 recs.Put("Max", ap.Max);
                                 recs.Put("Active", true);
                                 param.SignalId = recs.GetInt("SignalId");
                                 recs.Update();
                             }
                         }
                 using (var rec = new RecDao(db, "MomentsValues"))
                     using (var recs = new RecDao(db, "MomentsStrValues"))
                         foreach (var param in pars.Values)
                         {
                             if (!param.StringValue.IsEmpty())
                             {
                                 var dt = param.ReportParam.ArchiveParam.DataType;
                                 var r  = dt.LessOrEquals(DataType.Real) ? rec : recs;
                                 r.AddNew();
                                 r.Put("SignalId", param.SignalId);
                                 r.Put("Time", beg);
                                 if (dt.LessOrEquals(DataType.Real))
                                 {
                                     var d = param.StringValue.ToDouble();
                                     if (!double.IsNaN(d))
                                     {
                                         r.Put("Value", d);
                                     }
                                     else
                                     {
                                         r.Put("Value", 0);
                                         r.Put("Nd", 1);
                                     }
                                 }
                                 else if (dt == DataType.String)
                                 {
                                     r.Put("StrValue", param.StringValue);
                                 }
                                 else if (dt == DataType.Time)
                                 {
                                     var t = param.StringValue.ToDateTime();
                                     r.Put("TimeValue", t);
                                     if (t == Different.MinDate)
                                     {
                                         r.Put("Nd", 1);
                                     }
                                 }
                             }
                         }
                 using (var sys = new SysTabl(db, false))
                 {
                     var d = sys.Value("BeginInterval").ToDateTime();
                     if (d == Different.MinDate || d > beg)
                     {
                         sys.PutValue("BeginInterval", beg.ToString());
                     }
                     d = sys.Value("EndInterval").ToDateTime();
                     if (d < beg)
                     {
                         sys.PutValue("EndInterval", beg.ToString());
                     }
                 }
             }
         }
         catch (Exception ex)
         {
             Book.AddError("Ошибка при записи ручного ввода", ex);
         }
     }
 }
Ejemplo n.º 24
0
        private void FormSetupWin_Load(object sender, EventArgs e)
        {
            _setupIsLoaded = false;
            _book          = GeneralRep.ActiveBook;
            _book.AddEvent("Загрузка свойств отчета");
            var sys = _book.SysPage;

            try
            {   //Свойства отчета
                sys.GetControl(CodeReport, "Report");
                sys.GetControl(NameReport, "ReportName");
                sys.GetControl(DescriptionReport, "ReportDescription");
                FileReport.Text = GeneralRep.Application.ActiveWorkbook.FullName;
                sys.GetControl(MonthLength);
                sys.GetControl(DayLength);
                sys.GetControl(HourLength);
                sys.GetControl(MinuteLength);
                sys.GetControl(DayStart);
                sys.GetControl(HourStart);
                sys.GetControl(MinuteStart);
                radioDifferent.Checked           = sys.GetBoolValue("DifferentLength");
                radioLess.Checked                = sys.GetValue("DifferentLength") == "Less";
                radioEquals.Checked              = sys.GetValue("DifferentLength") == "Equals";
                radioNow.Checked                 = sys.GetValue("DefaultPeriod") == "Now";
                radioPrevious.Checked            = sys.GetValue("DefaultPeriod") != "Now";
                DifferentBegin.Checked           = sys.GetBoolValue("DifferentBegin");
                CalcName.Text                    = sys.GetValue("DefaultCalcName");
                AllowProjectsRepetitions.Checked = sys.GetBoolValue("AllowProjectsRepetitions");
            }
            catch (Exception ex)
            {
                GeneralRep.ShowError("Текущий файл не является файлом отчета InfoTask или был поврежден", ex);
                Close();
                return;
            }

            _book.AddEvent("Загрузка настроек из ReporterData");
            Providers.Rows.Clear();
            try
            {
                if (CodeReport.Text != null)
                {
                    using (var db = new DaoDb(General.ReporterFile))
                    {
                        int rid = 0;
                        using (var rec = new RecDao(db, "SELECT * FROM Reports WHERE Report = '" + CodeReport.Text + "'"))
                            if (rec.HasRows())
                            {
                                ThreadId.Text         = rec.GetInt("ThreadId").ToString();
                                UseOneArchive.Checked = rec.GetBool("UseOneArchive");
                                ServerReport.Text     = rec.GetString("ServerReport");
                                var dic = rec.GetString("FormInf").ToPropertyDicS();
                                FormToTemplate.Checked    = dic["FormTo"] == "Template";
                                FormToDir.Checked         = dic["FormTo"] == "Dir";
                                FormToFile.Checked        = dic["FormTo"] == "File";
                                ResultDir.Text            = dic["ResultDir"];
                                ResultFileName.Text       = dic["ResultFileName"];
                                ResultFile.Text           = dic["ResultFile"];
                                AddDateToName.Checked     = dic.GetBool("AddDateToName");
                                DateNameFormat.Text       = dic["DateNameFormat"];
                                AddBeginToName.Checked    = dic.GetBool("AddBeginToName");
                                BeginNameFormat.Text      = dic["BeginNameFormat"];
                                AddEndToName.Checked      = dic.GetBool("AddEndToName");
                                EndNameFormat.Text        = dic["EndNameFormat"];
                                AddCalcNameToName.Checked = dic.GetBool("AddCalcNameToName");
                                AddSheetToName.Checked    = dic.GetBool("AddSheetToName");
                                SetFocusToFormed.Checked  = dic.GetBool("SetFocusToFormed");
                                rid = rec.GetInt("ReportId");
                                _codes.Add("Report_Archive", rec.GetString("CodeArchive"));
                                _infs.Add("Report_Archive", rec.GetString("InfArchive"));
                            }
                        SetFormingEnabled();
                        labelThreadId.Visible = ThreadId.Visible;

                        //Список проектов
                        using (var recr = new RecDao(db, "SELECT * FROM Projects WHERE ReportId =" + rid))
                            foreach (var pr in sys.GetProjects().Values)
                            {
                                int  rn    = Projects.Rows.Add();
                                var  cells = Projects.Rows[rn].Cells;
                                bool b     = recr.FindFirst("Project", pr.Code);
                                if (AllowProjectsRepetitions.Checked)
                                {
                                    b = !pr.Code2.IsEmpty()
                                        ? recr.FindFirst("ProjectCode2", pr.Code2)
                                        : recr.FindFirst("(Project='" + pr.Code + "') AND ((ProjectCode2 = '') OR (ProjectCode2 Is Null))");
                                }
                                if (b)
                                {
                                    recr.GetToDataGrid("ProjectFile", cells);
                                    recr.GetToDataGrid("ProjectName", cells);
                                    if (AllowProjectsRepetitions.Checked)
                                    {
                                        recr.GetToDataGrid("ProjectCode2", cells);
                                    }
                                    cells["Project"] = new DataGridViewTextBoxCell();
                                    if (!UseOneArchive.Checked && pr.CalcMode != CalcModeType.Internal)
                                    {
                                        var acode = recr.GetString("CodeArchive");
                                        var ainf  = recr.GetString("InfArchive");
                                        _codes.Add(pr.CodeFinal + "_Archive", acode);
                                        _infs.Add(pr.CodeFinal + "_Archive", ainf);
                                    }
                                }
                                cells["Project"].Value         = pr.Code;
                                cells["ProjectCalcMode"].Value = pr.CalcMode.ToRussian();
                                if (AllowProjectsRepetitions.Checked)
                                {
                                    cells["ProjectCode2"].Value = pr.Code2;
                                }
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                GeneralRep.ShowError("Неправильный файл ReporterData.accdb", ex);
                Close();
                return;
            }

            _book.AddEvent("Загрузка настроек из ControllerData");
            try
            {
                int tid;
                if (!int.TryParse(ThreadId.Text, out tid))
                {
                    tid = 0;
                }
                if (tid != 0)
                {
                    using (var rect = new RecDao(General.ControllerFile, "SELECT * FROM Threads WHERE ThreadId = " + tid))
                    {
                        IsImit.Checked = rect.GetBool("IsImit");
                        ImitMode.Text  = rect.GetString("ImitMode");
                        using (var rec = new RecDao(rect.DaoDb, "SELECT * FROM Providers WHERE ThreadId=" + tid))
                            while (rec.Read())
                            {
                                string type = rec.GetString("ProviderType");
                                if (type == "Источник" || type == "Приемник" || (type == "Архив" && !UseOneArchive.Checked) || (type == "Имитатор" && IsImit.Checked))
                                {
                                    string name = rec.GetString("ProviderName");
                                    _codes.Add(name, rec.GetString("ProviderCode"));
                                    _infs.Add(name, rec.GetString("ProviderInf"));
                                }
                            }
                    }
                }
            }
            catch (Exception ex)
            {
                GeneralRep.ShowError("Неправильный файл ControllerData.accdb", ex);
            }
            _setupIsLoaded = true;
            UpdateProvidersList();
        }