void Save()
        {
            List <string> ErrorsCounterparties = new List <string>();
            int           counter      = 0;
            int           batchCounter = 0;

            UoW.Session.SetBatchSize(500);
            foreach (var item in CounterpatiesList)
            {
                try {
                    UoW.Save <Counterparty>(item);
                } catch (Exception ex) {
                    ErrorLog("Ошибка сохранения", item.Code1c, string.Format("{0}", item.Id), string.Format("{0}", ex.Message));
                    ErrorsCounterparties.Add(string.Format("{0}", item.Id));
                }
                progressbar.Text = string.Format("Сохранение: {0} из {1}", counter, CounterpatiesList.Count);
                QSMain.WaitRedraw();
                if (batchCounter == 500)
                {
                    UoW.Commit();
                    batchCounter = 0;
                }
                counter++;
                batchCounter++;
            }
            UoW.Commit();

            if (ErrorsCounterparties.Any())
            {
                File.WriteAllLines("ErrorsCounterparties.txt", errorLog);
            }

            progressbar.Text = "Сохранено.";
        }
Ejemplo n.º 2
0
    protected void OnChangeTimeOrderEvent(object sender, CalendarItem.TimeChangedEventArgs arg)
    {
        CalendarItem order = (CalendarItem)sender;

        logger.Info("Изменение времени заказа на {0:d} {1}ч...", arg.Date, arg.Hour);
        string sql = "UPDATE orders SET date = @date, hour = @hour WHERE id = @id;" +
                     " DELETE FROM employee_service_work WHERE id_order_pay in (SELECT id FROM order_pays WHERE order_id = @id)";

        QSMain.CheckConnectionAlive();
        try
        {
            MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB);

            cmd.Parameters.AddWithValue("@date", arg.Date);
            cmd.Parameters.AddWithValue("@hour", arg.Hour);
            cmd.Parameters.AddWithValue("@id", order.id);

            cmd.ExecuteNonQuery();
            logger.Info("Ok");

            if (arg.Date < order.Calendar.StartDate || arg.Date > order.Calendar.StartDate.AddDays(7))
            {
                order.Calendar.RefreshOrders();
            }
        }
        catch (Exception ex)
        {
            QSMain.ErrorMessageWithLog("Ошибка записи заказа!", logger, ex);
        }
    }
Ejemplo n.º 3
0
        public override bool Save()
        {
            string sql;

            if (NewItem)
            {
                sql = "INSERT INTO models (name, mark_id) " +
                      "VALUES (@name, @mark_id)";
            }
            else
            {
                sql = "UPDATE models SET name = @name, mark_id = @mark_id WHERE id = @id";
            }
            logger.Info("Запись модели...");
            QSMain.CheckConnectionAlive();
            try
            {
                MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB);

                cmd.Parameters.AddWithValue("@id", Itemid);
                cmd.Parameters.AddWithValue("@name", entryName.Text);
                cmd.Parameters.AddWithValue("@mark_id", DBWorks.ValueOrNull(Mark_id > 0, Mark_id));

                cmd.ExecuteNonQuery();
                logger.Info("Ok");
                return(true);
            }
            catch (Exception ex)
            {
                QSMain.ErrorMessageWithLog("Ошибка записи модели!", logger, ex);
            }
            return(false);
        }
Ejemplo n.º 4
0
        bool ExecuteBackup()
        {
            logger.Info("Создаем резервную копию базы.");
            if (String.IsNullOrWhiteSpace(entryFileName.Text))
            {
                logger.Warn("Имя файла резервной копии пустое. Отмена.");
                return(true);
            }

            progressbarTotal.Text        = "Создание резервной копии";
            progressbarOperation.Visible = true;
            QSMain.WaitRedraw();

            using (MySqlCommand cmd = QSMain.connectionDB.CreateCommand())
            {
                using (MySqlBackup mb = new MySqlBackup(cmd))
                {
                    var dir = System.IO.Path.GetDirectoryName(entryFileName.Text);

                    if (!Directory.Exists(dir))
                    {
                        Directory.CreateDirectory(dir);
                    }

                    logger.Debug(entryFileName.Text);
                    mb.ExportProgressChanged += Mb_ExportProgressChanged;
                    mb.ExportToFile(entryFileName.Text);
                }
            }

            progressbarOperation.Visible = false;
            return(false);
        }
