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;
    }
        protected void OnButtonOkClicked(object sender, EventArgs e)
        {
            try
            {
                if (checkCreateBackup.Active)
                {
                    if (ExecuteBackup())
                    {
                        return;
                    }
                }

                logger.Info("Обновляем базу данных до версии {0}", StringWorks.VersionToShortString(updateHop.Destanation));
                logger.Info("Проверяем все ли микро обновления установленны.");
                ExecuteMicroUpdates();

                logger.Info("Устанавливаем основное обновление.");
                RunOneUpdate(updateHop, String.Format("Обновление базы данных до версии {0}",
                                                      StringWorks.VersionToShortString(updateHop.Destanation)
                                                      ));

                if (MainSupport.BaseParameters.All.ContainsKey("micro_updates"))
                {
                    MainSupport.BaseParameters.RemoveParameter(QSMain.ConnectionDB,
                                                               "micro_updates");
                }

                MainSupport.LoadBaseParameters();

                logger.Info("Доустанавливаем микро обновления.");
                ExecuteMicroUpdates();

                progressbarTotal.Adjustment.Value = progressbarTotal.Adjustment.Upper;
                logger.Info("Обновление до версии {0}, завершено.", StringWorks.VersionToShortString(updateHop.Destanation));
                Success = true;
                Respond(Gtk.ResponseType.Ok);
            }
            catch (Exception ex)
            {
                QSMain.ErrorMessageWithLog("Ошибка при обновлении базы..", logger, ex);
                buttonOk.Sensitive = false;
                return;
            }
        }
Exemple #3
0
        public static void TryUpdate()
        {
            logger.Debug(System.Reflection.Assembly.GetCallingAssembly().FullName);
            Version currentDB  = Version.Parse(MainSupport.BaseParameters.Version);
            var     appVersion = MainSupport.ProjectVerion.Version;

            if (currentDB.Major == appVersion.Major && currentDB.Minor == appVersion.Minor)
            {
                return;
            }

            var update = updates.Find(u => u.Source == currentDB);

            if (update != null)
            {
                if (!QSMain.User.Admin)
                {
                    NotAdminErrorAndExit(false, update.Source, update.Destanation);
                }

                var dlg = new DBUpdateProcess(update);
                dlg.Show();
                dlg.Run();
                if (!dlg.Success)
                {
                    Environment.Exit(1);
                }
                dlg.Destroy();

                MainSupport.LoadBaseParameters();
                if (appVersion.Major != update.Destanation.Major && appVersion.Minor != update.Destanation.Minor)
                {
                    TryUpdate();
                }
            }
            else
            {
                logger.Error("Версия базы не соответствует программе, но обновление не найдено");
                ShowErrorAndExit(CheckBaseVersion.TextMessage +
                                 String.Format("\nОбновление базы для версии {0} не поддерживается.", StringWorks.VersionToShortString(currentDB)));
            }
        }
