コード例 #1
0
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        public override void Configure(Container container)
        {
            //Config examples
            //this.Plugins.Add(new PostmanFeature());
            //this.Plugins.Add(new CorsFeature());

            //数据库连接
            var dbFactory = new OrmLiteConnectionFactory("Data Source = 192.168.0.188;Initial Catalog =QRPay_ALL_DEV;User Id = sa;Password = Atbms1q2w3e4r;", SqlServerDialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            //全局json响应  根据类型匹配
            JsConfig.Init(new Config
            {
                TextCase             = TextCase.SnakeCase,
                ExcludeDefaultValues = true,
            });
            JsConfig <Guid> .SerializeFn     = guid => guid.ToString("D");
            JsConfig <TimeSpan> .SerializeFn = time =>
                                               (time.Ticks < 0 ? "-" : "") + time.ToString("hh':'mm':'ss'.'fffffff");


            //可以将请求和响应做一个缓存
            this.PreRequestFilters.Add((httpReq, httpRes) => {
                httpReq.UseBufferedStream = true;  // Buffer Request Input
                httpRes.UseBufferedStream = true;  // Buffer Response Output
            });

            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 100
            });

            //开启Swgger
            Plugins.Add(new SwaggerFeature());
        }
コード例 #2
0
        public string Serialize(T m)
        {
            JsConfig.Init(config);
            string s = ServiceStack.Text.JsonSerializer.SerializeToString(m);

            return(s);
        }
コード例 #3
0
 public void Allows_setting_config_before_Init()
 {
     JsConfig.MaxDepth = 1;
     JsConfig.Init(new Config {
         DateHandler = DateHandler.UnixTime
     });
 }
コード例 #4
0
        public void Can_override_TreatEnumAsInteger()
        {
            JsConfig.Init(new Config
            {
                TreatEnumAsInteger = false,
            });

            using (JsConfig.With(new Config
            {
                TreatEnumAsInteger = true
            }))
            {
                Assert.That(new GetDayOfWeekAsInt {
                    DayOfWeek = DayOfWeek.Tuesday
                }.ToJson(), Is.EqualTo("{\"DayOfWeek\":2}"));
                Assert.That("{\"DayOfWeek\":2}".FromJson <GetDayOfWeekAsInt>().DayOfWeek, Is.EqualTo(DayOfWeek.Tuesday));
            }

            Assert.That(new GetDayOfWeekAsInt {
                DayOfWeek = DayOfWeek.Tuesday
            }.ToJson(), Is.EqualTo("{\"DayOfWeek\":\"Tuesday\"}"));
            Assert.That("{\"DayOfWeek\":\"Tuesday\"}".FromJson <GetDayOfWeekAsInt>().DayOfWeek, Is.EqualTo(DayOfWeek.Tuesday));

            JsConfig.Reset();
        }
コード例 #5
0
        public override void Configure(Container container)
        {
            Plugins.Add(new MiniProfilerFeature());
            Plugins.Add(new RazorFormat());
            Plugins.Add(new ServerEventsFeature
            {
                OnCreated = (sub, req) =>
                {
                    sub.ServerArgs = new Dictionary <string, string>
                    {
                        { "server-arg", "1" }
                    };
                }
            });

            container.Register(new DataSource());

#if postgres
            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(
                    Environment.GetEnvironmentVariable("PGSQL_CONNECTION") ??
                    "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
                    PostgreSqlDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });
#else
            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });
#endif

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Rockstar>();
                db.Insert(Rockstar.SeedData);
            }

            JsConfig.Init(new Text.Config {
                TextCase = TextCase.CamelCase
            });

            //Register a external dependency-free
            container.Register <ICacheClient>(new MemoryCacheClient());

            //Enable Authentication an Registration
            ConfigureAuth(container);

            //Create your own custom User table
            using (var db = container.Resolve <IDbConnectionFactory>().Open())
                db.DropAndCreateTable <UserTable>();

            SetConfig(new HostConfig
            {
                DebugMode = true,
                AddRedirectParamsToQueryString = true,
            });
        }
コード例 #6
0
        public void Does_not_allow_setting_JsConfig_after_Init()
        {
            JsConfig.Init(new Config {
                DateHandler = DateHandler.UnixTime
            });

            Assert.Throws <NotSupportedException>(() => JsConfig.MaxDepth = 1000);
        }
コード例 #7
0
 protected void Application_Start()
 {
     JsConfig.Init(new Config {
         DateHandler = DateHandler.ISO8601,
         TextCase    = TextCase.CamelCase
     });
     //...
 }
コード例 #8
0
 /// <summary>
 /// Configure JSON serialization properties.
 /// </summary>
 /// <param name="container">The container.</param>
 private void ConfigureSerialization(Container container)
 {
     // Set JSON web services to return ISO8601 date format
     // Exclude type info during serialization as an effect of IoC
     JsConfig.Init(new ServiceStack.Text.Config {
         DateHandler     = DateHandler.ISO8601,
         ExcludeTypeInfo = true,
     });
 }
コード例 #9
0
        public void Does_not_allow_setting_multiple_inits_in_StrictMode()
        {
            JsConfig.Init();
            JsConfig.Init(new Config {
                MaxDepth = 1
            });

            Env.StrictMode = true;

            Assert.Throws <NotSupportedException>(() => JsConfig.Init());
        }
コード例 #10
0
        public void Does_combine_global_configs_in_multiple_inits()
        {
            JsConfig.Init(new Config {
                MaxDepth = 1
            });
            JsConfig.Init(new Config {
                DateHandler = DateHandler.UnixTime
            });

            Assert.That(JsConfig.MaxDepth, Is.EqualTo(1));
            Assert.That(JsConfig.DateHandler, Is.EqualTo(DateHandler.UnixTime));

            var newConfig = new Config();

            Assert.That(newConfig.MaxDepth, Is.EqualTo(1));
            Assert.That(newConfig.DateHandler, Is.EqualTo(DateHandler.UnixTime));
        }
コード例 #11
0
        public override void Configure(Container container)
        {
            Env.StrictMode = true;
            JsConfig.Init(new ServiceStack.Text.Config
            {
                DateHandler            = DateHandler.ISO8601,
                SkipDateTimeConversion = true,
                TextCase        = TextCase.CamelCase,
                ExcludeTypeInfo = true
            });

            SetConfig(new HostConfig
            {
                MapExceptionToStatusCode           = { { typeof(KeyNotFoundException), 404 } },
                Return204NoContentForEmptyResponse = true
            }
                      );
        }
コード例 #12
0
            public override void Configure(Container container)
            {
                JsConfig.Init(new Text.Config
                {
                    TextCase = TextCase.CamelCase,
                });

                SetConfig(new HostConfig
                {
                    DebugMode = false,
                });

                Plugins.Add(new ProtoBufFormat());

                GlobalRequestFilters.Add((req, res, dto) => {
                    if (dto is UncatchedException || dto is UncatchedExceptionAsync)
                    {
                        throw new ArgumentException();
                    }
                });

                //Custom global uncaught exception handling strategy
                this.UncaughtExceptionHandlers.Add((req, res, operationName, ex) =>
                {
                    res.WriteAsync($"UncaughtException {ex.GetType().Name}")
                    .ContinueWith(t => res.EndRequest(skipHeaders: true));
                });

                this.ServiceExceptionHandlers.Add((httpReq, request, ex) =>
                {
                    if (request is UncatchedException || request is UncatchedExceptionAsync)
                    {
                        throw ex;
                    }

                    if (request is CaughtException || request is CaughtExceptionAsync)
                    {
                        return(DtoUtils.CreateErrorResponse(request, new ArgumentException("ExceptionCaught")));
                    }

                    return(null);
                });
            }
コード例 #13
0
        protected void Application_Start()
        {
//            DbFactory = new OrmLiteConnectionFactory(
//                ConfigurationManager.AppSettings["connectionString"],
//                SqlServerDialect.Provider);

            JsConfig.Init(new ServiceStack.Text.Config {
                TextCase    = TextCase.CamelCase,
                DateHandler = DateHandler.ISO8601,
            });

            AreaRegistration.RegisterAllAreas();

            //WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);

            new AppHost().Init();
        }
コード例 #14
0
ファイル: AppHost.cs プロジェクト: ellwoods/ServiceStack
        public override void Configure(Container container)
        {
            Plugins.Add(new RequestLogsFeature {
                RequiredRoles = new[] { RoleNames.AllowAnon }
            });

            Plugins.Add(new RazorFormat());

            container.Register(new DataSource());

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.CreateTableIfNotExists <Rockstar>();
                db.Insert(Rockstar.SeedData);
            }

            JsConfig.Init(new Text.Config {
                TextCase = TextCase.CamelCase
            });

            //Register Typed Config some services might need to access
            var appSettings = new AppSettings();

            //Register a external dependency-free
            container.Register <ICacheClient>(new MemoryCacheClient());
            //Configure an alt. distributed persistent cache that survives AppDomain restarts. e.g Redis
            //container.Register<IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));

            //Enable Authentication an Registration
            ConfigureAuth(container);

            //Create your own custom User table
            using (var db = container.Resolve <IDbConnectionFactory>().Open())
                db.DropAndCreateTable <UserTable>();
        }
コード例 #15
0
ファイル: AppHost.cs プロジェクト: vabhishek1289/TechStacks
        /// <summary>
        /// Application specific configuration
        /// This method should initialize any IoC resources utilized by your web service classes.
        /// </summary>
        /// <param name="container"></param>
        public override void Configure(Container container)
        {
            PreConfigure(this);

            SetConfig(new HostConfig {
                AddRedirectParamsToQueryString = true,
                WebHostUrl = "http://techstacks.io", //for sitemap.xml urls
            });

            JsConfig.Init(new ServiceStack.Text.Config {
                DateHandler = DateHandler.ISO8601
            });

            if (AppSettings.GetString("OrmLite.Provider") == "Postgres")
            {
                container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory(AppSettings.GetString("OrmLite.ConnectionString"), PostgreSqlDialect.Provider));
            }
            else
            {
                container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory("~/App_Data/db.sqlite".MapHostAbsolutePath(), SqliteDialect.Provider));
            }

            var dbFactory = container.Resolve <IDbConnectionFactory>();

            this.Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[]
            {
                new TwitterAuthProvider(AppSettings),
                new GithubAuthProvider(AppSettings),
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false
                },
            }));

            container.Register(new TwitterUpdates(
                                   AppSettings.GetString("WebStacks.ConsumerKey"),
                                   AppSettings.GetString("WebStacks.ConsumerSecret"),
                                   AppSettings.GetString("WebStacks.AccessToken"),
                                   AppSettings.GetString("WebStacks.AccessSecret")));

            var authRepo = new OrmLiteAuthRepository <CustomUserAuth, UserAuthDetails>(dbFactory);

            container.Register <IUserAuthRepository>(authRepo);
            authRepo.InitSchema();

            using (var db = dbFactory.OpenDbConnection())
            {
                db.CreateTableIfNotExists <TechnologyStack>();
                db.CreateTableIfNotExists <Technology>();
                db.CreateTableIfNotExists <TechnologyChoice>();
                db.CreateTableIfNotExists <UserFavoriteTechnologyStack>();
                db.CreateTableIfNotExists <UserFavoriteTechnology>();

                RawHttpHandlers.Add(req => req.PathInfo == "/robots.txt" ? new NotFoundHttpHandler() : null);

                Plugins.Add(new SitemapFeature
                {
                    SitemapIndex =
                    {
                        new Sitemap {
                            AtPath       = "/sitemap-techstacks.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <TechnologyStack>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl
                            {
                                Location = new ClientTechnologyStack{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            }),
                        },
                        new Sitemap {
                            AtPath       = "/sitemap-technologies.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Technology>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl
                            {
                                Location = new ClientTechnology{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap
                        {
                            AtPath       = "/sitemap-users.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <CustomUserAuth>().OrderByDescending(x => x.ModifiedDate))
                                           .Map(x => new SitemapUrl
                            {
                                Location = new ClientUser{
                                    UserName = x.UserName
                                }.ToAbsoluteUri(),
                                LastModified    = x.ModifiedDate,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        }
                    }
                });
            }

            Plugins.Add(new RazorFormat());
            Plugins.Add(new ValidationFeature());
            Plugins.Add(new AutoQueryMetadataFeature
            {
                AutoQueryViewerConfig =
                {
                    ServiceDescription        = "Discover what technologies were used to create popular Websites and Apps",
                    ServiceIconUrl            = "/img/app/logo-76.png",
                    BackgroundColor           = "#0095F5",
                    TextColor                 = "#fff",
                    LinkColor                 = "#ffff8d",
                    BrandImageUrl             = "/img/app/brand.png",
                    BrandUrl                  = "http://techstacks.io",
                    BackgroundImageUrl        = "/img/app/bg.png",
                    IsPublic                  = true,
                    OnlyShowAnnotatedServices = true,
                }
            });
            Plugins.Add(new AutoQueryFeature {
                MaxLimit = 200
            });
            Plugins.Add(new AdminFeature());
            Plugins.Add(new OpenApiFeature());

            container.RegisterValidators(typeof(AppHost).Assembly);
            container.RegisterValidators(typeof(TechnologyServices).Assembly);

            RegisterTypedRequestFilter <IRegisterStats>((req, res, dto) =>
                                                        dbFactory.RegisterPageView(dto.GetStatsId()));

            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] { "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net", "http://null.jsbin.com" },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization"));
        }
コード例 #16
0
    // Configure your AppHost with the necessary configuration and dependencies your App needs
    public override void Configure(Container container)
    {
//            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);
        log = LogManager.GetLogger(typeof(AppHost));

        SetConfig(new HostConfig {
            // UseSameSiteCookies = true,
            AddRedirectParamsToQueryString = true,
        });

        JsConfig.Init(new Config {
            DateHandler = DateHandler.ISO8601
        });

        var dbFactory = container.Resolve <IDbConnectionFactory>();

        // enable server-side rendering, see: https://sharpscript.net
        Plugins.Add(new SharpPagesFeature {
            HtmlExtension = "htm",
            ScriptMethods =
            {
                new AppScriptMethods(GetCacheClient(), dbFactory)
            }
        });

        Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] {
            new TwitterAuthProvider(AppSettings),
            new GithubAuthProvider(AppSettings),
            new JwtAuthProvider(AppSettings)
            {
                RequireSecureConnection = false,
                UseTokenCookie          = true,
                CreatePayloadFilter     = (payload, session) => {
                    var githubAuth = session.ProviderOAuthAccess.Safe()
                                     .FirstOrDefault(x => x.Provider == "github");
                    payload["ats"] = githubAuth?.AccessTokenSecret;
                },
                PopulateSessionFilter = (session, obj, req) => {
                    session.ProviderOAuthAccess = new List <IAuthTokens> {
                        new AuthTokens {
                            Provider = "github", AccessTokenSecret = obj["ats"]
                        }
                    };
                }
            },
            new DiscourseAuthProvider {
                Provider     = "servicestack",
                DiscourseUrl = "https://forums.servicestack.net",
            },
        })
        {
            HtmlRedirect = "/"
        });

        container.Register <IMarkdownProvider>(c =>
                                               new GitHubApiMarkdownProvider(Environment.GetEnvironmentVariable("GITHUB_AUTH")));

        container.Register <ITwitterUpdates>(new TwitterUpdates(
                                                 AppSettings.GetString("WebStacks.ConsumerKey"),
                                                 AppSettings.GetString("WebStacks.ConsumerSecret"),
                                                 AppSettings.GetString("WebStacks.AccessToken"),
                                                 AppSettings.GetString("WebStacks.AccessSecret"))
        {
            BaseUrl = AppSettings.GetString("PublicBaseUrl"),
        });

        container.Register(new EmailProvider {
            UserName = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_USER") ??
                       AppSettings.GetString("smtp.UserName"),
            Password = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_PASS") ??
                       AppSettings.GetString("smtp.Password"),
            EnableSsl = true,
            Host      = AppSettings.GetString("smtp.Host"),
            Port      = AppSettings.Get <int>("smtp.Port"),
            Bcc       = AppSettings.GetString("smtp.Bcc"),
        });

        var authRepo = new OrmLiteAuthRepository <CustomUserAuth, UserAuthDetails>(dbFactory);

        container.Register <IUserAuthRepository>(authRepo);
        authRepo.InitSchema();

        using (var db = dbFactory.OpenDbConnection())
        {
            db.CreateTableIfNotExists <TechnologyStack>();
            db.CreateTableIfNotExists <Technology>();
            db.CreateTableIfNotExists <TechnologyChoice>();
            db.CreateTableIfNotExists <UserFavoriteTechnologyStack>();
            db.CreateTableIfNotExists <UserFavoriteTechnology>();

            Plugins.Add(CreateSiteMap(db, baseUrl: "https://techstacks.io"));
        }

        Plugins.Add(new CorsFeature(
                        allowOriginWhitelist: new[] {
            "https://techstacks.io", "https://www.techstacks.io",
            "http://localhost:3000", "http://localhost:16325", "http://localhost:8080", "http://null.jsbin.com",
            "http://run.plnkr.co"
        },
                        allowCredentials: true,
                        allowedHeaders: "Content-Type, Allow, Authorization",
                        maxAge: 60 * 60)); //Cache OPTIONS permissions

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

        Plugins.Add(new AutoQueryMetadataFeature {
            AutoQueryViewerConfig =
            {
                ServiceDescription        = "Discover what technologies were used to create popular Websites and Apps",
                ServiceIconUrl            = "/img/app/logo-76.png",
                BackgroundColor           = "#0095F5",
                TextColor                 = "#fff",
                LinkColor                 = "#ffff8d",
                BrandImageUrl             = "/img/app/brand.png",
                BrandUrl                  = "https://techstacks.io",
                BackgroundImageUrl        = "/img/app/bg.png",
                IsPublic                  = true,
                OnlyShowAnnotatedServices = true,
            }
        });
        Plugins.Add(new AutoQueryFeature {
            MaxLimit         = 500,
            StripUpperInLike = false,
            IncludeTotal     = true,
            ResponseFilters  =
            {
#if DEBUG
                ctx => ctx.Response.Meta["Cache"] = Stopwatch.GetTimestamp().ToString()
#endif
            }
        });
        Plugins.Add(new AdminFeature());
        Plugins.Add(new OpenApiFeature());

        RegisterTypedRequestFilter <IRegisterStats>((req, res, dto) =>
                                                    dbFactory.RegisterPageView(dto.GetStatsId()));

        if (Config.DebugMode)
        {
            Plugins.Add(new LispReplTcpServer {
                ScriptMethods =
                {
                    new DbScriptsAsync()
                },
                ScriptNamespaces =
                {
                    nameof(TechStacks),
                    $"{nameof(TechStacks)}.{nameof(ServiceInterface)}",
                    $"{nameof(TechStacks)}.{nameof(ServiceModel)}",
                },
            });
        }
    }
        public override void Configure(Container container)
        {
            JsConfig.Init(new Text.Config {
                TextCase = TextCase.CamelCase
            });

            SetConfig(new HostConfig
            {
                DebugMode = true,
                Return204NoContentForEmptyResponse = true,
            });

            container.Register <IDbConnectionFactory>(c => new OrmLiteConnectionFactory(
                                                          ":memory:", SqliteDialect.Provider));

            container.Register <IAuthRepository>(c =>
                                                 new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())
            {
                UseDistinctRoleTables = AppSettings.Get("UseDistinctRoleTables", true),
            });

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IAuthRepository>();

            authRepo.DropAndReCreateTables();

            CreateUser(authRepo, 1, "test", "test", new List <string> {
                "TheRole"
            }, new List <string> {
                "ThePermission"
            });
            CreateUser(authRepo, 2, "test2", "test2");

            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] { "http://localhost", "http://localhost:8080", "http://localhost:56500", "http://test.servicestack.net", "http://null.jsbin.com" },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization"));

            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[]
            {
                new BasicAuthProvider(AppSettings),
                new CredentialsAuthProvider(AppSettings),
            }));

            Plugins.Add(new OpenApiFeature());

            /*Plugins.Add(new AutoQueryFeature
             * {
             *  MaxLimit = 100,
             * });
             *
             * container.RegisterValidators(typeof(ThrowValidationValidator).Assembly);
             *
             * JavaGenerator.AddGsonImport = true;
             * var nativeTypes = this.GetPlugin<NativeTypesFeature>();
             * nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));
             *
             *
             *
             * this.RegisterRequestBinder<CustomRequestBinder>(
             *  httpReq => new CustomRequestBinder { IsFromBinder = true });
             *
             * Routes
             *  .Add<Movies>("/custom-movies", "GET")
             *  .Add<Movies>("/custom-movies/genres/{Genre}")
             *  .Add<Movie>("/custom-movies", "POST,PUT")
             *  .Add<Movie>("/custom-movies/{Id}")
             *  .Add<GetFactorial>("/fact/{ForNumber}")
             *  .Add<MoviesZip>("/all-movies.zip")
             *  .Add<GetHttpResult>("/gethttpresult")
             * ;
             */
        }
コード例 #18
0
            public override void Configure(Container container)
            {
                IocShared.Configure(this);

                JsConfig.Init(new Text.Config {
                    TextCase = TextCase.CamelCase,
                });
                ServiceStack.Auth.RegisterService.AllowUpdates = true;

                this.PreRequestFilters.Add((req, res) =>
                {
                    req.Items["_DataSetAtPreRequestFilters"] = true;
                });

                this.GlobalRequestFilters.Add((req, res, dto) =>
                {
                    req.Items["_DataSetAtRequestFilters"] = true;

                    if (dto is RequestFilter requestFilter)
                    {
                        res.StatusCode = requestFilter.StatusCode;
                        if (!requestFilter.HeaderName.IsNullOrEmpty())
                        {
                            res.AddHeader(requestFilter.HeaderName, requestFilter.HeaderValue);
                        }
                        res.Close();
                    }

                    if (dto is IRequiresSession secureRequests)
                    {
                        res.ReturnAuthRequired();
                    }
                });

                Plugins.Add(new SoapFormat());
                Plugins.Add(new MiniProfilerFeature());

                this.Container.Register <IDbConnectionFactory>(c =>
                                                               new OrmLiteConnectionFactory(
                                                                   "~/App_Data/db.sqlite".MapHostAbsolutePath(),
                                                                   SqliteDialect.Provider)
                {
                    ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
                });

                this.Container.Register <ICacheClient>(new MemoryCacheClient());
                //this.Container.Register<ICacheClient>(new BasicRedisClientManager());

                ConfigureAuth(container);

                //this.Container.Register<ISessionFactory>(
                //    c => new SessionFactory(c.Resolve<ICacheClient>()));

                var dbFactory = this.Container.Resolve <IDbConnectionFactory>();

                using (var db = dbFactory.Open())
                    db.DropAndCreateTable <Movie>();

                ModelConfig <Movie> .Id(x => x.Title);

                Routes
                .Add <Movies>("/custom-movies", "GET, OPTIONS")
                .Add <Movies>("/custom-movies/genres/{Genre}")
                .Add <Movie>("/custom-movies", "POST,PUT")
                .Add <Movie>("/custom-movies/{Id}")
                .Add <MqHostStats>("/mqstats");


                var resetMovies = this.Container.Resolve <ResetMoviesService>();

                resetMovies.Post(null);

                container.Register <IRedisClientsManager>(c => new RedisManagerPool());

                Plugins.Add(new TemplatePagesFeature());

                Plugins.Add(new ValidationFeature());
                Plugins.Add(new SessionFeature());
                Plugins.Add(new ProtoBufFormat());
                Plugins.Add(new RequestLogsFeature
                {
                    //RequestLogger = new RedisRequestLogger(container.Resolve<IRedisClientsManager>())
                    RequestLogger = new CsvRequestLogger(),
                });
                Plugins.Add(new OpenApiFeature
                {
                });
                Plugins.Add(new PostmanFeature());
                Plugins.Add(new CorsFeature());
                Plugins.Add(new AutoQueryFeature {
                    MaxLimit = 100
                });
                //Plugins.Add(new AdminFeature());

                container.RegisterValidators(typeof(CustomersValidator).Assembly);

                typeof(ResponseStatus)
                .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("This is the Response Status!"));

                typeof(ResponseStatus)
                .GetProperty("Message")
                .AddAttributes(new ServiceStack.DataAnnotations.DescriptionAttribute("A human friendly error message"));

                //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap);
                SetConfig(new HostConfig
                {
                    AdminAuthSecret = AuthTestsBase.AuthSecret,
                    ApiVersion      = "0.2.0",
                    //EnableFeatures = onlyEnableFeatures,
                    DebugMode     = true, //Show StackTraces for easier debugging
                    RedirectPaths =
                    {
                        { "/swagger-ui", "/swagger-ui/" }
                    }
                });

                if (StartMqHost)
                {
                    var redisManager = new BasicRedisClientManager();
                    var mqHost       = new RedisMqServer(redisManager);
                    mqHost.RegisterHandler <Reverse>(ExecuteMessage);
                    mqHost.Start();
                    this.Container.Register((IMessageService)mqHost);
                }
            }
コード例 #19
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
//            LogManager.LogFactory = new ConsoleLogFactory(debugEnabled:true);
            log = LogManager.GetLogger(typeof(AppHost));

            GetPlugin <NativeTypesFeature>().MetadataTypesConfig.BaseUrl = "https://www.techstacks.io";

            var debugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false);

            SetConfig(new HostConfig {
                // UseSameSiteCookies = true,
                AddRedirectParamsToQueryString = true,
                DebugMode = debugMode,
            });

            JsConfig.Init(new ServiceStack.Text.Config {
                DateHandler = DateHandler.ISO8601
            });

            var dbFactory = new OrmLiteConnectionFactory(
                Environment.GetEnvironmentVariable("TECHSTACKS_DB") ??
                AppSettings.GetString("OrmLite.ConnectionString"),
                PostgreSqlDialect.Provider);

            dbFactory.RegisterDialectProvider(nameof(PostgreSqlDialect), PostgreSqlDialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            // enable server-side rendering, see: https://sharpscript.net
            Plugins.Add(new SharpPagesFeature());

            Plugins.Add(new AuthFeature(() => new CustomUserSession(), new IAuthProvider[] {
                new TwitterAuthProvider(AppSettings),
                new GithubAuthProvider(AppSettings),
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    UseTokenCookie          = true,
                    CreatePayloadFilter     = (payload, session) => {
                        var githubAuth = session.ProviderOAuthAccess.Safe()
                                         .FirstOrDefault(x => x.Provider == "github");
                        payload["ats"] = githubAuth?.AccessTokenSecret;
                    },
                    PopulateSessionFilter = (session, obj, req) => {
                        session.ProviderOAuthAccess = new List <IAuthTokens> {
                            new AuthTokens {
                                Provider = "github", AccessTokenSecret = obj["ats"]
                            }
                        };
                    }
                },
                new DiscourseAuthProvider {
                    Provider     = "servicestack",
                    DiscourseUrl = "https://forums.servicestack.net",
                },
            })
            {
                HtmlRedirect = "/"
            });

            container.Register <IMarkdownProvider>(c =>
                                                   new GitHubApiMarkdownProvider(Environment.GetEnvironmentVariable("GITHUB_AUTH")));

            container.Register <ITwitterUpdates>(new TwitterUpdates(
                                                     AppSettings.GetString("WebStacks.ConsumerKey"),
                                                     AppSettings.GetString("WebStacks.ConsumerSecret"),
                                                     AppSettings.GetString("WebStacks.AccessToken"),
                                                     AppSettings.GetString("WebStacks.AccessSecret"))
            {
                BaseUrl = AppSettings.GetString("PublicBaseUrl"),
            });

            container.Register(new EmailProvider {
                UserName = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_USER") ??
                           AppSettings.GetString("smtp.UserName"),
                Password = Environment.GetEnvironmentVariable("TECHSTACKS_SMTP_PASS") ??
                           AppSettings.GetString("smtp.Password"),
                EnableSsl = true,
                Host      = AppSettings.GetString("smtp.Host"),
                Port      = AppSettings.Get <int>("smtp.Port"),
                Bcc       = AppSettings.GetString("smtp.Bcc"),
            });

            var authRepo = new OrmLiteAuthRepository <CustomUserAuth, UserAuthDetails>(dbFactory);

            container.Register <IUserAuthRepository>(authRepo);
            authRepo.InitSchema();

            using (var db = dbFactory.OpenDbConnection())
            {
                db.CreateTableIfNotExists <TechnologyStack>();
                db.CreateTableIfNotExists <Technology>();
                db.CreateTableIfNotExists <TechnologyChoice>();
                db.CreateTableIfNotExists <UserFavoriteTechnologyStack>();
                db.CreateTableIfNotExists <UserFavoriteTechnology>();

                var baseUrl = "https://techstacks.io";

                Plugins.Add(new SitemapFeature {
                    SitemapIndex =
                    {
                        new Sitemap                           {
                            Location     = baseUrl + "/sitemap-techstacks.xml",
                            AtPath       = "/sitemap-techstacks.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <TechnologyStack>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl {
                                Location = baseUrl + new ClientTechnologyStack{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            }),
                        },
                        new Sitemap                           {
                            Location     = baseUrl + "/sitemap-technologies.xml",
                            AtPath       = "/sitemap-technologies.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Technology>().OrderByDescending(x => x.LastModified))
                                           .Map(x => new SitemapUrl {
                                Location = baseUrl + new ClientTechnology{
                                    Slug = x.Slug
                                }.ToAbsoluteUri(),
                                LastModified    = x.LastModified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap                           {
                            Location     = baseUrl + "/sitemap-users.xml",
                            AtPath       = "/sitemap-users.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <CustomUserAuth>().OrderByDescending(x => x.ModifiedDate))
                                           .Map(x => new SitemapUrl {
                                Location = baseUrl + new ClientUser{
                                    UserName = x.UserName
                                }.ToAbsoluteUri(),
                                LastModified    = x.ModifiedDate,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap                           {
                            Location     = baseUrl + "/sitemap-organizations.xml",
                            AtPath       = "/sitemap-organizations.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Organization>().Where(x => x.Deleted == null)
                                                     .OrderByDescending(x => x.Modified))
                                           .Map(x => new SitemapUrl {
                                Location        = baseUrl + $"/{x.Slug}",
                                LastModified    = x.Modified,
                                ChangeFrequency = SitemapFrequency.Weekly,
                            })
                        },
                        new Sitemap                           {
                            Location     = baseUrl + "/sitemap-posts.xml",
                            AtPath       = "/sitemap-posts.xml",
                            LastModified = DateTime.UtcNow,
                            UrlSet       = db.Select(db.From <Post>()
                                                     .Where(x => x.Type != PostType.Question && x.Deleted == null && x.Hidden == null)
                                                     .Take(1000).OrderByDescending(x => x.Modified))
                                           .Map(x => new SitemapUrl {
                                Location        = baseUrl + $"/posts/{x.Id}/{x.Slug}",
                                LastModified    = x.Modified,
                                ChangeFrequency = SitemapFrequency.Hourly,
                            })
                        }
                    }
                });
            }

            Plugins.Add(new CorsFeature(
                            allowOriginWhitelist: new[] {
                "https://techstacks.io", "https://www.techstacks.io",
                "http://localhost:3000", "http://localhost:16325", "http://localhost:8080", "http://null.jsbin.com",
                "http://run.plnkr.co"
            },
                            allowCredentials: true,
                            allowedHeaders: "Content-Type, Allow, Authorization",
                            maxAge: 60 * 60)); //Cache OPTIONS permissions

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

            Plugins.Add(new AutoQueryMetadataFeature {
                AutoQueryViewerConfig =
                {
                    ServiceDescription        = "Discover what technologies were used to create popular Websites and Apps",
                    ServiceIconUrl            = "/img/app/logo-76.png",
                    BackgroundColor           = "#0095F5",
                    TextColor                 = "#fff",
                    LinkColor                 = "#ffff8d",
                    BrandImageUrl             = "/img/app/brand.png",
                    BrandUrl                  = "https://techstacks.io",
                    BackgroundImageUrl        = "/img/app/bg.png",
                    IsPublic                  = true,
                    OnlyShowAnnotatedServices = true,
                }
            });
            Plugins.Add(new AutoQueryFeature {
                MaxLimit         = 500,
                StripUpperInLike = false,
                IncludeTotal     = true,
                ResponseFilters  =
                {
#if DEBUG
                    ctx => ctx.Response.Meta["Cache"] = Stopwatch.GetTimestamp().ToString()
#endif
                }
            });
            Plugins.Add(new AdminFeature());
            Plugins.Add(new OpenApiFeature());

            RegisterTypedRequestFilter <IRegisterStats>((req, res, dto) =>
                                                        dbFactory.RegisterPageView(dto.GetStatsId()));

            if (Config.DebugMode)
            {
                Plugins.Add(new LispReplTcpServer {
                    ScriptMethods =
                    {
                        new DbScriptsAsync()
                    },
                    ScriptNamespaces =
                    {
                        nameof(TechStacks),
                        $"{nameof(TechStacks)}.{nameof(ServiceInterface)}",
                        $"{nameof(TechStacks)}.{nameof(ServiceModel)}",
                    },
                });
            }

            container.Register <IMessageService>(c => new BackgroundMqService());
            var mqServer = container.Resolve <IMessageService>();

            mqServer.RegisterHandler <SendNotification>(ExecuteMessage, 4);
            mqServer.RegisterHandler <SendSystemEmail>(ExecuteMessage);
            mqServer.RegisterHandler <SendEmail>(ExecuteMessage);

            AfterInitCallbacks.Add(host => {
                mqServer.Start();
                ExecuteService(new RetryPendingNotifications());
            });
        }
コード例 #20
0
        //public Startup(IConfiguration configuration)
        //    : base(configuration, typeof(Startup).Assembly, typeof(Program).Assembly, typeof(ExchangeInstaller).Assembly, typeof(WebSocketInstaller).Assembly) { }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddOptions();
            services.AddLogging(builder => builder.AddSerilog(Log.Logger));
            services.AddElm();
            JsConfig.Init(new Config
            {
                DateHandler          = DateHandler.ISO8601,
                AlwaysUseUtc         = true,
                TextCase             = TextCase.CamelCase,
                ExcludeDefaultValues = true,
                PropertyConvention   = PropertyConvention.Lenient,
            });
            JsConfig.AllowRuntimeTypeWithAttributesNamed = new System.Collections.Generic.HashSet <string>
            {
                nameof(DataContractAttribute),
                nameof(DataMemberAttribute),
                nameof(RuntimeSerializableAttribute)
            };

            //services.AddVaultService(Configuration);
            //services.AddAuthenticationCore();
            //services.AddAuthorizationCore();

            services.AddPolicyRegistry();
            services.AddHttpClientServices(Configuration);

            services.AddCacheServices(Configuration); //and redis configuration => move to CacheService
            services.AddExchangeAccessServices(Configuration);
            services.AddSocketConnectionService();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .SetIsOriginAllowed((host) => true)
                                  .AllowCredentials());
            });

            /////
            services.AddWebEncoders();
            services.AddMetrics()
            .AddMetricsEndpoints()
            .AddMetricsTrackingMiddleware();
            services.AddSingleton <IServiceId, ServiceId>();
            services.AddOpenTracing();
            services.AddConvey("connector")
            .AddCommandHandlers()
            .AddEventHandlers()
            .AddQueryHandlers()
            .AddInMemoryCommandDispatcher()
            .AddInMemoryEventDispatcher()
            .AddInMemoryQueryDispatcher()
            .AddJaeger()
            .AddMetrics()
            .AddRabbitMq();

            services.AddHostedService <TimedPollService>();
        }