Ejemplo n.º 5
0
        protected void OnButtonApplyClicked(object sender, EventArgs e)
        {
            var mergeList = Duplicates.Where(x => x.Selected).ToList();

            progressOp.Visible          = true;
            progressOp.Adjustment.Value = 0;
            progressOp.Adjustment.Upper = mergeList.Count;
            progressOp.Text             = "Ищем ссылки...";
            QSMain.WaitRedraw();
            var totalLinks = 0;

            foreach (var dup in mergeList)
            {
                var main = dup.Addresses.First(x => x.IsMain);
                foreach (var deleted in dup.Addresses.Where(x => !x.IsMain && !x.Ignore))
                {
                    totalLinks += ReplaceEntity.ReplaceEverywhere(uow, deleted.Address, main.Address);
                    uow.Delete(deleted.Address);
                    uow.Commit();

                    progressOp.Text = $"Ищем ссылки... Заменено {totalLinks} ссылок.";
                    QSMain.WaitRedraw();
                }

                ObservableDuplicates.Remove(dup);
                progressOp.Adjustment.Value++;
                QSMain.WaitRedraw();
            }
            progressOp.Text = $"Готово. Заменено {totalLinks} ссылок.";
        }
        protected void OnButtonCalculateClicked(object sender, EventArgs e)
        {
            progressbar1.Adjustment.Value = 0;
            progressbar1.Adjustment.Upper = points.Count;
            logger.Info("Рассчитываем расстояния от склада...");
            int notSaved   = 0;
            int calculated = 0;
            int saved      = 0;

            foreach (var point in points)
            {
                point.SetСoordinates(point.Latitude, point.Longitude);
                notSaved++;
                calculated++;
                labelCalculated.LabelProp = calculated.ToString();
                progressbar1.Adjustment.Value++;
                uow.Save(point);
                if (notSaved >= SaveBy || calculated == points.Count)
                {
                    logger.Info("Сохраняем {0} точек в базу...", notSaved);
                    uow.Commit();
                    saved += notSaved;
                    labelSaved.LabelProp = saved.ToString();
                    notSaved             = 0;
                    logger.Info("Рассчитываем расстояния от центра...");
                }
                QSMain.WaitRedraw();
            }
            logger.Info("Ок");
        }
Ejemplo n.º 7
0
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
        this.KeyReleaseEvent += ClipboardWorkaround.HandleKeyReleaseEvent;
        TDIMain.MainNotebook  = tdiMain;
        this.KeyReleaseEvent += TDIMain.TDIHandleKeyReleaseEvent;
        //Передаем лебл
        QSMain.StatusBarLabel = labelStatus;
        this.Title            = MainSupport.GetTitle();
        QSMain.MakeNewStatusTargetForNlog();

        MainSupport.LoadBaseParameters();

        MainUpdater.RunCheckVersion(true, true, true);
        QSMain.CheckServer(this);          // Проверяем настройки сервера

        if (QSMain.User.Login == "root")
        {
            string        Message = "Вы зашли в программу под администратором базы данных. У вас есть только возможность создавать других пользователей.";
            MessageDialog md      = new MessageDialog(this, DialogFlags.DestroyWithParent,
                                                      MessageType.Info,
                                                      ButtonsType.Ok,
                                                      Message);
            md.Run();
            md.Destroy();
            Users WinUser = new Users();
            WinUser.Show();
            WinUser.Run();
            WinUser.Destroy();
            return;
        }

        UsersAction.Sensitive = QSMain.User.Admin;
    }