Exemple #4
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            SmsRuConfiguration smsRuConfig;

            try {
                var builder = new ConfigurationBuilder()
                              .AddIniFile(configFile, optional: false);

                var configuration = builder.Build();

                var serviceSection = configuration.GetSection("Service");
                serviceHostName = serviceSection["service_host_name"];
                servicePort     = serviceSection["service_port"];

                var mysqlSection = configuration.GetSection("Mysql");
                mysqlServerHostName = mysqlSection["mysql_server_host_name"];
                mysqlServerPort     = mysqlSection["mysql_server_port"];
                mysqlUser           = mysqlSection["mysql_user"];
                mysqlPassword       = mysqlSection["mysql_password"];
                mysqlDatabase       = mysqlSection["mysql_database"];

                var smsRuSection = configuration.GetSection("SmsRu");

                smsRuConfig =
                    new SmsRuConfiguration(
                        smsRuSection["login"],
                        smsRuSection["password"],
                        smsRuSection["appId"],
                        smsRuSection["partnerId"],
                        smsRuSection["email"],
                        smsRuSection["smsNumberFrom"],
                        smsRuSection["smtpLogin"],
                        smsRuSection["smtpPassword"],
                        smsRuSection["smtpServer"],
                        int.Parse(smsRuSection["smtpPort"]),
                        bool.Parse(smsRuSection["smtpUseSSL"]),
                        bool.Parse(smsRuSection["translit"]),
                        bool.Parse(smsRuSection["test"])
                        );
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            try {
                var conStrBuilder = new MySqlConnectionStringBuilder();
                conStrBuilder.Server   = mysqlServerHostName;
                conStrBuilder.Port     = uint.Parse(mysqlServerPort);
                conStrBuilder.Database = mysqlDatabase;
                conStrBuilder.UserID   = mysqlUser;
                conStrBuilder.Password = mysqlPassword;
                conStrBuilder.SslMode  = MySqlSslMode.None;

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                                .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(db_config,
                                       new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();

                ISmsNotificationRepository smsNotificationRepository = new SmsNotificationRepository();

                SmsRuSendController smsSender = new SmsRuSendController(smsRuConfig);

                newClientInformer = new NewClientSmsInformer(smsSender, smsNotificationRepository);
                newClientInformer.Start();

                BaseParametersProvider parametersProvider = new BaseParametersProvider();
                LowBalanceNotifier     lowBalanceNotifier = new LowBalanceNotifier(smsSender, smsSender, parametersProvider);
                lowBalanceNotifier.Start();

                SmsInformerInstanceProvider serviceStatusInstanceProvider = new SmsInformerInstanceProvider(
                    smsNotificationRepository,
                    new BaseParametersProvider()
                    );
                WebServiceHost smsInformerStatus = new SmsInformerServiceHost(serviceStatusInstanceProvider);
                smsInformerStatus.AddServiceEndpoint(
                    typeof(ISmsInformerService),
                    new WebHttpBinding(),
                    String.Format("http://{0}:{1}/SmsInformer", serviceHostName, servicePort)
                    );
                smsInformerStatus.Open();
                logger.Info("Запущена служба мониторинга отправки смс уведомлений");

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception ex) {
                logger.Fatal(ex);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            try {
                IniConfigSource confFile = new IniConfigSource(configFile);
                confFile.Reload();
                IConfig serviceConfig = confFile.Configs["Service"];
                serviceHostName       = serviceConfig.GetString("service_host_name");
                servicePort           = serviceConfig.GetString("service_port");
                serviceWebPort        = serviceConfig.GetString("service_web_port");
                driverServiceHostName = serviceConfig.GetString("driver_service_host_name");
                driverServicePort     = serviceConfig.GetString("driver_service_port");

                IConfig bitrixConfig = confFile.Configs["Bitrix"];
                baseAddress = bitrixConfig.GetString("base_address");

                IConfig mysqlConfig = confFile.Configs["Mysql"];
                mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name");
                mysqlServerPort     = mysqlConfig.GetString("mysql_server_port", "3306");
                mysqlUser           = mysqlConfig.GetString("mysql_user");
                mysqlPassword       = mysqlConfig.GetString("mysql_password");
                mysqlDatabase       = mysqlConfig.GetString("mysql_database");
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            logger.Info("Запуск службы оплаты заказов по sms");
            try {
                var conStrBuilder = new MySqlConnectionStringBuilder
                {
                    Server   = mysqlServerHostName,
                    Port     = UInt32.Parse(mysqlServerPort),
                    Database = mysqlDatabase,
                    UserID   = mysqlUser,
                    Password = mysqlPassword,
                    SslMode  = MySqlSslMode.None
                };

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var dbConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                               .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                               .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(dbConfig,
                                       new[] {
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();

                ChannelFactory <IAndroidDriverService> channelFactory = new ChannelFactory <IAndroidDriverService>(
                    new BasicHttpBinding(),
                    string.Format("http://{0}:{1}/AndroidDriverService", driverServiceHostName, driverServicePort)
                    );
                IDriverPaymentService driverPaymentService = new DriverPaymentService(channelFactory);
                var paymentSender = new BitrixPaymentWorker(baseAddress);

                SmsPaymentServiceInstanceProvider smsPaymentServiceInstanceProvider = new SmsPaymentServiceInstanceProvider(paymentSender, driverPaymentService);

                ServiceHost smsPaymentServiceHost = new SmsPaymentServiceHost(smsPaymentServiceInstanceProvider);

                ServiceEndpoint webEndPoint = smsPaymentServiceHost.AddServiceEndpoint(
                    typeof(ISmsPaymentService),
                    new WebHttpBinding(),
                    $"http://{serviceHostName}:{serviceWebPort}/SmsPaymentWebService"
                    );
                WebHttpBehavior httpBehavior = new WebHttpBehavior();
                webEndPoint.Behaviors.Add(httpBehavior);

                smsPaymentServiceHost.AddServiceEndpoint(
                    typeof(ISmsPaymentService),
                    new BasicHttpBinding(),
                    $"http://{serviceHostName}:{servicePort}/SmsPaymentService"
                    );
                smsPaymentServiceHost.Description.Behaviors.Add(new PreFilter());

                smsPaymentServiceHost.Open();
                logger.Info("Server started.");

                (smsPaymentServiceInstanceProvider.GetInstance(null) as ISmsPaymentService)?.SynchronizePaymentStatuses();

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
Exemple #6
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            IConfig driverServiceConfig;
            IConfig firebaseConfig;

            try {
                IniConfigSource driverConfFile = new IniConfigSource(driverConfigFile);
                driverConfFile.Reload();
                driverServiceConfig = driverConfFile.Configs["Service"];
                firebaseConfig      = driverConfFile.Configs["Firebase"];

                IConfig mysqlConfig = driverConfFile.Configs["Mysql"];
                mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name");
                mysqlServerPort     = mysqlConfig.GetString("mysql_server_port", "3306");
                mysqlUser           = mysqlConfig.GetString("mysql_user");
                mysqlPassword       = mysqlConfig.GetString("mysql_password");
                mysqlDatabase       = mysqlConfig.GetString("mysql_database");
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            try {
                var conStrBuilder = new MySqlConnectionStringBuilder();
                conStrBuilder.Server   = mysqlServerHostName;
                conStrBuilder.Port     = UInt32.Parse(mysqlServerPort);
                conStrBuilder.Database = mysqlDatabase;
                conStrBuilder.UserID   = mysqlUser;
                conStrBuilder.Password = mysqlPassword;
                conStrBuilder.SslMode  = MySqlSslMode.None;

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                                .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(db_config,
                                       new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка в настройке подключения к БД.");
            }


            try {
                DriverServiceStarter.StartService(driverServiceConfig, firebaseConfig, new BaseParametersProvider());

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
Exemple #7
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;
            try {
                IniConfigSource configFile = new IniConfigSource(ConfigFile);
                configFile.Reload();
                IConfig config = configFile.Configs ["General"];
                server = config.GetString("server");
                port   = config.GetString("port", "3306");
                user   = config.GetString("user");
                pass   = config.GetString("password");
                db     = config.GetString("database");
                firebaseServerApiToken = config.GetString("server_api_token");
                firebaseSenderId       = config.GetString("firebase_sender");
                servicePort            = config.GetString("service_port");
                serviceHostName        = config.GetString("service_host_name");

                OsmService.ConfigureService(configFile);
            } catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            WebServiceHost OsmHost = new WebServiceHost(typeof(OsmService));

            logger.Info(String.Format("Создаем и запускаем службы..."));
            try {
                var conStrBuilder = new MySqlConnectionStringBuilder();
                conStrBuilder.Server   = server;
                conStrBuilder.Port     = UInt32.Parse(port);
                conStrBuilder.Database = db;
                conStrBuilder.UserID   = user;
                conStrBuilder.Password = pass;
                conStrBuilder.SslMode  = MySqlSslMode.None;

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                                .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(db_config,
                                       new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QSBanks.QSBanksMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QSContacts.QSContactsMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(EmailService.Email))
                });

                MainSupport.LoadBaseParameters();

                FCMHelper.Configure(firebaseServerApiToken, firebaseSenderId);

                ServiceHost    ChatHost          = new ServiceHost(typeof(ChatService));
                ServiceHost    AndroidDriverHost = new ServiceHost(typeof(AndroidDriverService));
                ServiceHost    EmailSendingHost  = new ServiceHost(typeof(EmailService.EmailService));
                WebServiceHost MailjetEventsHost = new WebServiceHost(typeof(EmailService.EmailService));
                WebServiceHost MobileHost        = new WebServiceHost(typeof(MobileService));

                ChatHost.AddServiceEndpoint(
                    typeof(IChatService),
                    new BasicHttpBinding(),
                    String.Format("http://{0}:{1}/ChatService", serviceHostName, servicePort)
                    );
                AndroidDriverHost.AddServiceEndpoint(
                    typeof(IAndroidDriverService),
                    new BasicHttpBinding(),
                    String.Format("http://{0}:{1}/AndroidDriverService", serviceHostName, servicePort)
                    );
                EmailSendingHost.AddServiceEndpoint(
                    typeof(IEmailService),
                    new BasicHttpBinding(),
                    String.Format("http://{0}:{1}/EmailService", serviceHostName, servicePort)
                    );
                MailjetEventsHost.AddServiceEndpoint(
                    typeof(IMailjetEventService),
                    new WebHttpBinding(),
                    String.Format("http://{0}:{1}/Mailjet", serviceHostName, servicePort)
                    );

                MobileService.BaseUrl = String.Format("http://{0}:{1}/Mobile", serviceHostName, servicePort);
                MobileHost.AddServiceEndpoint(
                    typeof(IMobileService),
                    new WebHttpBinding(),
                    MobileService.BaseUrl
                    );

                OsmWorker.ServiceHost = serviceHostName;
                OsmWorker.ServicePort = Int32.Parse(servicePort);
                OsmHost.AddServiceEndpoint(typeof(IOsmService), new WebHttpBinding(), OsmWorker.ServiceAddress);

                //FIXME Тут добавлен без дебага, потому что без него не работает отдача изображений в потоке. Метод Stream GetImage(string filename)
                // Просто не смог быстро разобраться. А конкретнее нужна строка reply = TraceMessage (reply.CreateBufferedCopy (int.MaxValue), Action.Send);
                // видимо она как то обрабатывает сообщение.
                MobileHost.Description.Behaviors.Add(new PreFilter());

                                #if DEBUG
                ChatHost.Description.Behaviors.Add(new PreFilter());
                AndroidDriverHost.Description.Behaviors.Add(new PreFilter());
                EmailSendingHost.Description.Behaviors.Add(new PreFilter());
                MailjetEventsHost.Description.Behaviors.Add(new PreFilter());
                OsmHost.Description.Behaviors.Add(new PreFilter());
                                #endif

                ChatHost.Open();
                AndroidDriverHost.Open();
                EmailSendingHost.Open();
                MailjetEventsHost.Open();
                MobileHost.Open();
                OsmHost.Open();

                //Запускаем таймеры рутины
                OrderRoutineTimer          = new System.Timers.Timer(120000);        //2 минуты
                OrderRoutineTimer.Elapsed += OrderRoutineTimer_Elapsed;
                OrderRoutineTimer.Start();
                TrackRoutineTimer          = new System.Timers.Timer(30000);        //30 секунд
                TrackRoutineTimer.Elapsed += TrackRoutineTimer_Elapsed;
                TrackRoutineTimer.Start();

                logger.Info("Server started.");

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            } catch (Exception e) {
                logger.Fatal(e);
            } finally {
                if (OsmHost.State == CommunicationState.Opened)
                {
                    OsmHost.Close();
                }

                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
Exemple #8
0
        public static void Main(string[] args)
        {
            CultureInfo.CurrentCulture = CultureInfo.CreateSpecificCulture("ru-RU");
            Application.Init();
            QSMain.GuiThread = System.Threading.Thread.CurrentThread;
            var appInfo = new ApplicationInfo();

            #region Первоначальная настройка обработки ошибок
            SingletonErrorReporter.Initialize(ReportWorker.GetReportService(), appInfo, new LogService(), null, false, null);
            var errorMessageModelFactory = new DefaultErrorMessageModelFactory(SingletonErrorReporter.Instance, null, null);
            var exceptionHandler         = new DefaultUnhandledExceptionHandler(errorMessageModelFactory, appInfo);

            exceptionHandler.SubscribeToUnhandledExceptions();
            exceptionHandler.GuiThread = System.Threading.Thread.CurrentThread;
            MainSupport.HandleStaleObjectStateException = EntityChangedExceptionHelper.ShowExceptionMessage;
            #endregion

            //FIXME Удалить после того как будет удалена зависимость от библиотеки QSProjectLib
            QSMain.ProjectPermission = new System.Collections.Generic.Dictionary <string, UserPermission>();

            CreateProjectParam();
            ConfigureViewModelWidgetResolver();
            ConfigureJournalColumnsConfigs();

            QSMain.SetupFromArgs(args);
            QS.Project.Search.GtkUI.SearchView.QueryDelay = 1500;

            Gtk.Settings.Default.SetLongProperty("gtk-button-images", 1, "");
            // Создаем окно входа
            Login LoginDialog = new Login();
            LoginDialog.Logo = Gdk.Pixbuf.LoadFromResource("Vodovoz.icons.logo.png");
            LoginDialog.SetDefaultNames("Vodovoz");
            LoginDialog.DefaultLogin  = "******";
            LoginDialog.DefaultServer = "sql.vod.qsolution.ru";
            LoginDialog.UpdateFromGConf();

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

            LoginDialog.Destroy();

            PerformanceHelper.StartMeasurement("Замер запуска приложения");
            GetPermissionsSettings();
            //Настройка базы
            CreateBaseConfig();
            PerformanceHelper.AddTimePoint(logger, "Закончена настройка базы");
            VodovozGtkServicesConfig.CreateVodovozDefaultServices();

            MainSupport.LoadBaseParameters();
            ParametersProvider.Instance.RefreshParameters();

            #region Настройка обработки ошибок c параметрами из базы и сервисами
            var baseParameters = new BaseParametersProvider();
            SingletonErrorReporter.Initialize(
                ReportWorker.GetReportService(),
                appInfo,
                new LogService(),
                LoginDialog.BaseName,
                LoginDialog.BaseName == baseParameters.GetDefaultBaseForErrorSend(),
                baseParameters.GetRowCountForErrorLog()
                );

            var errorMessageModelFactory2 = new DefaultErrorMessageModelFactory(SingletonErrorReporter.Instance, ServicesConfig.UserService, UnitOfWorkFactory.GetDefaultFactory);
            exceptionHandler.InteractiveService       = ServicesConfig.InteractiveService;
            exceptionHandler.ErrorMessageModelFactory = errorMessageModelFactory2;
            //Настройка обычных обработчиков ошибок.
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.MySqlException1055OnlyFullGroupBy);
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.MySqlException1366IncorrectStringValue);
            exceptionHandler.CustomErrorHandlers.Add(CommonErrorHandlers.NHibernateFlushAfterException);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.NHibernateStaleObjectStateExceptionException);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.MySqlExceptionConnectionTimeout);
            exceptionHandler.CustomErrorHandlers.Add(ErrorHandlers.MySqlExceptionAuth);

            #endregion

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

            DatePicker.CalendarFontSize      = 16;
            DateRangePicker.CalendarFontSize = 16;

            OsmWorker.ServiceHost = "osm.vod.qsolution.ru";
            OsmWorker.ServicePort = 7073;

            QS.Osm.Osrm.OsrmMain.ServerUrl = "http://osrm.vod.qsolution.ru:5000";

            PerformanceHelper.StartPointsGroup("Главное окно");

            MainSupport.TestVersion(null);        //Проверяем версию базы
            QSMain.CheckServer(null);             // Проверяем настройки сервера

            PerformanceHelper.AddTimePoint("Закончена загрузка параметров базы и проверка версии.");

            AutofacClassConfig();
            PerformanceHelper.AddTimePoint("Закончена настройка AutoFac.");
            if (QSMain.User.Login == "root")
            {
                string        Message = "Вы зашли в программу под администратором базы данных. У вас есть только возможность создавать других пользователей.";
                MessageDialog md      = new MessageDialog(null, DialogFlags.Modal,
                                                          MessageType.Info,
                                                          ButtonsType.Ok,
                                                          Message);
                md.Run();
                md.Destroy();
                UsersDialog usersDlg = new UsersDialog(ServicesConfig.InteractiveService);
                usersDlg.Show();
                usersDlg.Run();
                usersDlg.Destroy();
                return;
            }
            else
            {
                if (ChangePassword(LoginDialog.BaseName) && CanLogin())
                {
                    StartMainWindow(LoginDialog.BaseName);
                }
                else
                {
                    return;
                }
            }

            PerformanceHelper.EndPointsGroup();

            PerformanceHelper.AddTimePoint(logger, "Закончен старт SAAS. Конец загрузки.");

            QSSaaS.Session.StartSessionRefresh();

            PerformanceHelper.AddTimePoint(logger, "Закончен старт SAAS. Конец загрузки.");
            PerformanceHelper.Main.PrintAllPoints(logger);

            Application.Run();
            QSSaaS.Session.StopSessionRefresh();
            ClearTempDir();
        }
Exemple #9
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            logger.Info("Чтение конфигурационного файла...");
            IConfig serviceConfig;
            IConfig kassaConfig;

            try {
                IniConfigSource confFile = new IniConfigSource(configFile);
                confFile.Reload();
                serviceConfig   = confFile.Configs["Service"];
                serviceHostName = serviceConfig.GetString("service_host_name");
                servicePort     = serviceConfig.GetString("service_port");

                kassaConfig = confFile.Configs["ModulKassa"];
                IConfig mysqlConfig = confFile.Configs["Mysql"];
                mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name");
                mysqlServerPort     = mysqlConfig.GetString("mysql_server_port", "3306");
                mysqlUser           = mysqlConfig.GetString("mysql_user");
                mysqlPassword       = mysqlConfig.GetString("mysql_password");
                mysqlDatabase       = mysqlConfig.GetString("mysql_database");
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            logger.Info("Настройка подключения к БД...");
            try {
                var conStrBuilder = new MySqlConnectionStringBuilder {
                    Server   = mysqlServerHostName,
                    Port     = UInt32.Parse(mysqlServerPort),
                    Database = mysqlDatabase,
                    UserID   = mysqlUser,
                    Password = mysqlPassword,
                    SslMode  = MySqlSslMode.None
                };

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .ConnectionString(QSMain.ConnectionString)
                                //.ShowSql()
                                //.FormatSql()
                ;

                OrmConfig.ConfigureOrm(
                    db_config,
                    new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                }
                    );

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка в настройке подключения к БД.");
                return;
            }

            try {
                ReceiptServiceStarter.StartService(serviceConfig, kassaConfig);
                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
Exemple #10
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            try {
                IniConfigSource confFile = new IniConfigSource(configFile);
                confFile.Reload();
                IConfig serviceConfig = confFile.Configs["Service"];
                serviceHostName = serviceConfig.GetString("service_host_name");
                servicePort     = serviceConfig.GetString("service_port");
                serviceWebPort  = serviceConfig.GetString("service_web_port");

                IConfig mysqlConfig = confFile.Configs["Mysql"];
                mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name");
                mysqlServerPort     = mysqlConfig.GetString("mysql_server_port", "3306");
                mysqlUser           = mysqlConfig.GetString("mysql_user");
                mysqlPassword       = mysqlConfig.GetString("mysql_password");
                mysqlDatabase       = mysqlConfig.GetString("mysql_database");
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            logger.Info(String.Format("Запуск службы отправки электронной почты"));
            try {
                var conStrBuilder = new MySqlConnectionStringBuilder();
                conStrBuilder.Server   = mysqlServerHostName;
                conStrBuilder.Port     = UInt32.Parse(mysqlServerPort);
                conStrBuilder.Database = mysqlDatabase;
                conStrBuilder.UserID   = mysqlUser;
                conStrBuilder.Password = mysqlPassword;
                conStrBuilder.SslMode  = MySqlSslMode.None;

                QSMain.ConnectionString = conStrBuilder.GetConnectionString(true);
                var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                                .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                                .ConnectionString(QSMain.ConnectionString);

                OrmConfig.ConfigureOrm(db_config,
                                       new System.Reflection.Assembly[] {
                    System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(EmailService.Email)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                MainSupport.LoadBaseParameters();
                QS.HistoryLog.HistoryMain.Enable();

                EmailInstanceProvider emailInstanceProvider = new EmailInstanceProvider(new BaseParametersProvider());

                ServiceHost EmailSendingHost  = new EmailServiceHost(emailInstanceProvider);
                ServiceHost MailjetEventsHost = new EmailServiceHost(emailInstanceProvider);

                ServiceEndpoint webEndPoint = EmailSendingHost.AddServiceEndpoint(
                    typeof(IEmailServiceWeb),
                    new WebHttpBinding(),
                    String.Format("http://{0}:{1}/EmailServiceWeb", serviceHostName, serviceWebPort)
                    );
                WebHttpBehavior httpBehavior = new WebHttpBehavior();
                webEndPoint.Behaviors.Add(httpBehavior);

                EmailSendingHost.AddServiceEndpoint(
                    typeof(IEmailService),
                    new BasicHttpBinding(),
                    String.Format("http://{0}:{1}/EmailService", serviceHostName, servicePort)
                    );

                var mailjetEndPoint = MailjetEventsHost.AddServiceEndpoint(
                    typeof(IMailjetEventService),
                    new WebHttpBinding(),
                    String.Format("http://{0}:{1}/Mailjet", serviceHostName, servicePort)
                    );
                WebHttpBehavior mailjetHttpBehavior = new WebHttpBehavior();
                mailjetEndPoint.Behaviors.Add(httpBehavior);

#if DEBUG
                EmailSendingHost.Description.Behaviors.Add(new PreFilter());
                MailjetEventsHost.Description.Behaviors.Add(new PreFilter());
#endif
                EmailSendingHost.Open();
                MailjetEventsHost.Open();

                logger.Info("Server started.");

                UnixSignal[] signals =
                {
                    new UnixSignal(Signum.SIGINT),
                    new UnixSignal(Signum.SIGHUP),
                    new UnixSignal(Signum.SIGTERM)
                };
                UnixSignal.WaitAny(signals);
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }