コード例 #1
0
        public static void ConfigureNh()
        {
            if (NhConfigered)
            {
                return;
            }

            //Использование другого способа формировать id объектов, чтобы они не пересекались.
            //По умолчанию все первые объекты каждого типа были 1, а вторые 2. Если сравнивать объекты по id, то не всегда можно
            //действительно проверить что id правильный. Что в некторых случаях приводило к некоректной проверки в тестах. Когда сравнивались id, разных объектов,
            //при этом тест проходил так как номера их совпадали.
            MappingParams.UseIdsForTest = true;
            Console.WriteLine("Инициализация");
            var db_config = FluentNHibernate.Cfg.Db.MonoSqliteConfiguration.Standard.InMemory();

            Console.WriteLine("ORM");
            // Настройка ORM
            OrmConfig.ConfigureOrm(db_config, new System.Reflection.Assembly[] {
                System.Reflection.Assembly.GetAssembly(typeof(workwear.Domain.Users.UserSettings)),
                System.Reflection.Assembly.GetAssembly(typeof(MeasurementUnits)),
                System.Reflection.Assembly.GetAssembly(typeof(UserBase)),
            });

            NhConfigered = true;
        }
コード例 #2
0
        public static void ConfigureNh()
        {
            if (NhConfigered)
            {
                return;
            }

            Console.WriteLine("Инициализация");
            var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                            .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                            .ConnectionString("server=vod.qsolution.ru;port=3306;database=test-test;user id=test_only;password=7qqKWuNugQF2Y2W1;sslmode=None;");

            Console.WriteLine("ORM");
            // Настройка ORM
            OrmConfig.ConfigureOrm(db_config, new System.Reflection.Assembly[]
            {
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.UserBaseMap)),
                System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.TypeOfEntityMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.HMap.BankMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.Domain.Attachment))
            });

            NhConfigered = true;
        }
コード例 #3
0
        public EmailPrepareWorker(ILogger <EmailPrepareWorker> logger, IConfiguration configuration, IModel channel, IEmailRepository emailRepository,
                                  IEmailParametersProvider emailParametersProvider)
        {
            if (configuration is null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _logger                  = logger ?? throw new ArgumentNullException(nameof(logger));
            _channel                 = channel ?? throw new ArgumentNullException(nameof(channel));
            _emailRepository         = emailRepository ?? throw new ArgumentNullException(nameof(emailRepository));
            _emailParametersProvider = emailParametersProvider ?? throw new ArgumentNullException(nameof(emailParametersProvider));
            _emailSendKey            = configuration.GetSection(_queuesConfigurationSection)
                                       .GetValue <string>(_emailSendKeyParameter);
            _emailSendExchange = configuration.GetSection(_queuesConfigurationSection)
                                 .GetValue <string>(_emailSendExchangeParameter);
            _channel.QueueDeclare(_emailSendKey, true, false, false, null);

            var conStrBuilder = new MySqlConnectionStringBuilder();

            var databaseSection = configuration.GetSection("Database");

            conStrBuilder.Server   = databaseSection.GetValue("Hostname", "localhost");
            conStrBuilder.Port     = databaseSection.GetValue <uint>("Port", 3306);
            conStrBuilder.UserID   = databaseSection.GetValue("Username", "");
            conStrBuilder.Password = databaseSection.GetValue("Password", "");
            conStrBuilder.Database = databaseSection.GetValue("DatabaseName", "");
            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);

            OrmMain.ClassMappingList = new List <IOrmObjectMapping> ();            // Нужно, чтобы запустился конструктор OrmMain

            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.HibernateMapping.TypeOfEntityMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.HibernateMapping.AttachmentMap))
            });

            QS.HistoryLog.HistoryMain.Enable();

            using (var unitOfWork = UnitOfWorkFactory.CreateWithoutRoot("Email prepare worker"))
            {
                _instanceId = Convert.ToInt32(unitOfWork.Session
                                              .CreateSQLQuery("SELECT GET_CURRENT_DATABASE_ID()")
                                              .List <object>()
                                              .FirstOrDefault());
            }
        }
コード例 #4
0
        public void ConfigureOrm()
        {
            logger.Debug("Конфигурация ORM...");

            //Увеличиваем таймаут если нужно
            var dbConnectionStringBuilder = new DbConnectionStringBuilder {
                ConnectionString = QSMain.ConnectionString
            };

            if (dbConnectionStringBuilder.TryGetValue("ConnectionTimeout", out var timeoutAsObject) &&
                timeoutAsObject is string timeoutAsString
                )
            {
                if (Int32.TryParse(timeoutAsString, out int timeout) && timeout != connectionTimeoutSeconds)
                {
                    dbConnectionStringBuilder["ConnectionTimeout"] = connectionTimeoutSeconds;
                    QSMain.ConnectionString = dbConnectionStringBuilder.ConnectionString;
                }
            }
            else
            {
                dbConnectionStringBuilder.Add("ConnectionTimeout", connectionTimeoutSeconds);
                QSMain.ConnectionString = dbConnectionStringBuilder.ConnectionString;
            }

            var dbConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                           .Dialect <MySQL57SpatialExtendedDialect>()
                           .ConnectionString(QSMain.ConnectionString)
                           .AdoNetBatchSize(100)
                           .Driver <LoggedMySqlClientDriver>();

            // Настройка ORM
            OrmConfig.ConfigureOrm(
                dbConfig,
                new[] {
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.UserBaseMap)),
                System.Reflection.Assembly.GetAssembly(typeof(HibernateMapping.OrganizationMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.TypeOfEntityMap)),
                System.Reflection.Assembly.GetAssembly(typeof(Bank)),
                System.Reflection.Assembly.GetAssembly(typeof(HistoryMain)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.Domain.Attachment)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Report.Domain.UserPrintSettings))
            },
                cnf => {
                cnf.DataBaseIntegration(
                    dbi => {
                    dbi.BatchSize = 100;
                    dbi.Batcher <MySqlClientBatchingBatcherFactory>();
                }
                    );
            }
                );

            logger.Debug("OK");
        }
コード例 #5
0
        public EmailStatusUpdateWorker(ILogger <EmailStatusUpdateWorker> logger, IConfiguration configuration, IModel channel, IEmailRepository emailRepository)
        {
            if (configuration is null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            _logger          = logger ?? throw new ArgumentNullException(nameof(logger));
            _channel         = channel ?? throw new ArgumentNullException(nameof(channel));
            _emailRepository = emailRepository ?? throw new ArgumentNullException(nameof(emailRepository));
            _storedEmailStatusUpdatingQueueId = configuration.GetSection(_queuesConfigurationSection)
                                                .GetValue <string>(_emailStatusUpdateQueueParameter);
            _channel.QueueDeclare(_storedEmailStatusUpdatingQueueId, true, false, false, null);
            _consumer           = new AsyncEventingBasicConsumer(_channel);
            _consumer.Received += MessageRecieved;

            try
            {
                var conStrBuilder = new MySqlConnectionStringBuilder();

                var databaseSection = configuration.GetSection("Database");

                conStrBuilder.Server   = databaseSection.GetValue("Host", "localhost");
                conStrBuilder.Port     = databaseSection.GetValue <uint>("Port", 3306);
                conStrBuilder.UserID   = databaseSection.GetValue("Username", "");
                conStrBuilder.Password = databaseSection.GetValue("Password", "");
                conStrBuilder.Database = databaseSection.GetValue("DatabaseName", "");
                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.HibernateMapping.TypeOfEntityMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.HibernateMapping.AttachmentMap))
                });

                QS.HistoryLog.HistoryMain.Enable();
            }
            catch (Exception ex)
            {
                _logger.LogCritical(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }
        }
コード例 #6
0
        private void CreateBaseConfig()
        {
            _logger.LogInformation("Настройка параметров Nhibernate...");

            var conStrBuilder = new MySqlConnectionStringBuilder();

            var domainDBConfig = Configuration.GetSection("DomainDB");

            conStrBuilder.Server   = domainDBConfig.GetValue <string>("Server");
            conStrBuilder.Port     = domainDBConfig.GetValue <uint>("Port");
            conStrBuilder.Database = domainDBConfig.GetValue <string>("Database");
            conStrBuilder.UserID   = domainDBConfig.GetValue <string>("UserID");
            conStrBuilder.Password = domainDBConfig.GetValue <string>("Password");
            conStrBuilder.SslMode  = MySqlSslMode.None;

            var connectionString = conStrBuilder.GetConnectionString(true);

            var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                            .Dialect <MySQL57SpatialExtendedDialect>()
                            .ConnectionString(connectionString)
                            .AdoNetBatchSize(100);

            // Настройка ORM
            OrmConfig.ConfigureOrm(
                db_config,
                new System.Reflection.Assembly[]
            {
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.UserBaseMap)),
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.TypeOfEntityMap)),
                System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)),
                System.Reflection.Assembly.GetAssembly(typeof(Bank)),
                System.Reflection.Assembly.GetAssembly(typeof(HistoryMain)),
                System.Reflection.Assembly.GetAssembly(typeof(Attachment))
            }
                );

            var serviceUserId = 0;

            using (var unitOfWork = UnitOfWorkFactory.CreateWithoutRoot("Получение пользователя"))
            {
                serviceUserId = unitOfWork.Session.Query <Vodovoz.Domain.Employees.User>()
                                .Where(u => u.Login == domainDBConfig.GetValue <string>("UserID"))
                                .Select(u => u.Id)
                                .FirstOrDefault();
            }

            QS.Project.Repositories.UserRepository.GetCurrentUserId = () => serviceUserId;

            HistoryMain.Enable();
        }
コード例 #7
0
        /// <summary>
        /// Полная инициализация всего необходимого для тестирования в Nh
        /// </summary>
        public void InitialiseNHibernate(params Assembly[] assemblies)
        {
            if (configuration != null)
            {
                return;
            }

            var db_config = FluentNHibernate.Cfg.Db.MonoSqliteConfiguration.Standard.InMemory();

            OrmConfig.ConfigureOrm(db_config, assemblies);
            configuration = OrmConfig.NhConfig;
            inMemoryDBTestSessionProvider = new InMemoryDBTestSessionProvider(configuration);
            UnitOfWorkFactory             = new DefaultUnitOfWorkFactory(inMemoryDBTestSessionProvider);
        }
コード例 #8
0
        static void CreateBaseConfig()
        {
            logger.Info("Настройка параметров базы...");

            // Настройка ORM
            var db = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                     .ConnectionString(QSMain.ConnectionString)
                     .ShowSql()
                     .FormatSql();

            OrmConfig.ConfigureOrm(db, new System.Reflection.Assembly[] {
                System.Reflection.Assembly.GetAssembly(typeof(MainClass)),
                System.Reflection.Assembly.GetAssembly(typeof(UserBase)),
            });

            OrmMain.AddObjectDescription <CarBrand>().DefaultTableView().SearchColumn("Наименование", i => i.Name).OrderAsc(i => i.Name).End();
            OrmMain.AddObjectDescription <CarModel>().Dialog <CarModelDlg>();
            OrmMain.AddObjectDescription <StoreItem>().Dialog <StoreItemDlg>();

            JournalsColumnsConfigs.RegisterColumns();
        }
コード例 #9
0
        static void CreateBaseConfig()
        {
            logger.Info("Настройка параметров базы...");

            // Настройка ORM
            var db = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                     .Dialect <MySQL57ExtendedDialect>()
                     .ConnectionString(QSProjectsLib.QSMain.ConnectionString)
                     .AdoNetBatchSize(100)
                     .ShowSql()
                     .FormatSql();

            OrmConfig.ConfigureOrm(db, new System.Reflection.Assembly[] {
                System.Reflection.Assembly.GetAssembly(typeof(MainClass)),
                System.Reflection.Assembly.GetAssembly(typeof(MeasurementUnits)),
                System.Reflection.Assembly.GetAssembly(typeof(UserBase)),
                System.Reflection.Assembly.GetAssembly(typeof(HistoryMain)),
            });

                        #if DEBUG
            NLog.LogManager.Configuration.RemoveRuleByName("HideNhibernate");
                        #endif

            //Настраиваем классы сущностей
            OrmMain.AddObjectDescription(MeasurementUnitsOrmMapping.GetOrmMapping());
            //Спецодежда
            OrmMain.AddObjectDescription <RegulationDoc>().Dialog <RegulationDocDlg>().DefaultTableView().SearchColumn("Документ", i => i.Title).OrderAsc(i => i.Name).End();
            //Общее
            OrmMain.AddObjectDescription <UserBase>().DefaultTableView().Column("Имя", e => e.Name).End();
            OrmMain.AddObjectDescription <UserSettings>();
            //Склад
            OrmMain.AddObjectDescription <Income>().Dialog <Dialogs.Stock.IncomeDocDlg>();

            NotifyConfiguration.Enable();
            BuisnessLogicGlobalEventHandler.Init(new GtkQuestionDialogsInteractive());
            JournalsColumnsConfigs.RegisterColumns();
        }