Ejemplo n.º 8
0
        void RunOneUpdate(UpdateHop updateScript, string operationName)
        {
            logger.Info(operationName);
            textviewLog.Buffer.Text = textviewLog.Buffer.Text + operationName + "\n";

            string sql;

            using (Stream stream = updateScript.Assembly.GetManifestResourceStream(updateScript.Resource))
            {
                if (stream == null)
                {
                    throw new InvalidOperationException(String.Format("Ресурс {0} указанный в обновлениях не найден.", updateScript.Resource));
                }
                StreamReader reader = new StreamReader(stream);
                sql = reader.ReadToEnd();
            }

            int predictedCount = Regex.Matches(sql, ";").Count;

            logger.Debug("Предполагаем наличие {0} команд в скрипте.", predictedCount);

            progressbarTotal.Text             = operationName;
            progressbarTotal.Adjustment.Value = 0;
            progressbarTotal.Adjustment.Upper = predictedCount;
            QSMain.WaitRedraw();

            var script = new MySqlScript(QSMain.connectionDB, sql);

            script.StatementExecuted += Script_StatementExecuted;
            var commands = script.Execute();

            logger.Debug("Выполнено {0} SQL-команд.", commands);
        }
Ejemplo n.º 9
0
        public static bool DeleteObject(Type objectClass, int id, IUnitOfWork uow = null, System.Action beforeDeletion = null)
        {
            try {
                //Здесь так все криво, просто чтобы сделать независимую реализация чисто для совместимости со старым кодом.
                var        builder   = new ContainerBuilder();
                IContainer container = null;
                builder.Register((ctx) => new AutofacViewModelsGtkPageFactory(container)).As <IViewModelsPageFactory>();
                builder.RegisterType <GtkWindowsNavigationManager>().AsSelf().As <INavigationManager>().SingleInstance();
                builder.RegisterType <DeleteEntityGUIService>().AsSelf();
                builder.Register(x => DeleteConfig.Main).AsSelf();
                builder.RegisterType <GtkMessageDialogsInteractive>().As <IInteractiveMessage>();
                builder.RegisterType <GtkQuestionDialogsInteractive>().As <IInteractiveQuestion>();
                builder.RegisterModule(new DeletionAutofacModule());
                builder.Register(ctx => new ClassNamesBaseGtkViewResolver(Assembly.GetAssembly(typeof(DeletionView)))).As <IGtkViewResolver>();
                container = builder.Build();

                var deleteSerive = container.Resolve <DeleteEntityGUIService>();
                var deletion     = deleteSerive.DeleteEntity(objectClass, id, uow, beforeDeletion);

                while (deletion.DeletionExecuted == null)
                {
                    GtkHelper.WaitRedraw();
                    System.Threading.Thread.Sleep(50);
                }

                return(deletion.DeletionExecuted.Value);
            } catch (Exception ex) {
                QSMain.ErrorMessageWithLog("Ошибка удаления.", logger, ex);
                return(false);
            }
        }
Ejemplo n.º 10
0
        public static void Main(string[] args)
        {
            Application.Init();
            QSMain.SubscribeToUnhadledExceptions();
            QSMain.GuiThread = System.Threading.Thread.CurrentThread;
            CreateProjectParam();

            // Создаем окно входа
            Login LoginDialog = new QSProjectsLib.Login();

            LoginDialog.Logo = Gdk.Pixbuf.LoadFromResource("earchive.icons.logo.png");
            LoginDialog.SetDefaultNames("earchive");
            LoginDialog.DefaultLogin  = "******";
            LoginDialog.DefaultServer = "localhost";
            LoginDialog.UpdateFromGConf();

            ResponseType LoginResult;

            LoginResult = (ResponseType)LoginDialog.Run();
            if (LoginResult == ResponseType.DeleteEvent || LoginResult == ResponseType.Cancel)
            {
                return;
            }

            LoginDialog.Destroy();

            //Запускаем программу
            MainWin = new MainWindow();
            if (QSMain.User.Login == "root")
            {
                return;
            }
            MainWin.Show();
            Application.Run();
        }
