示例#1
0
            public override void Configure(Container container)
            {
                // Force a response type of JSON.
                RequestFilters.Add(
                    (IHttpRequest httpReq, IHttpResponse httpResp, object requestDto) =>
                {
                    var sessionId = httpReq.ResponseContentType = "text/json";
                });

                ResponseFilters.Add((IHttpRequest request, IHttpResponse response, object dto) =>
                {
                    var statusCode = dto as string;
                    if (statusCode != null)
                    {
                        response.StatusCode = int.Parse(statusCode);
                    }

                    var dict = dto as Dictionary <string, object>;
                    if (dict != null)
                    {
                        var val  = dict["value"];
                        var json = val as JsonObject;
                        if (json != null)
                        {
                            Logger.Info(JsonSerializer.SerializeToString(json));
                        }
                        else
                        {
                            Logger.Info(val.ToString());
                        }
                    }
                });
            }
示例#2
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;
        }
示例#3
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);
        }
示例#4
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);
        }
示例#5
0
 private void ConfigureNotFound()
 {
     ResponseFilters.Add((request, response, obj) =>
     {
         if (obj == null)
         {
             response.StatusCode = (int)HttpStatusCode.NotFound;
         }
     });
 }
示例#6
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);
        }
示例#7
0
        /// <summary>
        /// Adds the rest handlers.
        /// </summary>
        /// <param name="services">The services.</param>
        public void Init(IEnumerable <IService> services)
        {
            _restServices.AddRange(services);

            ServiceController = CreateServiceController();

            _logger.Info("Calling ServiceStack AppHost.Init");

            ServiceController.Init(this);

            var requestFilters = _appHost.GetExports <IRequestFilter>().ToList();

            foreach (var filter in requestFilters)
            {
                RequestFilters.Add(filter.Filter);
            }

            ResponseFilters.Add(new ResponseFilter(_logger).FilterResponse);
        }
示例#8
0
 public override void Configure(Container container)
 {
     // I add some request/response filters to set up the correct database
     // connection for the integration test database
     RequestFilters.Add((httpRequest, httpResponse, requestDto) =>
     {
         var dbContext = MakeSomeDatabaseContext();
         httpRequest.Items["DatabaseIntegrationTestContext"] = dbContext;
     });
     ResponseFilters.Add((httpRequest, httpResponse, responseDto) =>
     {
         var dbContext = httpRequest.Items["DatabaseIntegrationTestContext"] as DbContext;
         if (dbContext != null)
         {
             dbContext.Dispose();
             httpRequest.Items.Remove("DatabaseIntegrationTestContext");
         }
     });
     // now include any configuration you want to share between this
     // and your regular AppHost, e.g. IoC setup, EndpointHostConfig,
     // JsConfig setup, adding Plugins, etc.
     SharedAppHost.Configure(container);
 }
示例#9
0
        /// <summary>
        /// Configures the specified container.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            JsConfig.DateHandler       = JsonDateHandler.ISO8601;
            JsConfig.ExcludeTypeInfo   = true;
            JsConfig.IncludeNullValues = false;

            SetConfig(new EndpointHostConfig
            {
                DefaultRedirectPath = DefaultRedirectPath,

                MapExceptionToStatusCode =
                {
                    { typeof(InvalidOperationException),  422 },
                    { typeof(ResourceNotFoundException),  404 },
                    { typeof(FileNotFoundException),      404 },
                    { typeof(DirectoryNotFoundException), 404 }
                },

                DebugMode = true,

                ServiceName = ServerName,

                LogFactory = LogManager.LogFactory,

                // The Markdown feature causes slow startup times (5 mins+) on cold boots for some users
                // Custom format allows images
                EnableFeatures = Feature.Csv | Feature.Html | Feature.Json | Feature.Jsv | Feature.Metadata | Feature.Xml | Feature.CustomFormat
            });

            container.Adapter = _containerAdapter;

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new CorsFeature());

            ResponseFilters.Add(FilterResponse);
        }
        /// <summary>
        ///   Process image looking for interest points.
        /// </summary>
        ///
        /// <param name="image">Source image data to process.</param>
        ///
        /// <returns>Returns list of found interest points.</returns>
        ///
        /// <exception cref="UnsupportedImageFormatException">
        ///   The source image has incorrect pixel format.
        /// </exception>
        ///
        public List <SurfPoint> ProcessImage(UnmanagedImage image)
        {
            // check image format
            if (
                (image.PixelFormat != PixelFormat.Format8bppIndexed) &&
                (image.PixelFormat != PixelFormat.Format24bppRgb) &&
                (image.PixelFormat != PixelFormat.Format32bppRgb) &&
                (image.PixelFormat != PixelFormat.Format32bppArgb)
                )
            {
                throw new UnsupportedImageFormatException("Unsupported pixel format of the source image.");
            }

            // make sure we have grayscale image
            UnmanagedImage grayImage = null;

            if (image.PixelFormat == PixelFormat.Format8bppIndexed)
            {
                grayImage = image;
            }
            else
            {
                // create temporary grayscale image
                grayImage = Grayscale.CommonAlgorithms.BT709.Apply(image);
            }


            // 1. Compute the integral for the given image
            integral = IntegralImage.FromBitmap(grayImage);


            // 2. Compute interest point response map
            if (responses == null ||
                image.Width != responses.Width || image.Height != responses.Height)
            {
                responses = new ResponseFilters(image.Width, image.Height, octaves, initial);
            }

            responses.Compute(integral);


            // 3. Suppress non-maximum points
            List <SurfPoint> featureList = new List <SurfPoint>();

            // for each image pyramid in the response map
            foreach (ResponseLayer[] layers in responses)
            {
                // Grab the three layers forming the pyramid
                ResponseLayer bot = layers[0]; // bottom layer
                ResponseLayer mid = layers[1]; // middle layer
                ResponseLayer top = layers[2]; // top layer

                int border = (top.Size + 1) / (2 * top.Step);

                int tstep = top.Step;
                int mstep = mid.Size - bot.Size;

                int mscale = mid.Width / top.Width;
                int bscale = bot.Width / top.Width;

                int r = 1;

                // for each row
                for (int y = border + 1; y < top.Height - border; y++)
                {
                    // for each pixel
                    for (int x = border + 1; x < top.Width - border; x++)
                    {
                        float currentValue = mid.Responses[y * mscale, x *mscale];

                        // for each windows' row
                        for (int i = -r; (currentValue >= threshold) && (i <= r); i++)
                        {
                            // for each windows' pixel
                            for (int j = -r; j <= r; j++)
                            {
                                int yi = y + i;
                                int xj = x + j;

                                // for each response layer
                                if (top.Responses[yi, xj] >= currentValue ||
                                    bot.Responses[yi * bscale, xj *bscale] >= currentValue || ((i != 0 || j != 0) &&
                                                                                               mid.Responses[yi * mscale, xj *mscale] >= currentValue))
                                {
                                    currentValue = 0;
                                    break;
                                }
                            }
                        }

                        // check if this point is really interesting
                        if (currentValue >= threshold)
                        {
                            // interpolate to sub-pixel precision
                            double[] offset = interpolate(y, x, top, mid, bot);

                            if (System.Math.Abs(offset[0]) < 0.5 &&
                                System.Math.Abs(offset[1]) < 0.5 &&
                                System.Math.Abs(offset[2]) < 0.5)
                            {
                                featureList.Add(new SurfPoint(
                                                    (float)((x + offset[0]) * tstep),
                                                    (float)((y + offset[1]) * tstep),
                                                    (float)(0.1333f * (mid.Size + offset[2] * mstep)),
                                                    mid.Laplacian[y * mscale, x * mscale]));
                            }
                        }
                    }
                }
            }

            return(featureList);
        }
示例#11
0
        /// <summary>
        /// Configures the specified container.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            JsConfig.DateHandler       = JsonDateHandler.ISO8601;
            JsConfig.ExcludeTypeInfo   = true;
            JsConfig.IncludeNullValues = false;

            SetConfig(new EndpointHostConfig
            {
                DefaultRedirectPath = DefaultRedirectPath,

                // Tell SS to bubble exceptions up to here
                WriteErrorsToResponse = false
            });

            container.Adapter = new ContainerAdapter(ApplicationHost);

            Plugins.Add(new SwaggerFeature());
            Plugins.Add(new CorsFeature());

            ServiceStack.Logging.LogManager.LogFactory = new NLogFactory();

            ResponseFilters.Add((req, res, dto) =>
            {
                var exception = dto as Exception;

                if (exception != null)
                {
                    _logger.ErrorException("Error processing request", exception);

                    if (!string.IsNullOrEmpty(exception.Message))
                    {
                        res.AddHeader("X-Application-Error-Code", exception.Message.Replace(Environment.NewLine, " "));
                    }
                }

                if (dto is CompressedResult)
                {
                    // Per Google PageSpeed
                    // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
                    // The correct version of the resource is delivered based on the client request header.
                    // This is a good choice for applications that are singly homed and depend on public proxies for user locality.
                    res.AddHeader("Vary", "Accept-Encoding");
                }

                var hasOptions = dto as IHasOptions;

                if (hasOptions != null)
                {
                    // Content length has to be explicitly set on on HttpListenerResponse or it won't be happy
                    string contentLength;

                    if (hasOptions.Options.TryGetValue("Content-Length", out contentLength) && !string.IsNullOrEmpty(contentLength))
                    {
                        var length = long.Parse(contentLength);

                        if (length > 0)
                        {
                            var response = (HttpListenerResponse)res.OriginalResponse;

                            response.ContentLength64 = length;

                            // Disable chunked encoding. Technically this is only needed when using Content-Range, but
                            // anytime we know the content length there's no need for it
                            response.SendChunked = false;
                        }
                    }
                }
            });
        }
示例#12
0
        public override void Configure(Container containerFunq)
        {
            Log.Info("Configure AppHost");
            new Module().Init(UnityServiceLocator.Instance);

            var container = UnityServiceLocator.Instance;

            containerFunq.Adapter = new UnityContainerAdapter(container, new Logger());

            var serverSettings = container.Resolve <IServerSettings>();

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[]
            {
                new CustomCredentialsAuthProvider(UnityContainerExtensions.Resolve <ICommandBus>(container),
                                                  UnityContainerExtensions.Resolve <IAccountDao>(container),
                                                  UnityContainerExtensions.Resolve <IPasswordService>(container),
                                                  UnityContainerExtensions.Resolve <IServerSettings>(container)),
                new CustomFacebookAuthProvider(UnityContainerExtensions.Resolve <IAccountDao>(container)),
                new CustomTwitterAuthProvider(UnityContainerExtensions.Resolve <IAccountDao>(container))
            }));

            Plugins.Add(new ValidationFeature());
            containerFunq.RegisterValidators(typeof(SaveFavoriteAddressValidator).Assembly);

            RequestFilters.Add((httpReq, httpResp, requestDto) =>
            {
                var authSession = httpReq.GetSession();
                if (authSession != null && !string.IsNullOrEmpty(authSession.UserAuthId))
                {
                    var account = container.Resolve <IAccountDao>().FindById(new Guid(authSession.UserAuthId));
                    if (account == null || account.DisabledByAdmin)
                    {
                        httpReq.RemoveSession();
                    }
                }
            });


            SetConfig(new EndpointHostConfig
            {
                GlobalResponseHeaders =
                {
                    { "Access-Control-Allow-Origin",  "*"                               },
                    { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                },

                EnableFeatures = (serverSettings.ServerData.ShowAPIMetadata ? Feature.All : Feature.All.Remove(Feature.Metadata))
            });


            ContentTypeFilters.Register("text/x-csv", CsvCustomSerializer.SerializeToStream, CsvCustomSerializer.DeserializeFromStream);
            ResponseFilters.Add((req, res, dto) =>
            {
                if (req.ResponseContentType == "text/x-csv")
                {
                    res.AddHeader(HttpHeaders.ContentDisposition,
                                  string.Format("attachment;filename={0}.csv", req.OperationName));
                }
            });

            Log.Info("Configure AppHost finished");
        }
 public FragmentApplicationBuilderOptions AddResponseFilter(Func <HttpContext, FragmentResponseFilter> responseFilterCreator)
 {
     ResponseFilters.Add(responseFilterCreator);
     return(this);
 }