コード例 #10
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

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

            const string configValueNotFoundString = "Не удалось прочитать значение параметра \"{0}\" из файла конфигурации";

            try
            {
                var builder = new ConfigurationBuilder()
                              .AddJsonFile(configFile, false);
                var configuration = builder.Build();

                var serviceConfig = configuration.GetSection("Service");
                serviceHostName = serviceConfig["service_host_name"]
                                  ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "service_host_name"));
                servicePort = serviceConfig["service_port"]
                              ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "service_port"));

                var modulKassaConfig = configuration.GetSection("ModulKassa");
                modulKassaBaseAddress = modulKassaConfig["base_address"]
                                        ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "base_address"));

                var mysqlConfig = configuration.GetSection("MySql");
                mysqlServerHostName = mysqlConfig["mysql_server_host_name"]
                                      ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "mysql_server_host_name"));
                mysqlServerPort = mysqlConfig["mysql_server_port"]
                                  ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "mysql_server_port"));
                mysqlUser = mysqlConfig["mysql_user"]
                            ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "mysql_user"));
                mysqlPassword = mysqlConfig["mysql_password"]
                                ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "mysql_password"));
                mysqlDatabase = mysqlConfig["mysql_database"]
                                ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "mysql_database"));

                cashboxes = new List <CashBox>();
                var cashboxesConfig = configuration.GetSection("Cashboxes")?.GetChildren()
                                      ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "Cashboxes"));
                foreach (var cashboxConfig in cashboxesConfig)
                {
                    string stringId = cashboxConfig["id"];
                    if (string.IsNullOrWhiteSpace(stringId) || !int.TryParse(stringId, out int id))
                    {
                        throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "id"));
                    }

                    string stringUserName = cashboxConfig["user_name"];
                    if (string.IsNullOrWhiteSpace(stringUserName) || !Guid.TryParse(stringUserName, out Guid userName))
                    {
                        throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "user_name"));
                    }

                    var cashBox = new CashBox
                    {
                        Id              = id,
                        UserName        = userName,
                        RetailPointName = cashboxConfig["retail_point_name"]
                                          ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "retail_point_name")),
                                                Password = cashboxConfig["password"]
                                                           ?? throw new ConfigurationErrorsException(string.Format(configValueNotFoundString, "password")),
                    };
                    cashboxes.Add(cashBox);
                }
                if (!cashboxes.Any())
                {
                    throw new ConfigurationErrorsException(
                              $"В конфигурационном файле не найдено данных ни для одной кассы ({nameof(CashBox)})");
                }
            }
            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
                };

                var dbConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                               .ConnectionString(conStrBuilder.GetConnectionString(true));

                OrmConfig.ConfigureOrm(
                    dbConfig,
                    new[]
                {
                    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)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.TypeOfEntityMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.Domain.Attachment))
                }
                    );

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

            try {
                ReceiptServiceStarter.StartService(serviceHostName, servicePort, modulKassaBaseAddress, cashboxes);

                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    UnixSignal[] signals =
                    {
                        new UnixSignal(Signum.SIGINT),
                        new UnixSignal(Signum.SIGHUP),
                        new UnixSignal(Signum.SIGTERM)
                    };
                    UnixSignal.WaitAny(signals);
                }
                else
                {
                    Console.ReadLine();
                }
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
コード例 #11
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");

                IConfig osrmConfig = confFile.Configs["OsrmService"];
                serverUrl = osrmConfig.GetString("server_url");

                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(Bank)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });
                OsrmMain.ServerUrl = serverUrl;

                IDeliveryRepository           deliveryRepository            = new DeliveryRepository();
                DeliveryRulesInstanceProvider deliveryRulesInstanceProvider = new DeliveryRulesInstanceProvider(deliveryRepository);
                ServiceHost deliveryRulesHost = new DeliveryRulesServiceHost(deliveryRulesInstanceProvider);

                ServiceEndpoint webEndPoint = deliveryRulesHost.AddServiceEndpoint(
                    typeof(IDeliveryRulesService),
                    new WebHttpBinding(),
                    $"http://{serviceHostName}:{servicePort}/DeliveryRules"
                    );
                WebHttpBehavior httpBehavior = new WebHttpBehavior();
                webEndPoint.Behaviors.Add(httpBehavior);

#if DEBUG
                deliveryRulesHost.Description.Behaviors.Add(new PreFilter());
#endif
                deliveryRulesHost.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);
            }
        }
コード例 #12
0
ファイル: CreateProjectParam.cs プロジェクト: RoAr80/Vodovoz
        static void CreateBaseConfig()
        {
            logger.Info("Настройка параметров базы...");
            //Увеличиваем таймоут
            QSMain.ConnectionString += ";ConnectionTimeout=120";

            var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                            .Dialect <MySQL57SpatialExtendedDialect>()
                            .ConnectionString(QSMain.ConnectionString)
                            .AdoNetBatchSize(100)
                            .Driver <LoggedMySqlClientDriver>();

            // Настройка ORM
            OrmConfig.ConfigureOrm(
                db_config,
                new System.Reflection.Assembly[] {
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.UserBaseMap)),
                System.Reflection.Assembly.GetAssembly(typeof(HibernateMapping.OrganizationMap)),
                System.Reflection.Assembly.GetAssembly(typeof(Bank)),
                System.Reflection.Assembly.GetAssembly(typeof(HistoryMain)),
            },
                (cnf) => {
                cnf.DataBaseIntegration(
                    dbi => {
                    dbi.BatchSize = 100;
                    dbi.Batcher <MySqlClientBatchingBatcherFactory>();
                }
                    );
            }
                );
            #region Dialogs mapping

            OrmMain.ClassMappingList = new List <IOrmObjectMapping> {
                //Простые справочники
                OrmObjectMapping <CullingCategory> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <Nationality> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <Citizenship> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <Manufacturer> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <EquipmentColors> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <User> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <UserSettings> .Create().Dialog <UserSettingsView>(),
                OrmObjectMapping <FuelType> .Create().Dialog <FuelTypeDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Стоимость", x => x.Cost.ToString()).End(),
                OrmObjectMapping <MovementWagon> .Create().Dialog <MovementWagonViewModel>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                //Остальные справочники
                OrmObjectMapping <CarProxyDocument> .Create().Dialog <CarProxyDlg>(),
                OrmObjectMapping <M2ProxyDocument> .Create().Dialog <M2ProxyDlg>(),
                OrmObjectMapping <ProductGroup> .Create().Dialog <ProductGroupDlg>(),
                OrmObjectMapping <CommentTemplate> .Create().Dialog <CommentTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Comment).End(),
                OrmObjectMapping <FineTemplate> .Create().Dialog <FineTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Reason).End(),
                OrmObjectMapping <PremiumTemplate> .Create().Dialog <PremiumTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Reason).End(),
                OrmObjectMapping <MeasurementUnits> .Create().Dialog <MeasurementUnitsDlg>().DefaultTableView().SearchColumn("ОКЕИ", x => x.OKEI).SearchColumn("Название", x => x.Name).Column("Точность", x => x.Digits.ToString()).End(),
                OrmObjectMapping <Contact> .Create().Dialog <ContactDlg>()
                .DefaultTableView().SearchColumn("Фамилия", x => x.Surname).SearchColumn("Имя", x => x.Name).SearchColumn("Отчество", x => x.Patronymic).End(),
                OrmObjectMapping <Order> .Create().Dialog <OrderDlg>().PopupMenu(OrderPopupMenu.GetPopupMenu),
                OrmObjectMapping <UndeliveredOrder> .Create().Dialog <UndeliveredOrderDlg>(),
                OrmObjectMapping <Organization> .Create().Dialog <OrganizationDlg>().DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <DeliverySchedule> .Create().Dialog <DeliveryScheduleDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Время доставки", x => x.DeliveryTime).End(),
                OrmObjectMapping <ProductSpecification> .Create().Dialog <ProductSpecificationDlg>().DefaultTableView().SearchColumn("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <EquipmentType> .Create().Dialog <EquipmentTypeDlg>().DefaultTableView().Column("Название", equipmentType => equipmentType.Name).End(),
                //Связанное с клиентом
                OrmObjectMapping <Proxy> .Create().Dialog <ProxyDlg>()
                .DefaultTableView().SearchColumn("Номер", x => x.Number).SearchColumn("С", x => x.StartDate.ToShortDateString()).SearchColumn("По", x => x.ExpirationDate.ToShortDateString()).End(),
                OrmObjectMapping <DeliveryPoint> .Create().Dialog <DeliveryPointDlg>().DefaultTableView().SearchColumn("ID", x => x.Id.ToString()).Column("Адрес", x => x.Title).End(),
                OrmObjectMapping <PaidRentPackage> .Create().Dialog <PaidRentPackageDlg>()
                .DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип оборудования", x => x.EquipmentType.Name).SearchColumn("Цена в сутки", x => CurrencyWorks.GetShortCurrencyString(x.PriceDaily)).SearchColumn("Цена в месяц", x => CurrencyWorks.GetShortCurrencyString(x.PriceMonthly)).End(),
                OrmObjectMapping <FreeRentPackage> .Create().Dialog <FreeRentPackageDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип оборудования", x => x.EquipmentType.Name).OrderAsc(x => x.Name).End(),
                OrmObjectMapping <Counterparty> .Create().Dialog <CounterpartyDlg>().DefaultTableView().SearchColumn("Название", x => x.FullName).End(),
                OrmObjectMapping <Tag> .Create().Dialog <TagDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <CounterpartyContract> .Create().Dialog <CounterpartyContractDlg>(),
                OrmObjectMapping <DocTemplate> .Create().Dialog <DocTemplateDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип", x => x.TemplateType.GetEnumTitle()).End(),
                OrmObjectMapping <TransferOperationDocument> .Create().Dialog <TransferOperationDocumentDlg>(),
                //Справочники с фильтрами
                OrmObjectMapping <Equipment> .Create().Dialog <EquipmentDlg>().JournalFilter <EquipmentFilter>()
                .DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Номенклатура", x => x.NomenclatureName).Column("Тип", x => x.Nomenclature.Type.Name).SearchColumn("Серийный номер", x => x.Serial).Column("Дата последней обработки", x => x.LastServiceDate.ToShortDateString()).End(),
                //Логисткика
                OrmObjectMapping <RouteList> .Create().Dialog <RouteListCreateDlg>()
                .DefaultTableView().SearchColumn("Номер", x => x.Id.ToString()).Column("Дата", x => x.Date.ToShortDateString()).Column("Статус", x => x.Status.GetEnumTitle()).SearchColumn("Водитель", x => String.Format("{0} - {1}", x.Driver.FullName, x.Car.Title)).End(),
                OrmObjectMapping <RouteColumn> .Create().DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <DeliveryShift> .Create().Dialog <DeliveryShiftDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Диапазон времени", x => x.DeliveryTime).End(),
                OrmObjectMapping <DeliveryDaySchedule> .Create().Dialog <DeliveryDayScheduleDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                //Сервис
                OrmObjectMapping <ServiceClaim> .Create().Dialog <ServiceClaimDlg>().DefaultTableView().Column("Номер", x => x.Id.ToString()).Column("Тип", x => x.ServiceClaimType.GetEnumTitle()).Column("Оборудование", x => x.Equipment.Title).Column("Подмена", x => x.ReplacementEquipment != null ? "Да" : "Нет").Column("Точка доставки", x => x.DeliveryPoint.Title).End(),
                //Касса
                OrmObjectMapping <Income> .Create().Dialog <CashIncomeDlg> (),
                OrmObjectMapping <ExpenseCategory> .Create().Dialog <ExpenseCategoryViewModel>().DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", e => e.Name).Column("Тип документа", e => e.ExpenseDocumentType.GetEnumTitle()).TreeConfig(new RecursiveTreeConfig <ExpenseCategory>(x => x.Parent, x => x.Childs)).End(),
                OrmObjectMapping <Expense> .Create().Dialog <CashExpenseDlg> (),
                OrmObjectMapping <AdvanceReport> .Create().Dialog <AdvanceReportDlg> (),
                OrmObjectMapping <Fine> .Create().Dialog <FineDlg> (),
                OrmObjectMapping <Premium> .Create().Dialog <PremiumDlg> (),
                OrmObjectMapping <IncomeCashTransferDocument> .Create().Dialog <IncomeCashTransferDlg>(),
                OrmObjectMapping <CommonCashTransferDocument> .Create().Dialog <CommonCashTransferDlg>(),
                //Банкинг
                OrmObjectMapping <AccountIncome> .Create(),
                OrmObjectMapping <AccountExpense> .Create(),
                //Склад
                OrmObjectMapping <Warehouse> .Create().Dialog <WarehouseDlg>().DefaultTableView().Column("Название", w => w.Name).Column("В архиве", w => w.IsArchive ? "Да":"").End(),
                OrmObjectMapping <RegradingOfGoodsTemplate> .Create().Dialog <RegradingOfGoodsTemplateDlg>().DefaultTableView().Column("Название", w => w.Name).End()
            };

            #region Складские документы
            OrmMain.AddObjectDescription <IncomingWater>().Dialog <IncomingWaterDlg>();
            OrmMain.AddObjectDescription <WriteoffDocument>().Dialog <WriteoffDocumentDlg>();
            OrmMain.AddObjectDescription <InventoryDocument>().Dialog <InventoryDocumentDlg>();
            OrmMain.AddObjectDescription <ShiftChangeWarehouseDocument>().Dialog <ShiftChangeWarehouseDocumentDlg>();
            OrmMain.AddObjectDescription <RegradingOfGoodsDocument>().Dialog <RegradingOfGoodsDocumentDlg>();
            OrmMain.AddObjectDescription <SelfDeliveryDocument>().Dialog <SelfDeliveryDocumentDlg>();
            OrmMain.AddObjectDescription <CarLoadDocument>().Dialog <CarLoadDocumentDlg>();
            OrmMain.AddObjectDescription <CarUnloadDocument>().Dialog <CarUnloadDocumentDlg>();
            #endregion

            #region Goods
            OrmMain.AddObjectDescription <Nomenclature>().Dialog <NomenclatureDlg>().JournalFilter <NomenclatureFilter>().
            DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .Column("Тип", x => x.CategoryString)
            .SearchColumn("Номер в ИМ", x => x.OnlineStoreExternalId)
            .End();
            OrmMain.AddObjectDescription <Folder1c>().Dialog <Folder1cDlg>()
            .DefaultTableView()
            .SearchColumn("Код 1С", x => x.Code1c)
            .SearchColumn("Название", x => x.Name)
            .TreeConfig(new RecursiveTreeConfig <Folder1c>(x => x.Parent, x => x.Childs)).End();
            #endregion

            #region Простые справочники
            OrmMain.AddObjectDescription <DiscountReason>()
            .DefaultTableView()
            .SearchColumn("Название", x => x.Name)
            .End();
            OrmMain.AddObjectDescription <GeographicGroup>()
            .Dialog <GeographicGroupDlg>()
            .DefaultTableView()
            .SearchColumn("Название", x => x.Name)
            .Column("Код", x => x.Id.ToString())
            .End();
            OrmMain.AddObjectDescription <TariffZone>()
            .DefaultTableView()
            .SearchColumn("Номер", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();
            OrmMain.AddObjectDescription <NonReturnReason>()
            .DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();
            OrmMain.AddObjectDescription <PaymentFrom>()
            .DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();
            OrmMain.AddObjectDescription <Post>()
            .DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();

            #endregion

            #region неПростые справочники
            OrmMain.AddObjectDescription <Subdivision>().Dialog <SubdivisionDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Руководитель", x => x.Chief == null ? "" : x.Chief.ShortName).SearchColumn("Номер", x => x.Id.ToString()).TreeConfig(new RecursiveTreeConfig <Subdivision>(x => x.ParentSubdivision, x => x.ChildSubdivisions)).End();
            OrmMain.AddObjectDescription <TypeOfEntity>()
            .Dialog <TypeOfEntityDlg>()
            .DefaultTableView()
            .SearchColumn("Тип документа", x => TypeOfEntityRepository.GetEntityNameByString(x.Type))
            .SearchColumn("Название документа", x => x.CustomName)
            .SearchColumn("Код", x => x.Id.ToString())
            .Column("Активно", x => !x.IsActive ? "нет" : String.Empty)
            .SearchColumn("Имя класса", x => x.Type)
            .OrderAsc(x => x.CustomName)
            .End();
            OrmMain.AddObjectDescription <Employee>().Dialog <EmployeeDlg>().DefaultTableView()
            .Column("Код", x => x.Id.ToString())
            .SearchColumn("Ф.И.О.", x => x.FullName)
            .Column("Категория", x => x.Category.GetEnumTitle())
            .OrderAsc(x => x.LastName).OrderAsc(x => x.Name).OrderAsc(x => x.Patronymic)
            .End();
            OrmMain.AddObjectDescription <Trainee>().Dialog <TraineeDlg>().DefaultTableView()
            .Column("Код", x => x.Id.ToString())
            .SearchColumn("Ф.И.О.", x => x.FullName)
            .OrderAsc(x => x.LastName).OrderAsc(x => x.Name).OrderAsc(x => x.Patronymic)
            .End();
            OrmMain.AddObjectDescription <DeliveryPriceRule>().Dialog <DeliveryPriceRuleDlg>().DefaultTableView()
            .Column("< 19л б.", x => x.Water19LCount.ToString())
            .Column("< 6л б.", x => x.Water6LCount)
            .Column("< 1,5л б.", x => x.Water1500mlCount)
            .Column("< 0,6л б.", x => x.Water600mlCount)
            .Column("Минимальная сумма заказа", x => x.OrderMinSumEShopGoods.ToString())
            .SearchColumn("Описание правила", x => x.Title)
            .End();
            OrmMain.AddObjectDescription <Car>().Dialog <CarsDlg>().DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Модель а/м", x => x.Model)
            .SearchColumn("Гос. номер", x => x.RegistrationNumber)
            .SearchColumn("Водитель", x => x.Driver != null ? x.Driver.FullName : string.Empty)
            .End();
            OrmMain.AddObjectDescription <Certificate>().Dialog <CertificateDlg>().DefaultTableView()
            .SearchColumn("Имя", x => x.Name)
            .Column("Тип", x => x.TypeOfCertificate.GetEnumTitle())
            .SearchColumn("Номер", x => x.Id.ToString())
            .SearchColumn("Начало срока", x => x.StartDate.HasValue ? x.StartDate.Value.ToString("dd.MM.yyyy") : "Ошибка!")
            .SearchColumn("Окончание срока", x => x.ExpirationDate.HasValue ? x.ExpirationDate.Value.ToString("dd.MM.yyyy") : "Бессрочно")
            .Column("Архивный?", x => x.IsArchive ? "Да" : string.Empty)
            .OrderAsc(x => x.IsArchive)
            .OrderAsc(x => x.Id)
            .End();
            OrmMain.AddObjectDescription <StoredImageResource>().Dialog <ImageLoaderDlg>().DefaultTableView()
            .SearchColumn("Номер", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();
            OrmMain.AddObjectDescription <DeliveryPointCategory>().Dialog <DeliveryPointCategoryDlg>().DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .Column("В архиве?", x => x.IsArchive ? "Да" : "Нет")
            .OrderAsc(x => x.Name)
            .End();
            OrmMain.AddObjectDescription <CounterpartyActivityKind>().Dialog <CounterpartyActivityKindDlg>().DefaultTableView()
            .SearchColumn("Код", x => x.Id.ToString())
            .SearchColumn("Название", x => x.Name)
            .End();

            #endregion

            OrmMain.ClassMappingList.AddRange(QSBanks.QSBanksMain.GetModuleMaping());

            #endregion

            HistoryMain.Enable();
            TemplatePrinter.InitPrinter();
            ImagePrinter.InitPrinter();

            //Настройка ParentReference
            ParentReferenceConfig.AddActions(new ParentReferenceActions <Organization, Account> {
                AddNewChild = (o, a) => o.AddAccount(a)
            });
            ParentReferenceConfig.AddActions(new ParentReferenceActions <Counterparty, Account> {
                AddNewChild = (c, a) => c.AddAccount(a)
            });
            ParentReferenceConfig.AddActions(new ParentReferenceActions <Employee, Account> {
                AddNewChild = (c, a) => c.AddAccount(a)
            });
            ParentReferenceConfig.AddActions(new ParentReferenceActions <Trainee, Account> {
                AddNewChild = (c, a) => c.AddAccount(a)
            });
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: Art8m/Vodovozfork
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;
            AppDomain.CurrentDomain.ProcessExit        += CurrentDomain_ProcessExit;

            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"];
                serviceWebPort  = serviceSection["service_web_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"];
            }
            catch (Exception ex) {
                logger.Fatal(ex, "Ошибка чтения конфигурационного файла.");
                return;
            }

            logger.Info("Запуск службы отправки электронной почты");
            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(EmailService.OrderEmail)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase))
                });

                QS.HistoryLog.HistoryMain.Enable();

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

                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.");

                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    UnixSignal[] signals =
                    {
                        new UnixSignal(Signum.SIGINT),
                        new UnixSignal(Signum.SIGHUP),
                        new UnixSignal(Signum.SIGTERM)
                    };
                    UnixSignal.WaitAny(signals);
                }
                else
                {
                    Console.ReadLine();
                }
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
コード例 #14
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);
            }
        }
コード例 #15
0
        static void CreateBaseConfig()
        {
            logger.Info("Настройка параметров базы...");
            //Увеличиваем таймоут
            QSMain.ConnectionString += ";ConnectionTimeout=120";

            var db_config = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                            .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>()
                            .ConnectionString(QSMain.ConnectionString)
                            .AdoNetBatchSize(100)
                            .ShowSql()
                            .FormatSql();

            // Настройка ORM
            OrmConfig.ConfigureOrm(db_config, new System.Reflection.Assembly[] {
                System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.UserBaseMap)),
                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(QS.HistoryLog.HistoryMain)),
            },
                                   (cnf) => cnf.DataBaseIntegration(
                                       dbi => { dbi.BatchSize = 100; dbi.Batcher <MySqlClientBatchingBatcherFactory>(); }
                                       ));
            #region Dialogs mapping

            OrmMain.ClassMappingList = new List <IOrmObjectMapping> {
                //Простые справочники
                OrmObjectMapping <CullingCategory> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <Nationality> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <Manufacturer> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <EquipmentColors> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <User> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <UserSettings> .Create().Dialog <UserSettingsDlg>(),
                OrmObjectMapping <FuelType> .Create().Dialog <FuelTypeDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Стоимость", x => x.Cost.ToString()).End(),
                OrmObjectMapping <MovementWagon> .Create().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                //Остальные справочники
                //OrmObjectMapping<CarProxyDocument>.Create().Dialog<ProxyDocumentDlg>().DefaultTableView().SearchColumn("Водитель", x => x.Driver != null ? x.Driver.Title : "").End(),
                OrmObjectMapping <CarProxyDocument> .Create().Dialog <CarProxyDlg>(),
                OrmObjectMapping <M2ProxyDocument> .Create().Dialog <M2ProxyDlg>(),
                OrmObjectMapping <CommentTemplate> .Create().Dialog <CommentTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Comment).End(),
                OrmObjectMapping <FineTemplate> .Create().Dialog <FineTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Reason).End(),
                OrmObjectMapping <PremiumTemplate> .Create().Dialog <PremiumTemplateDlg>().DefaultTableView().SearchColumn("Шаблон комментария", x => x.Reason).End(),
                OrmObjectMapping <MeasurementUnits> .Create().Dialog <MeasurementUnitsDlg>().DefaultTableView().SearchColumn("ОКЕИ", x => x.OKEI).SearchColumn("Название", x => x.Name).Column("Точность", x => x.Digits.ToString()).End(),
                OrmObjectMapping <Contact> .Create().Dialog <ContactDlg>()
                .DefaultTableView().SearchColumn("Фамилия", x => x.Surname).SearchColumn("Имя", x => x.Name).SearchColumn("Отчество", x => x.Patronymic).End(),
                OrmObjectMapping <Car> .Create().Dialog <CarsDlg>()
                .DefaultTableView().SearchColumn("Модель а/м", x => x.Model).SearchColumn("Гос. номер", x => x.RegistrationNumber).SearchColumn("Водитель", x => x.Driver != null ? x.Driver.FullName : String.Empty).End(),
                OrmObjectMapping <Order> .Create().Dialog <OrderDlg>().PopupMenu(OrderPopupMenu.GetPopupMenu),
                OrmObjectMapping <UndeliveredOrder> .Create().Dialog <UndeliveredOrderDlg>(),
                OrmObjectMapping <Organization> .Create().Dialog <OrganizationDlg>().DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <DeliverySchedule> .Create().Dialog <DeliveryScheduleDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Время доставки", x => x.DeliveryTime).End(),
                OrmObjectMapping <ProductSpecification> .Create().Dialog <ProductSpecificationDlg>().DefaultTableView().SearchColumn("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <EquipmentType> .Create().Dialog <EquipmentTypeDlg>().DefaultTableView().Column("Название", equipmentType => equipmentType.Name).End(),
                //Связанное с клиентом
                OrmObjectMapping <Proxy> .Create().Dialog <ProxyDlg>()
                .DefaultTableView().SearchColumn("Номер", x => x.Number).SearchColumn("С", x => x.StartDate.ToShortDateString()).SearchColumn("По", x => x.ExpirationDate.ToShortDateString()).End(),
                OrmObjectMapping <DeliveryPoint> .Create().Dialog <DeliveryPointDlg>().DefaultTableView().SearchColumn("ID", x => x.Id.ToString()).Column("Адрес", x => x.Title).End(),
                OrmObjectMapping <PaidRentPackage> .Create().Dialog <PaidRentPackageDlg>()
                .DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип оборудования", x => x.EquipmentType.Name).SearchColumn("Цена в сутки", x => CurrencyWorks.GetShortCurrencyString(x.PriceDaily)).SearchColumn("Цена в месяц", x => CurrencyWorks.GetShortCurrencyString(x.PriceMonthly)).End(),
                OrmObjectMapping <FreeRentPackage> .Create().Dialog <FreeRentPackageDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип оборудования", x => x.EquipmentType.Name).OrderAsc(x => x.Name).End(),
                OrmObjectMapping <FreeRentAgreement> .Create().Dialog <FreeRentAgreementDlg>(),
                OrmObjectMapping <DailyRentAgreement> .Create().Dialog <DailyRentAgreementDlg>(),
                OrmObjectMapping <NonfreeRentAgreement> .Create().Dialog <NonFreeRentAgreementDlg>(),
                OrmObjectMapping <SalesEquipmentAgreement> .Create().Dialog <EquipSalesAgreementDlg>(),
                OrmObjectMapping <WaterSalesAgreement> .Create().Dialog <WaterAgreementDlg>(),
                OrmObjectMapping <RepairAgreement> .Create().Dialog <RepairAgreementDlg>(),
                OrmObjectMapping <Counterparty> .Create().Dialog <CounterpartyDlg>().DefaultTableView().SearchColumn("Название", x => x.FullName).End(),
                OrmObjectMapping <Tag> .Create().Dialog <TagDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <ClientCameFrom> .Create().Dialog <ClientCameFromDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <CounterpartyContract> .Create().Dialog <CounterpartyContractDlg>(),
                OrmObjectMapping <DocTemplate> .Create().Dialog <DocTemplateDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Тип", x => x.TemplateType.GetEnumTitle()).End(),
                OrmObjectMapping <Residue> .Create().Dialog <ResidueDlg>(),
                OrmObjectMapping <TransferOperationDocument> .Create().Dialog <TransferOperationDocumentDlg>(),
                //Справочники с фильтрами
                OrmObjectMapping <Equipment> .Create().Dialog <EquipmentDlg>().JournalFilter <EquipmentFilter>()
                .DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Номенклатура", x => x.NomenclatureName).Column("Тип", x => x.Nomenclature.Type.Name).SearchColumn("Серийный номер", x => x.Serial).Column("Дата последней обработки", x => x.LastServiceDate.ToShortDateString()).End(),
                //Логисткика
                OrmObjectMapping <RouteList> .Create().Dialog <RouteListCreateDlg>()
                .DefaultTableView().SearchColumn("Номер", x => x.Id.ToString()).Column("Дата", x => x.Date.ToShortDateString()).Column("Статус", x => x.Status.GetEnumTitle()).SearchColumn("Водитель", x => String.Format("{0} - {1}", x.Driver.FullName, x.Car.Title)).End(),
                OrmObjectMapping <RouteColumn> .Create().DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <DeliveryShift> .Create().Dialog <DeliveryShiftDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).SearchColumn("Диапазон времени", x => x.DeliveryTime).End(),
                OrmObjectMapping <DeliveryDaySchedule> .Create().Dialog <DeliveryDayScheduleDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).End(),
                OrmObjectMapping <LogisticsArea> .Create().Dialog <LogisticsAreaDlg>().DefaultTableView().SearchColumn("Название", x => x.Name).Column("Город", x => x.IsCity ? "Да" : "Нет").End(),
                //Сервис
                OrmObjectMapping <ServiceClaim> .Create().Dialog <ServiceClaimDlg>().DefaultTableView().Column("Номер", x => x.Id.ToString()).Column("Тип", x => x.ServiceClaimType.GetEnumTitle()).Column("Оборудование", x => x.Equipment.Title).Column("Подмена", x => x.ReplacementEquipment != null ? "Да" : "Нет").Column("Точка доставки", x => x.DeliveryPoint.Title).End(),
                //Касса
                OrmObjectMapping <IncomeCategory> .Create().EditPermision("money_manage_cash").DefaultTableView().Column("Код", x => x.Id.ToString()).Column("Название", e => e.Name).End(),
                OrmObjectMapping <ExpenseCategory> .Create().Dialog <CashExpenseCategoryDlg>().EditPermision("money_manage_cash").DefaultTableView().Column("Код", x => x.Id.ToString()).SearchColumn("Название", e => e.Name).TreeConfig(new RecursiveTreeConfig <ExpenseCategory>(x => x.Parent, x => x.Childs)).End(),
                OrmObjectMapping <Income> .Create().Dialog <CashIncomeDlg> (),
                OrmObjectMapping <Expense> .Create().Dialog <CashExpenseDlg> (),
                OrmObjectMapping <AdvanceReport> .Create().Dialog <AdvanceReportDlg> (),
                OrmObjectMapping <Fine> .Create().Dialog <FineDlg> (),
                OrmObjectMapping <Premium> .Create().Dialog <PremiumDlg> (),
                //Банкинг
                OrmObjectMapping <AccountIncome> .Create(),
                OrmObjectMapping <AccountExpense> .Create(),
                //Склад
                OrmObjectMapping <Warehouse> .Create().Dialog <WarehouseDlg>().DefaultTableView().Column("Название", w => w.Name).Column("В архиве", w => w.IsArchive ? "Да":"").End(),
                OrmObjectMapping <RegradingOfGoodsTemplate> .Create().Dialog <RegradingOfGoodsTemplateDlg>().DefaultTableView().Column("Название", w => w.Name).End()
            };

            #region Складские документы
            OrmMain.AddObjectDescription <IncomingInvoice>().Dialog <IncomingInvoiceDlg>();
            OrmMain.AddObjectDescription <IncomingWater>().Dialog <IncomingWaterDlg>();
            OrmMain.AddObjectDescription <MovementDocument>().Dialog <MovementDocumentDlg>();
            OrmMain.AddObjectDescription <WriteoffDocument>().Dialog <WriteoffDocumentDlg>();
            OrmMain.AddObjectDescription <InventoryDocument>().Dialog <InventoryDocumentDlg>();
            OrmMain.AddObjectDescription <ShiftChangeWarehouseDocument>().Dialog <ShiftChangeWarehouseDocumentDlg>();
            OrmMain.AddObjectDescription <RegradingOfGoodsDocument>().Dialog <RegradingOfGoodsDocumentDlg>();
            OrmMain.AddObjectDescription <SelfDeliveryDocument>().Dialog <SelfDeliveryDocumentDlg>();
            OrmMain.AddObjectDescription <CarLoadDocument>().Dialog <CarLoadDocumentDlg>();
            OrmMain.AddObjectDescription <CarUnloadDocument>().Dialog <CarUnloadDocumentDlg>();
            #endregion

            #region Goods
            OrmMain.AddObjectDescription <Nomenclature>().Dialog <NomenclatureDlg>().JournalFilter <NomenclatureFilter>().DefaultTableView().SearchColumn("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).Column("Тип", x => x.CategoryString).End();
            OrmMain.AddObjectDescription <Folder1c>().Dialog <Folder1cDlg>().DefaultTableView().SearchColumn("Код 1С", x => x.Code1c).SearchColumn("Название", x => x.Name).TreeConfig(new RecursiveTreeConfig <Folder1c>(x => x.Parent, x => x.Childs)).End();
            OrmMain.AddObjectDescription <ProductGroup>().Dialog <ProductGroupDlg>().EditPermision("can_edit_online_store").DefaultTableView().SearchColumn("Код", x => x.Id.ToString()).SearchColumn("Название", x => x.Name).TreeConfig(new RecursiveTreeConfig <ProductGroup>(x => x.Parent, x => x.Childs)).End();
            #endregion

            OrmMain.AddObjectDescription <DiscountReason>().DefaultTableView().SearchColumn("Название", x => x.Name).End();

            # region Простые справочники
コード例 #16
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);
            }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: RoAr80/Vodovoz
        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);
            }
        }
