Пример #1
0
 public RequestDispatchFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
     : base(operation, endpoint, converter, behavior)
 {
 }
Пример #2
0
        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());

                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);
            }
        }
        public void Start()
        {
            Logger?.Info($"{ServiceName} starting.");
            var openSucceeded = false;

            try
            {
                _serviceHost?.Close();

                _serviceHost = new ServiceHost(typeof(TServiceImplementation));
            }
            catch (Exception e)
            {
                Logger?.Error(e, $"Caught exception while creating {ServiceName}:{e}");
                return;
            }

            try
            {
                var webHttpBinding = new WebHttpBinding(WebHttpSecurityMode.None);
                _serviceHost.AddServiceEndpoint(typeof(TServiceContract), webHttpBinding, _serviceUri);

                var webHttpBehavior = new WebHttpBehavior
                {
                    DefaultOutgoingResponseFormat = WebMessageFormat.Json
                };
                _serviceHost.Description.Endpoints[0].Behaviors.Add(webHttpBehavior);

                _serviceHost.Open();
                openSucceeded = true;
            }
            catch (Exception ex)
            {
                Logger?.Error(ex, $"Caught exception while starting {ServiceName} : {ex}");
            }
            finally
            {
                if (!openSucceeded)
                {
                    _serviceHost.Abort();
                }
            }

            if (_serviceHost.State == CommunicationState.Opened)
            {
                Logger?.Info($"{ServiceName} started at {_serviceUri}.");
            }
            else
            {
                Logger?.Fatal($"{ServiceName} failed to open.");
                var closeSucceeded = false;
                try
                {
                    _serviceHost.Close();
                    closeSucceeded = true;
                }
                catch (Exception ex)
                {
                    Logger?.Error(ex, $"{ServiceName} failed to close: {ex}");
                }
                finally
                {
                    if (!closeSucceeded)
                    {
                        _serviceHost.Abort();
                    }
                }
            }
        }
Пример #4
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("Запуск службы правил доставки...");
            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.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();
                var backupDistrictService = new BackupDistrictService();

                DeliveryRulesInstanceProvider deliveryRulesInstanceProvider = new DeliveryRulesInstanceProvider(deliveryRepository, backupDistrictService);
                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
                backupDistrictService.StartAutoUpdateTask();

                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);
            }
        }
Пример #5
0
        private ServiceHost StartNetTcpAndHttpService(ModelManager modelManager, Boolean onlyNetTcp)
        {
            Uri[] baseAddresses;
            if (onlyNetTcp)
            {
                baseAddresses = new Uri[] {
                    new Uri($"net.tcp://localhost:{FiskmoMTEngineSettings.Default.MtServicePort}/")
                };
            }
            else
            {
                baseAddresses = new Uri[] {
                    new Uri($"net.tcp://localhost:{FiskmoMTEngineSettings.Default.MtServicePort}/"),
                    new Uri($"http://localhost:8500/")
                };
            };

            var mtService = new MTService(modelManager);

            Log.Information($"Creating service host with following URIs: {String.Join(",",baseAddresses.Select(x => x.ToString()))}");

            var selfHost = new ServiceHost(mtService, baseAddresses);

            // Check to see if the service host already has a ServiceMetadataBehavior
            ServiceMetadataBehavior smb = selfHost.Description.Behaviors.Find <ServiceMetadataBehavior>();

            // If not, add one
            if (smb == null)
            {
                smb = new ServiceMetadataBehavior();
            }
            smb.MetadataExporter.PolicyVersion = PolicyVersion.Policy15;
            selfHost.Description.Behaviors.Add(smb);
            // Add MEX endpoint
            selfHost.AddServiceEndpoint(
                ServiceMetadataBehavior.MexContractName,
                MetadataExchangeBindings.CreateMexTcpBinding(),
                "mex"
                );

            var nettcpBinding = new NetTcpBinding();

            //Use default net.tcp security, which is based on Windows authentication:
            //using the service is only possible from other computers in the same domain.
            //TODO: add a checkbox (with warning) in the UI for using security mode None,
            //to allow connections from IP range (also add same checkbox to clients).

            //nettcpBinding.Security.Mode = SecurityMode.None;

            /*nettcpBinding.Security.Mode = SecurityMode.Transport;
             * nettcpBinding.Security.Transport.ClientCredentialType =
             *  TcpClientCredentialType.Windows;*/

            //Customization tuning sets tend to be big
            nettcpBinding.MaxReceivedMessageSize = 20000000;
            selfHost.AddServiceEndpoint(typeof(IMTService), nettcpBinding, "MTService");

            if (!onlyNetTcp)
            {
                selfHost.AddServiceEndpoint(typeof(IMTService), new WebHttpBinding(), "MTRestService");
                WebHttpBehavior helpBehavior = new WebHttpBehavior();
                helpBehavior.HelpEnabled = true;
                selfHost.Description.Endpoints[2].Behaviors.Add(helpBehavior);
            }

            Log.Information($"Opening the service host");
            selfHost.Open();
            return(selfHost);
        }