Ejemplo n.º 11
0
        public List <DeletedItem> GetDeletionList(Type objectClass, int id)
        {
            logger.Debug("Поиск зависимостей для класса {0}...", objectClass);
            var info = DeleteConfig.ClassInfos.Find(i => i.ObjectClass == objectClass);

            if (info == null)
            {
                throw new InvalidOperationException(String.Format("Удаление для класса {0} не настроено в DeleteConfig", objectClass));
            }

            uint entityId = Convert.ToUInt32(id);

            try {
                CheckDlg         = new CheckOperationDlg();
                CheckDlg.Visible = false;
                var self = info.GetSelfEntity(this, entityId);
                PreparedOperation = info.CreateDeleteOperation(self);
                DeletedItems.Add(new DeletedItem {
                    ItemClass = info.ObjectClass,
                    ItemId    = entityId,
                    Title     = self.Title
                });
                countReferenceItems = FillChildOperation(info, PreparedOperation, new TreeIter(), self);
            } catch (Exception ex) {
                QSMain.ErrorMessageWithLog("Ошибка в разборе зависимостей удаляемого объекта.", logger, ex);
            }

            return(DeletedItems);
        }
Ejemplo n.º 12
0
        void UpdateText()
        {
            if (statisticsTxtAction == null)
            {
                return;
            }

            double remainTime = 0;

            if (startLoadTime.HasValue)
            {
                remainTime = (DateTime.Now - startLoadTime.Value).Ticks * ((double)(proposeNeedCached - totalCached) / addedCached);
            }
            statisticsTxtAction.Invoke(
                string.Format(
                    "Уникальных координат: {0}\nРасстояний загружено: {1}\nРасстояний в кеше: {2}/{7}(~{6:P})\nОсталось времени: {9:hh\\:mm\\:ss}\nНовых запрошено: {3}({8})\nОшибок в запросах: {4}\nСреднее скорости: {5:F2}м/с",
                    totalPoints,
                    startCached,
                    totalCached,
                    addedCached,
                    totalErrors,
                    (double)totalMeters / totalSec,
                    (double)totalCached / proposeNeedCached,
                    proposeNeedCached,
                    unsavedItems,
                    TimeSpan.FromTicks((long)remainTime)
                    )
                );
            QSMain.WaitRedraw(100);
        }
Ejemplo n.º 13
0
        void UpdateFields()
        {
            //Получаем таблицу полей
            string sql = String.Format("SELECT {0}.* FROM {0} " +
                                       "WHERE {0}.tablename = @table", CFMain.FieldsInfoTable);

            logger.Info("Обновляем таблицу полей");
            try
            {
                MySqlCommand cmd = new MySqlCommand(sql, (MySqlConnection)QSMain.ConnectionDB);
                cmd.Parameters.AddWithValue("@table", CurrentTable.DBName);
                using (MySqlDataReader rdr = cmd.ExecuteReader())
                {
                    FieldsStore.Clear();
                    while (rdr.Read())
                    {
                        FieldsStore.AppendValues(rdr.GetInt32("id"),
                                                 rdr.GetString("name"),
                                                 rdr.GetString("columnname"));
                    }
                }
                logger.Info("Ок");
            }catch (Exception ex)
            {
                logger.Error(ex, "Ошибка чтения полей {0}!", CurrentTable.DBName);
                QSMain.ErrorMessage(this, ex);
            }
            OnTreeviewFieldsCursorChanged(treeviewFields, EventArgs.Empty);
        }
Ejemplo n.º 14
0
        public static void UpdateFeedReads(NewsFeed feed)
        {
            if (feed.FirstRead)
            {
                throw new InvalidOperationException("Нельзя обновить новый фид с FirstRead = true");
            }
            QSMain.CheckConnectionAlive();
            logger.Info("Обновляем прочитанные новости...");
            string    sql = "UPDATE read_news SET items = @items WHERE id = @id";
            DbCommand cmd = QSMain.ConnectionDB.CreateCommand();

            cmd.CommandText = sql;

            DbParameter param = cmd.CreateParameter();

            param.ParameterName = "@id";
            param.Value         = feed.DataBaseId;
            cmd.Parameters.Add(param);

            param = cmd.CreateParameter();
            param.ParameterName = "@items";
            param.Value         = String.Join(",", feed.ReadItems);
            cmd.Parameters.Add(param);

            cmd.ExecuteNonQuery();
            logger.Info("Ok");
        }
