Esempio n. 1
0
        public override void Configure(Container container)
        {
            RequestFilters.Add((req, resp, requestDto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod,
                                       req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            ResponseFilters.Add((req, resp, dto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode,
                                       resp.ContentType));
            });

            JsConfig.DateHandler = JsonDateHandler.ISO8601;
            Plugins.Add(new RequestLogsFeature());

            ConfigureQueues(container);

            var config = new EndpointHostConfig();

            if (m_debugEnabled)
            {
                config.DebugMode             = true;
                config.WriteErrorsToResponse = true;
                config.ReturnsInnerException = true;
            }

            SetConfig(config);
        }
Esempio n. 2
0
        public override void Configure(Funq.Container container)
        {
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            // Remove some unused features that by default are included
            Plugins.RemoveAll(p => p is CsvFormat);
            Plugins.RemoveAll(p => p is MetadataFeature);

            // Get disable features specified in Config file (i.e. Soap, Metadata, etc.)
            var disabled = AppHostConfigHelper.GetDisabledFeatures();

            // Construct Service Endpoint Host Configuration store
            var config = new EndpointHostConfig
            {
                DefaultContentType              = ContentType.Json,
                WriteErrorsToResponse           = false,
                EnableFeatures                  = Feature.All.Remove(disabled),
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    ContentType.Html
                },
            };

            // Apply configuration
            SetConfig(config);

            // Initialize Databases & associated Routes
            container.InitDatabaseRoutes(Routes);

            // Register Cache Clients
            container.Register <ICacheClient>(new MemoryCacheClient());

            // Register Redis Client Manager
            container.Register <IRedisClientsManager>(c =>
                                                      new PooledRedisClientManager("localhost:6379"));
        }
Esempio n. 3
0
        public override void Configure(Container container)
        {
            EndpointHostConfig config = _bootstrapper
                                        .BootstrapAll(this);

            SetConfig(config);
        }
Esempio n. 4
0
 public SwaggerUiConfig(EndpointHostConfig endpointHostConfig, string title = null, string apiVersion = null, bool useBasicAuth = false) : this()
 {
     HostConfig   = endpointHostConfig;
     Title        = title;
     ApiVersion   = apiVersion;
     UseBasicAuth = useBasicAuth;
 }
Esempio n. 5
0
        public override void Configure(Container container)
        {
            LoadConfigEnv();

            RequestFilters.Add((req, resp, requestDto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod,
                                       req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            ResponseFilters.Add((req, resp, dto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode,
                                       resp.ContentType));
            });

            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] { new CredentialsAuthProvider() })
                        );
            Plugins.Add(new RegistrationFeature());
            Plugins.Add(new SessionFeature());
            Plugins.Add(new RequestLogsFeature());


            container.Register <IRedisClientsManager>(c =>
                                                      new PooledRedisClientManager(m_redisConnString));
            container.Register <ICacheClient>(c =>
                                              (ICacheClient)c.Resolve <IRedisClientsManager>()
                                              .GetCacheClient())
            .ReusedWithin(Funq.ReuseScope.None);


            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(m_pgConnString, PostgreSQLDialectProvider.Instance)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info
            container.Register <IUserAuthRepository>(c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));


            Plugins.Add(new ValidationFeature());

            container.RegisterValidators(typeof(CreateQueueValidator).Assembly);
            container.RegisterValidators(typeof(CreateTopicValidator).Assembly);

            var config = new EndpointHostConfig();

            if (m_debugEnabled)
            {
                config.DebugMode             = true; //Show StackTraces in service responses during development
                config.WriteErrorsToResponse = true;
                config.ReturnsInnerException = true;
            }

            SetConfig(config);
            CreateMissingTables(container);
        }
Esempio n. 6
0
        /// <summary>Override Configure method</summary>
        public override void Configure(Container container)
        {
            System.Configuration.Configuration rootWebConfig =
                System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(null);

            JsConfig.ExcludeTypeInfo     = false;
            JsConfig.IncludePublicFields = false;

            log4net.Config.XmlConfigurator.Configure();

            //Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
            var config = new EndpointHostConfig {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin", "*" }
                    //{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" }//,
                },
                DebugMode                      = true,  //Enable StackTraces in development
                WebHostUrl                     = rootWebConfig.AppSettings.Settings["BaseUrl"].Value,
                WriteErrorsToResponse          = false, //custom exception handling
                ServiceStackHandlerFactoryPath = "t2api",
                //WsdlServiceNamespace = "t2api",
                ReturnsInnerException = false
            };

            config.AllowFileExtensions.Add("json");
            config.AllowFileExtensions.Add("geojson");
            config.AllowFileExtensions.Add("woff2");
            base.SetConfig(config);

            this.ContentTypeFilters.Register("application/opensearchdescription+xml", AppHost.CustomXmlSerializer, null);
            ResponseFilters.Add(CustomResponseFilter);

            this.ServiceExceptionHandler = ExceptionHandling.ServiceExceptionHandler;
        }