Пример #6
0
        public WebMessageFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
        {
            this.operation = operation;
            this.endpoint  = endpoint;
            this.converter = converter;
            this.behavior  = behavior;
            ApplyWebAttribute();
#if !NET_2_1
            // This is a hack for WebScriptEnablingBehavior
            var jqc = converter as JsonQueryStringConverter;
            if (jqc != null)
            {
                BodyName = jqc.CustomWrapperName;
            }
#endif
        }
Пример #7
0
 protected WebDispatchMessageFormatter(OperationDescription operation, ServiceEndpoint endpoint, QueryStringConverter converter, WebHttpBehavior behavior)
     : base(operation, endpoint, converter, behavior)
 {
 }
    protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)
    {
        string[] urlTokens = baseAddresses[0].AbsolutePath.Split('/');
        string   version   = urlTokens[1].ToUpper();

        Type[] contractInterfaces = serviceType.GetInterfaces().Where(i => i.GetCustomAttributes(true).Where(a => a.GetType() == typeof(System.ServiceModel.ServiceContractAttribute)).Any()).ToArray();
        Type   contractType       = contractInterfaces.Where(i => i.Namespace.ToUpper().Contains(version)).Single();

        ServiceHost host = base.CreateServiceHost(serviceType, baseAddresses);

        WSHttpBinding wsHttpBinding = new WSHttpBinding();

        wsHttpBinding.SendTimeout            = new TimeSpan(0, 5, 0);
        wsHttpBinding.MaxReceivedMessageSize = Int32.MaxValue;
        wsHttpBinding.BypassProxyOnLocal     = true;
        wsHttpBinding.Security.Mode          = SecurityMode.None;
        //wsHttpBinding.TransactionFlow = true;
        //wsHttpBinding.ReaderQuotas.MaxStringContentLength = Int32.MaxValue;

        //ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, wsHttpBinding, "");

        WebHttpBinding webHttpBinding = new WebHttpBinding();

        webHttpBinding.Security.Mode = WebHttpSecurityMode.None;
        webHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
        webHttpBinding.Security.Transport.ProxyCredentialType  = HttpProxyCredentialType.None;
        webHttpBinding.BypassProxyOnLocal = true;

        ServiceEndpoint endpoint = host.AddServiceEndpoint(contractType, webHttpBinding, "");

        WebHttpBehavior webHttpBehavior = new WebHttpBehavior();

        webHttpBehavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
        //behavior.DefaultBodyStyle = WebMessageBodyStyle.Bare;
        webHttpBehavior.DefaultBodyStyle      = WebMessageBodyStyle.Wrapped;
        webHttpBehavior.FaultExceptionEnabled = true;

        endpoint.Behaviors.Add(webHttpBehavior);

        ServiceMetadataBehavior metadataBehaviour;

        if ((host.Description.Behaviors.Contains(typeof(ServiceMetadataBehavior))))
        {
            metadataBehaviour = (ServiceMetadataBehavior)host.Description.Behaviors[typeof(ServiceMetadataBehavior)];
        }
        else
        {
            metadataBehaviour = new ServiceMetadataBehavior();
            host.Description.Behaviors.Add(metadataBehaviour);
        }
        metadataBehaviour.HttpGetEnabled = true;

        ServiceDebugBehavior debugBehaviour;

        if (host.Description.Behaviors.Contains(typeof(ServiceDebugBehavior)))
        {
            debugBehaviour = (ServiceDebugBehavior)host.Description.Behaviors[typeof(ServiceDebugBehavior)];
        }
        else
        {
            debugBehaviour = new ServiceDebugBehavior();
            host.Description.Behaviors.Add(debugBehaviour);
        }
        debugBehaviour.IncludeExceptionDetailInFaults = true;

        return(host);
    }