Ejemplo n.º 15
0
        public static void SaveFirstRead()
        {
            NewsFeeds.FindAll(f => f.FirstRead).ForEach(delegate(NewsFeed feed) {
                QSMain.CheckConnectionAlive();
                logger.Info("Сохраняем новый feed({0})...", feed.Title);
                string sql = "INSERT INTO read_news (user_id, feed_id, items) " +
                             "VALUES (@user_id, @feed_id, @items)";
                DbCommand cmd   = QSMain.ConnectionDB.CreateCommand();
                cmd.CommandText = sql;

                DbParameter param   = cmd.CreateParameter();
                param.ParameterName = "@user_id";
                param.Value         = QSMain.User.Id;
                cmd.Parameters.Add(param);

                param = cmd.CreateParameter();
                param.ParameterName = "@feed_id";
                param.Value         = feed.Id;
                cmd.Parameters.Add(param);

                param = cmd.CreateParameter();
                param.ParameterName = "@items";
                param.Value         = String.Join(",", feed.ReadItems);
                cmd.Parameters.Add(param);

                cmd.ExecuteNonQuery();
                feed.FirstRead = false;
            });
        }
Ejemplo n.º 16
0
        protected void OnButtonPrintClicked(object sender, EventArgs e)
        {
            var docCount   = (checkRoute.Active ? 1 : 0) + (checkDailyList.Active ? 1 : 0) + (checkRouteMap.Active ? 1 : 0) + (checkLoadSofiyskaya.Active ? 1 : 0);
            var routeCount = Routes.Count(x => x.Selected);

            progressPrint.Adjustment.Upper = docCount * routeCount;
            progressPrint.Adjustment.Value = 0;
            showDialog = true;
            bool needCommit = false;

            foreach (var route in Routes.Where(x => x.Selected))
            {
                progressPrint.Text = String.Format("Печатаем МЛ {0} - {1}", route.RouteList.Id, route.RouteList.Driver.ShortName);
                QSMain.WaitRedraw();
                bool printed = false;

                if (checkDailyList.Active)
                {
                    PrintDoc(route.RouteList, RouteListPrintableDocuments.DailyList, PageOrientation.Portrait, 1);
                    progressPrint.Adjustment.Value++;
                    QSMain.WaitRedraw();
                }

                if (checkRoute.Active)
                {
                    PrintDoc(route.RouteList, RouteListPrintableDocuments.RouteList, PageOrientation.Landscape, spinRoute.ValueAsInt);
                    progressPrint.Adjustment.Value++;
                    QSMain.WaitRedraw();
                    printed = true;
                }

                if (checkRouteMap.Active)
                {
                    PrintDoc(route.RouteList, RouteListPrintableDocuments.RouteMap, PageOrientation.Portrait, 1);
                    progressPrint.Adjustment.Value++;
                    QSMain.WaitRedraw();
                }

                if (checkLoadSofiyskaya.Active)
                {
                    PrintDoc(route.RouteList, RouteListPrintableDocuments.LoadSofiyskaya, PageOrientation.Portrait, 1);
                    progressPrint.Adjustment.Value++;
                    QSMain.WaitRedraw();
                }

                if (printed)
                {
                    route.RouteList.Printed = true;
                    uow.Save(route.RouteList);
                    needCommit = true;
                }
            }

            if (needCommit)
            {
                uow.Commit();
            }
            progressPrint.Text = "Готово";
        }
Ejemplo n.º 17
0
        protected void OnButtonFineDuplicatesClicked(object sender, EventArgs e)
        {
            progressOp.Visible          = true;
            progressOp.Adjustment.Value = 0;
            progressOp.Text             = "Получаем дубликаты адресов из базы...";
            QSMain.WaitRedraw();

            DeliveryPoint mainPointAlias = null;

            var dublicateSubquery = QueryOver.Of <DeliveryPoint>()
                                    .Where(x => x.Counterparty.Id == mainPointAlias.Counterparty.Id &&
                                           x.Latitude == mainPointAlias.Latitude &&
                                           x.Longitude == mainPointAlias.Longitude &&
                                           x.Id != mainPointAlias.Id &&
                                           (x.Code1c == null || mainPointAlias.Code1c == null || x.Code1c == mainPointAlias.Code1c))
                                    .Select(x => x.Id);

            var list = uow.Session.QueryOver <DeliveryPoint>(() => mainPointAlias)
                       .WithSubquery.WhereExists(dublicateSubquery)
                       .Fetch(x => x.Counterparty).Eager
                       .OrderBy(x => x.Counterparty).Asc
                       .ThenBy(x => x.Latitude).Asc
                       .ThenBy(x => x.Longitude).Asc
                       .List();

            progressOp.Adjustment.Upper = list.Count + 3;
            progressOp.Text             = "Обрабатываем адреса...";
            progressOp.Adjustment.Value++;
            QSMain.WaitRedraw();

            Duplicates = new List <DublicateNode>();
            DublicateNode lastDuplicate = null;

            foreach (var dp in list)
            {
                if (lastDuplicate == null || !lastDuplicate.Compare(dp))
                {
                    lastDuplicate = new DublicateNode();
                    Duplicates.Add(lastDuplicate);
                }
                lastDuplicate.Addresses.Add(new AddressNode(lastDuplicate, dp));
                progressOp.Adjustment.Value++;
                QSMain.WaitRedraw();
            }

            Duplicates.ForEach(x => x.FineMain());
            progressOp.Adjustment.Value++;
            QSMain.WaitRedraw();

            Duplicates = Duplicates.OrderBy(x => x.CounterParty).ThenBy(x => x.FirstAddress1c).ToList();
            progressOp.Adjustment.Value++;
            QSMain.WaitRedraw();

            ObservableDuplicates = new GenericObservableList <DublicateNode>(Duplicates);

            ytreeviewDuplicates.SetItemsSource(ObservableDuplicates);
            progressOp.Visible = false;
        }
Ejemplo n.º 18
0
 void Mb_ExportProgressChanged(object sender, ExportProgressArgs e)
 {
     progressbarOperation.Text             = String.Format("Экспорт {0}", e.CurrentTableName);
     progressbarOperation.Adjustment.Upper = e.TotalRowsInCurrentTable;
     progressbarOperation.Adjustment.Value = e.CurrentRowIndexInCurrentTable;
     progressbarTotal.Adjustment.Upper     = e.TotalTables;
     progressbarTotal.Adjustment.Value     = e.CurrentTableIndex;
     QSMain.WaitRedraw();
 }
Ejemplo n.º 19
0
        void Export_ProgressUpdated(object sender, EventArgs e)
        {
            var export = sender as Export;

            progressbarTotal.Text             = export.CurrentTaskText + export.CurrentStepText;
            progressbarTotal.Adjustment.Upper = export.TotalTasks;
            progressbarTotal.Adjustment.Value = export.CurrentTask;
            UpdateErrors(export.Errors);
            QSMain.WaitRedraw();
        }
Ejemplo n.º 20
0
        private void drawtable()
        {
            string sql = "SELECT COUNT(*) as cnt FROM docs";

            QSMain.CheckConnectionAlive();
            MySqlCommand    cmd = new MySqlCommand(sql, QSMain.connectionDB);
            MySqlDataReader rdr = cmd.ExecuteReader();

            rdr.Read();
            labelCountDoc.Text = String.Format("{0} шт.", rdr.GetInt32("cnt"));
            rdr.Close();

            sql = "SELECT * FROM (SELECT doc_types.name as name, YEAR(docs.create_date) as year, " +
                  "MONTH(docs.create_date) as month, count(images.id/1048576) as col, " +
                  "SUM(images.size/1048576) as sum, AVG(images.size/1048576) as avg FROM images " +
                  "LEFT JOIN docs ON images.doc_id = docs.id " +
                  "LEFT JOIN doc_types ON doc_types.id = docs.type_id " +
                  "GROUP BY doc_types.name , year , month WITH ROLLUP) as tt " +
                  "ORDER BY name, year, month;";
            cmd = new MySqlCommand(sql, QSMain.connectionDB);
            rdr = cmd.ExecuteReader();
            rdr.Read();
            labelCountImag.Text  = String.Format("{0} шт.", rdr.GetInt64("col"));
            labelCommonImag.Text = String.Format("{0:N0} Мб", rdr.GetDouble("sum"));
            labelAvgImag.Text    = String.Format("{0:N} Мб", rdr.GetDouble("avg"));


            TreeIter MainIter = TreeIter.Zero, NowIter = TreeIter.Zero;

            while (rdr.Read())
            {
                string col = String.Format("{0} шт.", rdr.GetInt32("col"));
                string sum = String.Format("{0:N0} Мб", rdr.GetDouble("sum"));
                string avg = String.Format("{0:N} Мб", rdr.GetDouble("avg"));
                if (rdr["month"] == DBNull.Value)
                {
                    if (rdr["year"] == DBNull.Value)
                    {
                        string name = rdr.GetString("name");
                        MainIter = stattree.AppendValues(name, col, sum, avg);
                    }
                    else
                    {
                        string year = rdr.GetInt32("year").ToString();
                        NowIter = stattree.AppendValues(MainIter, year, col, sum, avg);
                    }
                }
                else
                {
                    string month = String.Format("{0:MMMM}", new DateTime(1, rdr.GetInt32("month"), 1));
                    stattree.AppendValues(NowIter, month, col, sum, avg);
                }
            }
            rdr.Close();
        }
Ejemplo n.º 21
0
        private void UpdateProgress(string msg, double progress)
        {
            if (progress == 0)
            {
                progressbar1.Fraction = 0;
            }

            progressbar1.Fraction += progress;
            progressbar1.Text      = msg;
            QSMain.WaitRedraw();
        }
Ejemplo n.º 22
0
 protected void OnSaveActionActivated(object sender, EventArgs e)
 {
     try
     {
         SaveAllDocs();
     }
     catch (Exception ex)
     {
         QSMain.ErrorMessageWithLog(this, "Ошибка в обработке документов", logger, ex);
     }
 }
Ejemplo n.º 23
0
        void OnScanerImageTransfer(object sender, ImageTransferEventArgs e)
        {
            progressScan.Text = "Завершаем загрузку...";
            logger.Debug("ImageTransfer event");

            vimageslist1.Images.Add(e.Image);

            progressScan.Text             = "Ок";
            progressScan.Adjustment.Value = progressScan.Adjustment.Upper;
            QSMain.WaitRedraw();
        }
 void UpdateProgress(double progress, string text)
 {
     if (progress > 1)
     {
         progress = 1;
     }
     progressBar.Fraction = progress;
     progressBar.Text     = $"{(int) (progress * 100)}% - {text} ";
     progressBar.Fraction = progress > 1 ? 1d : progress;
     QSMain.WaitRedraw();
 }
Ejemplo n.º 25
0
        public static bool DeleteObject(string table, int id)
        {
            var delete = new QS.Deletion.DeleteCore();

            try {
                return(delete.RunDeletion(table, id));
            } catch (Exception ex) {
                QSMain.ErrorMessageWithLog("Ошибка удаления.", logger, ex);
                return(false);
            }
        }
Ejemplo n.º 26
0
        public static bool DeleteObject(Type objectClass, int id, IUnitOfWork uow = null, System.Action beforeDeletion = null)
        {
            var delete = uow == null ? new QS.Deletion.DeleteCore() : new QS.Deletion.DeleteCore(uow);

            delete.BeforeDeletion = beforeDeletion;
            try {
                return(delete.RunDeletion(objectClass, id));
            } catch (Exception ex) {
                QSMain.ErrorMessageWithLog("Ошибка удаления.", logger, ex);
                return(false);
            }
        }
Ejemplo n.º 27
0
        void Vadjustment_ValueChanged(object sender, EventArgs e)
        {
            if (takenAll || datatreeChangesets.Vadjustment.Value + datatreeChangesets.Vadjustment.PageSize < datatreeChangesets.Vadjustment.Upper)
            {
                return;
            }

            var lastPos = datatreeChangesets.Vadjustment.Value;

            UpdateJournal(true);
            QSMain.WaitRedraw();
            datatreeChangesets.Vadjustment.Value = lastPos;
        }
Ejemplo n.º 28
0
        public static void Main(string[] args)
        {
            Application.Init();
            QSMain.SubscribeToUnhadledExceptions();
            QSMain.GuiThread = System.Threading.Thread.CurrentThread;
            QSSupportLib.MainSupport.Init();
            CreateProjectParam();
            // Создаем окно входа
            Login LoginDialog = new Login();

            LoginDialog.Logo = Gdk.Pixbuf.LoadFromResource("BioGorod.Icons.logo.png");
            LoginDialog.SetDefaultNames("BioGorod");
            LoginDialog.DefaultLogin  = "******";
            LoginDialog.DefaultServer = "localhost";
            LoginDialog.UpdateFromGConf();

            ResponseType LoginResult;

            LoginResult = (ResponseType)LoginDialog.Run();
            if (LoginResult == ResponseType.DeleteEvent || LoginResult == ResponseType.Cancel)
            {
                return;
            }

            LoginDialog.Destroy();

            //Настройка базы
            CreateBaseConfig();

            //Настрока удаления
            ConfigureDeletion();

            //Настройка карты
            GMap.NET.MapProviders.GMapProvider.UserAgent = String.Format("{0}/{1} used GMap.Net/{2} ({3})",
                                                                         QSSupportLib.MainSupport.ProjectVerion.Product,
                                                                         StringWorks.VersionToShortString(QSSupportLib.MainSupport.ProjectVerion.Version),
                                                                         StringWorks.VersionToShortString(System.Reflection.Assembly.GetAssembly(typeof(GMap.NET.MapProviders.GMapProvider)).GetName().Version),
                                                                         Environment.OSVersion.VersionString
                                                                         );
            GMap.NET.MapProviders.GMapProvider.Language = GMap.NET.LanguageType.Russian;

            //Запускаем программу
            MainWin = new MainWindow();
            QSMain.ErrorDlgParrent = MainWin;
            if (QSMain.User.Login == "root")
            {
                return;
            }
            MainWin.Show();
            Application.Run();
        }
Ejemplo n.º 29
0
        public void GetDocumentInformationByTypeName()
        {
            QSMain.CheckConnectionAlive();
            logger.Info("Запрос типа документа " + TypeName + "...");
            string sql = "SELECT doc_types.* FROM doc_types " +
                         "WHERE doc_types.type_name = @type_name LIMIT 1";
            MySqlDataReader rdr = null;

            try {
                MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB);
                cmd.Parameters.AddWithValue("@type_name", TypeName);
                rdr = cmd.ExecuteReader();

                if (!rdr.Read())
                {
                    return;
                }

                TypeId = rdr.GetInt32("id");

                Name = rdr["name"].ToString();
                if (rdr["table_name"] == DBNull.Value)
                {
                    DBTableExsist = false;
                }
                else
                {
                    DBTableName   = rdr["table_name"].ToString();
                    DBTableExsist = true;
                }

                if (rdr["description"] != DBNull.Value)
                {
                    Description = rdr.GetString("description");
                }

                if (rdr["template"] != DBNull.Value)
                {
                    string str = rdr.GetString("template");
                    Template = RecognizeTemplate.Load(str);
                }

                rdr.Close();
                logger.Info("Ok");
            } catch (Exception ex) {
                logger.Warn(ex, "Ошибка получения информации о типе документа!");
            }
            finally{
                rdr?.Close();
            }
        }
Ejemplo n.º 30
0
        protected void OnButtonDeleteClicked(object sender, EventArgs e)
        {
            treeviewDocs.Selection.GetSelected(out TreeIter iter);
            int itemid = (int)DocsListStore.GetValue(iter, 0);

            string sql = "DELETE FROM docs WHERE id = @id";

            QSMain.CheckConnectionAlive();
            MySqlCommand cmd = new MySqlCommand(sql, QSMain.connectionDB);

            cmd.Parameters.AddWithValue("@id", itemid);
            cmd.ExecuteNonQuery();
            UpdateDocs();
        }