コード例 #18
0
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

            IConfiguration configuration;

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

                configuration = builder.Build();

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

                var bitrixSection = configuration.GetSection("Bitrix");
                baseAddress = bitrixSection["base_address"];

                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"];
            }
            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,
                    ConnectionTimeout = 30
                };

                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)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Project.HibernateMapping.TypeOfEntityMap)),
                    System.Reflection.Assembly.GetAssembly(typeof(QS.Attachments.Domain.Attachment))
                });

                QS.HistoryLog.HistoryMain.Enable();

                var driverApiSection = configuration.GetSection("DriverAPI");

                var driverApiHelperConfiguration = new DriverApiHelperConfiguration
                {
                    ApiBase = new Uri(driverApiSection["ApiBase"]),
                    NotifyOfSmsPaymentStatusChangedURI = driverApiSection["NotifyOfSmsPaymentStatusChangedURI"],
                    NotifyOfFastDeliveryOrderAddedURI  = driverApiSection["NotifyOfFastDeliveryOrderAddedURI"]
                };

                ISmsPaymentStatusNotificationReciever smsPaymentStatusNotificationReciever =
                    new DriverAPIHelper(driverApiHelperConfiguration);
                var paymentSender = new BitrixPaymentController(baseAddress);

                var smsPaymentFileCache = new SmsPaymentFileCache("/tmp/VodovozSmsPaymentServiceTemp.txt");

                SmsPaymentServiceInstanceProvider smsPaymentServiceInstanceProvider = new SmsPaymentServiceInstanceProvider(
                    paymentSender,
                    smsPaymentStatusNotificationReciever,
                    new OrderParametersProvider(new ParametersProvider()),
                    smsPaymentFileCache,
                    new SmsPaymentDTOFactory(new OrderOrganizationProviderFactory().CreateOrderOrganizationProvider()),
                    new SmsPaymentValidator(new OrganizationParametersProvider(new ParametersProvider()))
                    );

                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.");

                var serviceInstance = smsPaymentServiceInstanceProvider.GetInstance(null) as ISmsPaymentService;
                serviceInstance?.SynchronizePaymentStatuses();

                var unsavedPaymentsWorker = new CachePaymentsWorker(smsPaymentFileCache, serviceInstance);
                var overduePaymentsWorker = new OverduePaymentsWorker();
                unsavedPaymentsWorker.Start();
                overduePaymentsWorker.Start();

                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    UnixSignal[] signals =
                    {
                        new UnixSignal(Signum.SIGINT),
                        new UnixSignal(Signum.SIGHUP),
                        new UnixSignal(Signum.SIGTERM)
                    };
                    UnixSignal.WaitAny(signals);
                }
                else
                {
                    Console.ReadLine();
                }
            }
            catch (Exception e) {
                logger.Fatal(e);
            }
            finally {
                if (Environment.OSVersion.Platform == PlatformID.Unix)
                {
                    Thread.CurrentThread.Abort();
                }
                Environment.Exit(0);
            }
        }
コード例 #19
0
ファイル: Program.cs プロジェクト: RoAr80/Vodovoz
        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);
            }
        }
コード例 #20
0
ファイル: Program.cs プロジェクト: RoAr80/Vodovoz
        public static void Main(string[] args)
        {
            AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException;

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

            IConfig[] cashboxesConfig;

            try {
                XmlConfigSource confFile = new XmlConfigSource(configFile);
                confFile.Reload();
                serviceConfig = confFile.Configs["Service"];
                kassaConfig   = confFile.Configs["ModulKassa"];

                cashboxesConfig = new[] {
                    confFile.Configs["RetailPointSosnovcev"],
                    confFile.Configs["RetailPointVodovozSouth"],
                    confFile.Configs["RetailPointVodovozNorth"]
                };

                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
                };

                var dbConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard
                               .ConnectionString(conStrBuilder.GetConnectionString(true));

                OrmConfig.ConfigureOrm(
                    dbConfig,
                    new[] {
                    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))
                }
                    );

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

            try {
                ReceiptServiceStarter.StartService(serviceConfig, kassaConfig, cashboxesConfig);

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