Esempio n. 7
0
 public void Init(
     Container container,
     IList <IPlugin> plugins,
     IServiceRoutes routes,
     EndpointHostConfig endpointHostconfig
     )
 {
 }
Esempio n. 8
0
        public void RegisterService(Type serviceType, params string[] atRestPaths)
        {
            if (Config == null)
            {
                Config = new EndpointHostConfig("BasicAppHost", new ServiceManager(Assembly.GetExecutingAssembly()));
            }

            Config.ServiceManager.RegisterService(serviceType);
        }
Esempio n. 9
0
 void setEndpointHostConfig(EndpointHostConfig endpointHostconfig)
 {
     endpointHostconfig = new EndpointHostConfig
     {
         EnableFeatures = Feature.All.Remove(
             Feature.Xml | Feature.Jsv |
             Feature.Csv | Feature.Soap),
         DefaultContentType = ContentType.Json
     };
 }
		protected void SetConfig(EndpointHostConfig config)
		{
			if (config.ServiceName == null)
				config.ServiceName = EndpointHost.Config.ServiceName;

			if (config.ServiceManager == null)
				config.ServiceManager = EndpointHost.Config.ServiceManager;

			config.ServiceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions;

			EndpointHost.Config = config;

			JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers;
			JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers;
		}
Esempio n. 11
0
        public EndpointHostConfig WithConfig()
        {
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            var config = new EndpointHostConfig
            {
                EnableFeatures                 = Feature.All.Remove(Feature.Jsv | Feature.Soap | Feature.Xml),
                DefaultContentType             = ContentType.Json,
                ServiceStackHandlerFactoryPath = "api",
            };

            // not defined members of an enumeration will return a 404 (not found)
            config.MapExceptionToStatusCode[typeof(RequestBindingException)] = 404;

            return(config);
        }
Esempio n. 12
0
        public override void Configure(Container container)
        {
            RequestFilters.Add((req, resp, requestDto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}", DateTimeOffset.Now.Ticks, req.HttpMethod,
                                       req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            ResponseFilters.Add((req, resp, dto) => {
                var log = LogManager.GetLogger(GetType());
                log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks, resp.StatusCode,
                                       resp.ContentType));
            });

            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] { new CredentialsAuthProvider() })
                        );
            Plugins.Add(new RegistrationFeature());
            Plugins.Add(new SessionFeature());
            Plugins.Add(new RequestLogsFeature());

            container.Register <ICacheClient> (new MemoryCacheClient());

            container.Register <IDbConnectionFactory> (
                new OrmLiteConnectionFactory(@"Data Source=db.sqlite;Version=3;",
                                             SqliteOrmLiteDialectProvider.Instance)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info
            container.Register <IUserAuthRepository> (c => new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory> ()));

            Plugins.Add(new ValidationFeature());

            var config = new EndpointHostConfig();

            if (m_debugEnabled)
            {
                config.DebugMode             = true; //Show StackTraces in service responses during development
                config.WriteErrorsToResponse = true;
                config.ReturnsInnerException = true;
            }

            SetConfig(config);
        }
Esempio n. 13
0
        public override void Configure(Container container)
        {
            LogManager.LogFactory = new NLogFactory();
            this.RequestFilters.Add((req, resp, requestDto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Info(string.Format("REQ {0}: {1} {2} {3} {4} {5}",
                                       DateTimeOffset.Now.Ticks, req.HttpMethod,
                                       req.OperationName, req.RemoteIp, req.RawUrl, req.UserAgent));
            });
            this.ResponseFilters.Add((req, resp, dto) => {
                ILog log = LogManager.GetLogger(GetType());
                log.Info(string.Format("RES {0}: {1} {2}", DateTimeOffset.Now.Ticks,
                                       resp.StatusCode, resp.ContentType));
            });

            container.Register <IDbConnectionFactory> (
                new OrmLiteConnectionFactory(@"Data Source=db.sqlite;Version=3;",
                                             SqliteOrmLiteDialectProvider.Instance)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            Plugins.Add(new ValidationFeature());
            container.RegisterValidators(typeof(AppHost).Assembly);

            var config = new EndpointHostConfig();

            if (m_debugEnabled)
            {
                config.DebugMode             = true;     //Show StackTraces in service responses during development
                config.WriteErrorsToResponse = true;
                config.ReturnsInnerException = true;
            }

            SetConfig(config);

            SetUpDb(container);
        }
Esempio n. 14
0
        public void Init(
            Container container,
            IList <IPlugin> plugins,
            IServiceRoutes routes,
            EndpointHostConfig endpointHostconfig
            )
        {
            LogManager.LogFactory = new NLogFactory();

            //Configure User Defined REST Paths
            //Routes
            //  .Add<Hello>("/hello")
            //  .Add<Hello>("/hello/{Name*}");

            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            setPlugins(plugins);

            registerDependencies(container);

            setEndpointHostConfig(endpointHostconfig);
        }
Esempio n. 15
0
        // private AppBootstrapper bootstrap(IContentTypeFilter filter)
        // ...

        #endregion

        // finish configuration. Last method in the chain
        private void endBootstrapping(EndpointHostConfig config)
        {
            // do whatever is needed in the configuration
        }
        protected void SetConfig(EndpointHostConfig config)
        {
            if (config.ServiceName == null)
                config.ServiceName = EndpointHost.Config.ServiceName;

            if (config.ServiceManager == null)
                config.ServiceManager = EndpointHost.Config.ServiceManager;

            config.ServiceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions;

            EndpointHost.Config = config;

            JsonDataContractSerializer.Instance.UseBcl = config.UseBclJsonSerializers;
            JsonDataContractDeserializer.Instance.UseBcl = config.UseBclJsonSerializers;
        }
 protected void SetConfig(EndpointHostConfig config)
 {
     EndpointHost.Config = config;
     this.serviceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions;
 }
Esempio n. 18
0
 protected void SetConfig(EndpointHostConfig config)
 {
     EndpointHost.Config = config;
     this.serviceManager.ServiceController.EnableAccessRestrictions = config.EnableAccessRestrictions;
 }
Esempio n. 19
0
        public override void Configure(Funq.Container container)
        {
            this.ComposeObjectGraph(container);

            JsConfig.DateHandler = JsonDateHandler.ISO8601;

            Plugins.Add(new SwaggerFeature());

            // register our custom exception handling
            this.ExceptionHandler        = Rainy.ErrorHandling.ExceptionHandler.CustomExceptionHandler;
            this.ServiceExceptionHandler = Rainy.ErrorHandling.ExceptionHandler.CustomServiceExceptionHandler;

            string swagger_path;

            if (JsonConfig.Config.Global.Development)
            {
                swagger_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../swagger-ui/");
            }
            else
            {
                swagger_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "swagger-ui/");
            }
            var swagger_handler = new FilesystemHandler("/swagger-ui/", swagger_path);

            IHttpHandlerDecider uihandler;
            IHttpHandlerDecider fontshandler = null;

            if (JsonConfig.Config.Global.Development)
            {
                var webui_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../../Rainy.UI/dist/");
                uihandler = (IHttpHandlerDecider) new FilesystemHandler("/", webui_path);
                var fonts_path = Path.Combine(Path.GetDirectoryName(this.GetType().Assembly.Location), "../../../Rainy.UI/dist/fonts/");
                fontshandler = (IHttpHandlerDecider) new FilesystemHandler("/fonts/", fonts_path);
            }
            else
            {
                uihandler = (IHttpHandlerDecider) new EmbeddedResourceHandler("/", this.GetType().Assembly, "Rainy.WebService.Admin.UI");
            }

            this.RequestFilters.Add((req, resp, dto) => {
                if (req.HttpMethod == "OPTIONS")
                {
                    resp.StatusCode = 200;
                    resp.End();
                }
            });

            // BUG HACK
            // GlobalResponseHeaders are not cleared between creating instances of a new config
            // this will be fatal (duplicate key error) for unit tests so we clear the headers
            EndpointHostConfig.Instance.GlobalResponseHeaders.Clear();

            var endpoint_config = new EndpointHostConfig {
                EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //DefaultRedirectPath = "/admin/",

                // not all tomboy clients send the correct content-type
                // so we force application/json
                DefaultContentType = ContentType.Json,

                RawHttpHandlers =
                {
                    uihandler.CheckAndProcess,
                    fontshandler.CheckAndProcess,
                    swagger_handler.CheckAndProcess
                },

                // enable cors
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                                    },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"      },
                    // time in seconds preflight responses can be cached by the client
                    { "Access-Control-Max-Age",       "1728000"                              },
//					{ "Access-Control-Max-Age", "1" },

                    // the Authority header must be whitelisted; it is sent be the rainy-ui
                    // for authentication
                    { "Access-Control-Allow-Headers", "Content-Type, Authority, AccessToken" },
                },
            };

            endpoint_config.AddMaxAgeForStaticMimeTypes["text/html"]       = new TimeSpan(1, 0, 0);
            endpoint_config.AddMaxAgeForStaticMimeTypes["text/css"]        = new TimeSpan(1, 0, 0);
            endpoint_config.AddMaxAgeForStaticMimeTypes["text/javascript"] = new TimeSpan(1, 0, 0);
            SetConfig(endpoint_config);
        }