Beispiel #1
0
        public static void AddDummyUserIfRequired(Funq.Container container)
        {
            // create a dummy user
            var fac = container.Resolve <IDbConnectionFactory> ();

            using (var db = fac.OpenDbConnection()) {
                if (db.FirstOrDefault <DBUser> (u => u.Username == "dummy") == null)
                {
                    var user = new DBUser();
                    user.Username = "******";
                    user.CreateCryptoFields("foobar123");
                    user.FirstName                 = "John Dummy";
                    user.LastName                  = "Doe";
                    user.AdditionalData            = "Dummy user that is created when in development mode";
                    user.IsActivated               = true;
                    user.IsVerified                = true;
                    user.Manifest.LastSyncRevision = 0;
                    user.EmailAddress              = "*****@*****.**";
                    db.Insert <DBUser> (user);
                    // insert some sample notes
                    var f   = container.Resolve <DbStorageFactory> ();
                    var key = user.GetPlaintextMasterKey("foobar123");
                    var r   = new RequestingUser {
                        Username            = "******",
                        EncryptionMasterKey = key.ToHexString()
                    };
                    // populate with note test cases taken from Tomdroid
                    // these notes will fail Tomboy...
                    using (var storage = f.GetDbStorage(r)) {
                        var sample_notes = new DiskStorage("../../../sample_notes/");
                        sample_notes.GetNotes().Values.ToList().ForEach(n => storage.SaveNote(n));
                    }
                }
            }
        }
Beispiel #2
0
        private void WireupGenericTestClasses(Funq.Container container)
        {
            container.Register <IAuthenticator> (c => {
                var factory = c.Resolve <IDbConnectionFactory> ();
                var dbauth  = new DbAuthenticator(factory);
                //var dbauth = new DbTestAuthenticator ();

                var test_user = new DBUser {
                    Username    = RainyTestServer.TEST_USER,
                    IsActivated = true,
                    IsVerified  = true
                };
                test_user.CreateCryptoFields(RainyTestServer.TEST_PASS);

                // insert a dummy testuser
                using (var db = factory.OpenDbConnection()) {
                    db.InsertParam <DBUser> (test_user);
                }

                return(dbauth);
            });

            container.Register <IAdminAuthenticator> (c => {
                var admin_auth = new DummyAdminAuthenticator(ADMIN_TEST_PASS);
                return((IAdminAuthenticator)admin_auth);
            });

            RegisterStorageFactory(container, false);

            container.Register <IDataBackend> (c => {
                var conn_factory    = c.Resolve <IDbConnectionFactory> ();
                var storage_factory = c.Resolve <DbStorageFactory> ();
                var auth            = c.Resolve <IAuthenticator> ();
                var handler         = c.Resolve <OAuthHandler> ();
                return(new DatabaseBackend(conn_factory, storage_factory, auth, handler));
            });

            container.Register <OAuthHandler> (c => {
                var auth    = c.Resolve <IAuthenticator> ();
                var factory = c.Resolve <IDbConnectionFactory> ();
//				ITokenRepository<AccessToken> access_tokens = new SimpleTokenRepository<AccessToken> ();
//				ITokenRepository<RequestToken> request_tokens = new SimpleTokenRepository<RequestToken> ();
                ITokenRepository <AccessToken> access_tokens   = new DbAccessTokenRepository <AccessToken> (factory);
                ITokenRepository <RequestToken> request_tokens = new DbRequestTokenRepository <RequestToken> (factory);
                ITokenStore token_store = new RainyTokenStore(access_tokens, request_tokens);
                OAuthHandler handler    = new OAuthHandler(auth, access_tokens, request_tokens, token_store);
                return(handler);
            });

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

            DatabaseBackend.CreateSchema(connFactory, true);

            // HACK so the user is inserted when a fixture SetUp is run
            container.Resolve <IAuthenticator> ();
        }
Beispiel #3
0
        /* Uncomment to enable ServiceStack Authentication and CustomUserSession */
        private void ConfigureAuth(Funq.Container container)
        {
            var appSettings = new AppSettings();

            //Default route: /auth/{provider}
            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[] {
                new AcmeCredentialsAuthProvider(appSettings),
            }));

            //Default route: /register
            Plugins.Add(new RegistrationFeature());

            //Requires ConnectionString configured in Web.Config
            var connectionString = ConfigurationManager.ConnectionStrings["SSHelloWorldAuth"].ConnectionString;

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));

            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

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

            authRepo.CreateMissingTables();

            // CreateUser(authRepo, 1, "testuser", null, "Test2#4%");
        }
        private void ConfigureAuth(Funq.Container container)
        {
            var appSettings = new AppSettings();

            //Default route: /auth/{provider}
            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[]
            {
                new CredentialsAuthProvider(appSettings),
//					new FacebookAuthProvider(appSettings),
//					new TwitterAuthProvider(appSettings),
//					new BasicAuthProvider(appSettings),
            }));

            //Default route: /register
            Plugins.Add(new RegistrationFeature());

            //Requires ConnectionString configured in Web.Config
            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(":memory:", false,
                                                                                   SqliteDialect.Provider));

            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

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

            authRepo.CreateMissingTables();
        }
Beispiel #5
0
        public override void Configure(Funq.Container container)
        {
            container.Register <IDbConnectionFactory>(
                c =>
                new OrmLiteConnectionFactory("~/App_Data/db.sqlite".MapHostAbsolutePath(),
                                             SqliteDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            container.RegisterAutoWired <JournalService>();
            container.RegisterAutoWired <SessionService>();

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Journal>();
                db.DropAndCreateTable <Session>();
                db.DropAndCreateTable <Task>();
                db.DropAndCreateTable <JournalNote>();
                db.DropAndCreateTable <SessionNote>();

                //Seed Lists
                db.InsertAll(SeedData.JournalSeed);
                db.InsertAll(SeedData.JournalNoteSeed);
                db.InsertAll(SeedData.SessionSeed);
                db.InsertAll(SeedData.TaskSeed);
                db.InsertAll(SeedData.SessionNoteSeed);
            }
        }
            //Configure ServiceStack Authentication and CustomUserSession
            private void ConfigureAuth(Funq.Container container)
            {
                Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                            new IAuthProvider[] {
                    new CredentialsAuthProvider(AppSettings),
                    new FacebookAuthProvider(AppSettings),
                    new TwitterAuthProvider(AppSettings),
                    new GoogleOpenIdOAuthProvider(AppSettings),
                    new OpenIdOAuthProvider(AppSettings),
                    new DigestAuthProvider(AppSettings),
                    new BasicAuthProvider(AppSettings),
                })
                {
                    IncludeRegistrationService = true
                });
                ServiceStack.Auth.RegisterService.AllowUpdates = true;
                container.Register <IAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

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

                authRepo.DropAndReCreateTables();
                authRepo.CreateUserAuth(new UserAuth
                {
                    UserName    = Constants.AdminName,
                    DisplayName = "The Admin User",
                    Email       = Constants.AdminEmail,
                    FirstName   = "Admin",
                    LastName    = "User",
                }, Constants.AdminPassword);
            }
Beispiel #7
0
        /* Example ServiceStack Authentication and CustomUserSession */
        private void ConfigureAuth(Funq.Container container)
        {
            var appSettings = new AppSettings();

            //Default route: /auth/{provider}
            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[] {
                new CredentialsAuthProvider(appSettings),
                new FacebookAuthProvider(appSettings),
                new TwitterAuthProvider(appSettings),
                new BasicAuthProvider(appSettings),
            }));

            //Default route: /register
            Plugins.Add(new RegistrationFeature());

            //Requires ConnectionString configured in Web.Config
            var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));

            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>()));

            container.Resolve <IUserAuthRepository>().InitSchema();
        }
Beispiel #8
0
        public override void Configure(Funq.Container container)
        {
            Plugins.Add(new RazorFormat());

            //Works but recommend handling 404 at end of .NET Core pipeline
            //this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Unauthorized] = new RazorHandler("/login");

            Plugins.Add(new AuthFeature(() => new CustomUserSession(),
                                        new IAuthProvider[]
            {
                new CredentialsAuthProvider(),                  //HTML Form post of UserName/Password credentials
                new BasicAuthProvider(),                        //Sign-in with HTTP Basic Auth
                new DigestAuthProvider(AppSettings),            //Sign-in with HTTP Digest Auth
                new TwitterAuthProvider(AppSettings),           //Sign-in with Twitter
                new FacebookAuthProvider(AppSettings),          //Sign-in with Facebook
                new GithubAuthProvider(AppSettings),            //Sign-in with GitHub OAuth Provider
                new YandexAuthProvider(AppSettings),            //Sign-in with Yandex OAuth Provider
                new VkAuthProvider(AppSettings),                //Sign-in with VK.com OAuth Provider
            })
            {
                HtmlRedirect = "/",
                IncludeRegistrationService = true,
            });

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

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

            SessionService.ResetUsers(authRepo);
        }
Beispiel #9
0
 private void registerTrackingDisposables <T, TService>(Funq.Container container) where T : class, TService
 {
     container.RegisterAutoWiredAs <T, TService>();
     // execute dispose later on
     if (typeof(T).GetInterface("IDisposable") != null)
     {
         _disposables.Push(() => ((IDisposable)container.Resolve <TService>()).Dispose());
     }
 }
Beispiel #10
0
        // http://localhost:5000/auth/[email protected]&&password=!Abc1234
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            // enable server-side rendering, see: https://sharpscript.net
            Plugins.Add(new SharpPagesFeature());

            if (Config.DebugMode)
            {
                Plugins.Add(new HotReloadFeature());
            }

            Plugins.Add(new RazorFormat()); // enable ServiceStack.Razor

            SetConfig(new HostConfig
            {
                AddRedirectParamsToQueryString = true,
                DebugMode = AppSettings.Get(nameof(HostConfig.DebugMode), false),
//                UseSameSiteCookies = true, // prevents OAuth providers which use Sessions like Twitter from working
                UseSecureCookies = true,
            });

            var cache = container.Resolve <ICacheClient>();

            Plugins.Add(new ValidationFeature());

//            Svg.CssFillColor["svg-auth"] = "#ccc";
            Svg.CssFillColor["svg-icons"] = "#e33";

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound]  = new RazorHandler("/notfound");
            this.CustomErrorHttpHandlers[HttpStatusCode.Forbidden] = new SharpPageHandler("/forbidden");

            Svg.Load(RootDirectory.GetDirectory("/assets/svg"));

            Plugins.Add(new PostmanFeature());

            var nativeTypesFeature = GetPlugin <NativeTypesFeature>();

            nativeTypesFeature
            .ExportAttribute <BindableAttribute>(attr => {
                var metaAttr = nativeTypesFeature.GetGenerator().ToMetadataAttribute(attr);
                return(metaAttr);
            });


//            TypeScriptGenerator.TypeFilter = (type, args) => {
//                if (type == "ResponseBase`1" && args[0] == "Dictionary<String,List`1>")
//                    return "ResponseBase<Map<string,Array<any>>>";
//                return null;
//            };

//            TypeScriptGenerator.DeclarationTypeFilter = (type, args) => {
//                return null;
//            };


            //GetPlugin<SvgFeature>().ValidateFn = req => Config.DebugMode; // only allow in DebugMode
        }
Beispiel #11
0
        private void ConfigureAuth(Funq.Container container, IAppSettings appSettings)
        {
            //Enable and register existing services you want this host to make use of.
            //Look in Web.config for examples on how to configure your oauth providers, e.g. oauth.facebook.AppId, etc.

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                            () => new CustomUserSession(), //Use your own typed Custom UserSession type
                            new IAuthProvider[] {
                new CredentialsAuthProvider(),             //HTML Form post of UserName/Password credentials
                new TwitterAuthProvider(appSettings),      //Sign-in with Twitter
                new FacebookAuthProvider(appSettings),     //Sign-in with Facebook
                new DigestAuthProvider(appSettings),       //Sign-in with Digest Auth
                new BasicAuthProvider(),                   //Sign-in with Basic Auth
                new YahooOpenIdOAuthProvider(appSettings), //Sign-in with Yahoo OpenId
                new OpenIdOAuthProvider(appSettings),      //Sign-in with Custom OpenId
            }));

            //Provide service for new users to register so they can login with supplied credentials.
            Plugins.Add(new RegistrationFeature());

            //override the default registration validation with your own custom implementation
            container.RegisterAs <CustomRegistrationValidator, IValidator <Register> >();

#if SQLSERVER
            //SQL Server Example:
            container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory(
                                                          "Server=localhost;Database=test;User Id=test;Password=test", SqlServer2012Dialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });
#else
            //Create a DB Factory configured to access the UserAuth PostgreSQL DB
            var connStr = appSettings.GetString("ConnectionString");  //ConnectionString in Web.Config
            container.Register <IDbConnectionFactory>(new OrmLiteConnectionFactory(connStr, PostgreSqlDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });
#endif


            //Store User Data into the referenced SqlServer database
            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>();                         //If using and RDBMS to persist UserAuth, we must create required tables
            if (appSettings.Get("RecreateAuthTables", false))
            {
                authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
            }
            else
            {
                authRepo.InitSchema();   //Create only the missing tables
            }
            Plugins.Add(new RequestLogsFeature());
        }
Beispiel #12
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            //Load environment config from text file if exists
            var liveSettings = "~/appsettings.txt".MapHostAbsolutePath();
            var appSettings  = File.Exists(liveSettings)
                ? (IAppSettings) new TextFileSettings(liveSettings)
                : new AppSettings();

            AppConfig = new AppConfig(appSettings);
            container.Register(AppConfig);

            //Change the default ServiceStack configuration
            //const Feature disableFeatures = Feature.Jsv | Feature.Soap;
            SetConfig(new HostConfig
            {
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Html
                },
                HandlerFactoryPath = "api",
                DebugMode          = true,
            });

            Plugins.Add(new MiniProfilerFeature());

            //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, appSettings);

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

            //Register application services
            container.Register(new TodoRepository());
            container.Register <ITwitterGateway>(new TwitterGateway());

            //Configure Custom User Defined REST Paths for your services
            ConfigureServiceRoutes();

            Plugins.Add(new SwaggerFeature {
                UseBootstrapTheme = true
            });
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature());

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
            ServiceStackController.CatchAllController = reqCtx => container.TryResolve <HomeController>();
        }
Beispiel #13
0
        private void ConfigureAuth(Funq.Container container)
        {
            //Enable and register existing services you want this host to make use of.
            //Look in Web.config for examples on how to configure your oauth providers, e.g. oauth.facebook.AppId, etc.
            var appSettings = new AppSettings(tier: "dev");

            //var appSettings = new AppSettings(); //uncomment to use "live" config appSettings

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                            () => new CustomUserSession(),  //Use your own typed Custom UserSession type
                            new IAuthProvider[] {
                new CredentialsAuthProvider(),              //HTML Form post of UserName/Password credentials
                new TwitterAuthProvider(appSettings),       //Sign-in with Twitter
                new FacebookAuthProvider(appSettings),      //Sign-in with Facebook
                new DigestAuthProvider(appSettings),        //Sign-in with Digest Auth
                new BasicAuthProvider(),                    //Sign-in with Basic Auth
                new GoogleOpenIdOAuthProvider(appSettings), //Sign-in with Google OpenId
                new YahooOpenIdOAuthProvider(appSettings),  //Sign-in with Yahoo OpenId
                new OpenIdOAuthProvider(appSettings),       //Sign-in with Custom OpenId
            }));

            //Provide service for new users to register so they can login with supplied credentials.
            Plugins.Add(new RegistrationFeature());

            //override the default registration validation with your own custom implementation
            container.RegisterAs <CustomRegistrationValidator, IValidator <Register> >();

            //Create a DB Factory configured to access the UserAuth SQL Server DB
            var connStr = appSettings.Get("SQLSERVER_CONNECTION_STRING", //AppHarbor or Local connection string
                                          ConfigUtils.GetConnectionString("UserAuth"));

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(connStr, //ConnectionString in Web.Config
                                             SqlServerOrmLiteDialectProvider.Instance)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            //Store User Data into the referenced SqlServer database
            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>();                         //If using and RDBMS to persist UserAuth, we must create required tables

            if (appSettings.Get("RecreateAuthTables", false))
            {
                authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
            }
            else
            {
                authRepo.InitSchema();   //Create only the missing tables
            }
            Plugins.Add(new RequestLogsFeature());
        }
Beispiel #14
0
        public static void Initialize(Funq.Container container)
        {
            DefaultConfig(container);

            JsConfig.EmitCamelCaseNames = true;
            JsConfig.DateHandler        = ServiceStack.Text.JsonDateHandler.ISO8601;

            var config = container.Resolve <IConfig>();

            config.Configure();
        }
Beispiel #15
0
        protected void ConfigureMessageServiceForLongOperations <T>(Funq.Container container, bool startMessageService = true) where T : LongOperationStartDtoBase
        {
            container.Register <IMessageService>(c => new RedisMqServer(c.Resolve <IRedisClientsManager>()));
            container.Resolve <IMessageService>().RegisterHandler <T>(m =>
            {
                var req = new BasicRequest
                {
                    Verb = HttpMethods.Post
                };

                req.Headers["X-ss-id"] = m.GetBody().SessionId;
                var response           = ExecuteMessage(m, req);
                return(response);
            });

            if (startMessageService)
            {
                container.Resolve <IMessageService>().Start();
            }
        }
Beispiel #16
0
        public void CreateMissingTables(Funq.Container container)
        {
            using (IDbConnection db = dbConnectionFactory.OpenDbConnection())
            {
                ((OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>()).CreateMissingTables();

                db.CreateTableIfNotExists <CategoryModels>();
                db.CreateTableIfNotExists <BookModels>();
                db.CreateTableIfNotExists <BookPropertyModels>();
            }
        }
Beispiel #17
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

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

            //Uncomment to change the default ServiceStack configuration
            //SetConfig(new EndpointHostConfig {
            //});

            //Enable Authentication
            //ConfigureAuth(container);

            var appSettings = new AppSettings();

            string baseApiUrl = appSettings.Get("BaseApiUrl", "foo");

            //Register all your dependencies
//            container.Register<IJellybeanDispenser>(c => new VanillaJellybeanDispenser());
//            container.Register(c => new SweetVendingMachine(c.Resolve<IJellybeanDispenser>()));
//            container.Register(c => new SweetShop(c.Resolve<SweetVendingMachine>()));
// See more at: http://anthonysteele.co.uk/the-funq-ioc-container#sthash.ketDSF72.dpuf
            container.Register <IAppConfig>(c => new AppConfig());
            container.Register <IEventRepository>(c => new EventRepository());
            container.Resolve <IEventRepository>().Config = container.Resolve <IAppConfig>();
            // container.Register(c => new TodoRepository());

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

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Beispiel #18
0
        public static void Initialize(Funq.Container container)
        {
            DefaultConfig(container);

            JsConfig.EmitCamelCaseNames = true;
            JsConfig.DateHandler        = ServiceStack.Text.JsonDateHandler.ISO8601;

            var config = container.Resolve <IConfig>();

            config.Configure();

            MapperConfig.Configure();


            using (var db = container.Resolve <IDbConnectionFactory>().OpenDbConnection())
            {
                db.CreateTableIfNotExists(
                    typeof(Address).Assembly.GetTypes()
                    .Where(t => t.IsClass && t.Namespace != null && t.Name != null && t.Namespace.Equals("model.db")).ToArray()
                    );
            }
        }
Beispiel #19
0
        public static void DefaultConfig(Funq.Container container)
        {
            var provider = MySqlDialectProvider.Instance;

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(ConfigurationManager.ConnectionStrings["defaultConnection"].ConnectionString
                                             , provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });
            ;
            container.Register <IUnitOfWorkProvider>(new UnitOfWorkProvider(container.Resolve <IDbConnectionFactory>()));
            container.Register <IConfig>(new ApiConfig(container.Resolve <IDbConnectionFactory>()));

            container.Register <IRepoAddress>(new AddressRepository(container.Resolve <IUnitOfWorkProvider>()));
            container.Register <IAddressService>(new AddressService(container.Resolve <IRepoAddress>()));

            //container.Register<IRepoUsers>(new UsersRepository(container.Resolve<IUnitOfWorkProvider>()));
            //container.Register<IUsersService>(new UsersService(container.Resolve<IRepoUsers>()));

            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Beispiel #20
0
        public override void Configure(Funq.Container container)
        {
            //ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
            //ServiceStackController.CatchAllController = reqCtx => container.TryResolve<HomeController>();
            SetConfig(new HostConfig
            {
                //HandlerFactoryPath = "api",
                DebugMode = _configuration.GetValue <bool>("DebugMode", false),
                AddRedirectParamsToQueryString = true,
                UseCamelCase = true,
            });


#if DEBUG
            if (Config.DebugMode)
            {
                container.Resolve <IZippedLinksRepository>().ReInitSchema();
            }
#else
            container.Resolve <IZippedLinksRepository>().InitSchema();
#endif
        }
Beispiel #21
0
        protected void ConfigureMessageServiceForAfterChangeState <T>(Funq.Container container) where T : AfterChangeStateBaseDto
        {
            container.Resolve <IMessageService>().RegisterHandler <T>(m =>
            {
                var req = new BasicRequest
                {
                    Verb = HttpMethods.Post
                };

                req.Headers["X-ss-id"] = m.GetBody().SessionId;
                var response           = ExecuteMessage(m, req);
                return(null);
            }, noOfThreads: 1);
        }
Beispiel #22
0
        /// <summary>
        /// Configures the application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Funq.Container container)
        {
            // Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

            // Create the connection factory for our database.
            var factory = new OrmLiteConnectionFactory(WebConfigurationManager.ConnectionStrings["SquarePeg"].ConnectionString, MySqlDialect.Provider);

            // Register database.
            container.Register(c => factory.OpenDbConnection());

            // Register logging.
            container.Register <ILog>(c => LogManager.GetLogger(this.GetType()));

            // Register caching dependencies.
            container.Register <IRedisClientsManager>(c => new PooledRedisClientManager("localhost:6379"));
            container.Register <ICacheClient>(c =>
                                              (ICacheClient)c.Resolve <IRedisClientsManager>()
                                              .GetCacheClient())
            .ReusedWithin(Funq.ReuseScope.None);

            // Register repositories
            container.Register <IBoardsRepository>(c => new BoardsRepository(container.Resolve <IDbConnection>()));

            // Register services.
            container.Register <IBoardsService>(
                c => new BoardsService(container.Resolve <IBoardsRepository>(), container.Resolve <ICacheClient>()));

            // Configure the authentiation.
            this.ConfigureAuth(container, factory);

            // Set the sharec container; this is used by other shared omponents such as aspects.
            SharedContainer.Container = container;

            // Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
        }
Beispiel #23
0
        public override void Configure(Funq.Container container)
        {
            //Set JSON web services to return idiomatic JSON camelCase properties
            ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;

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

            AppConfig = new AppConfig(appSettings);
            container.Register(AppConfig);

            //Register all your dependencies:

            //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
            var dbFactory = container.Resolve <IDbConnectionFactory>();

            dbFactory.Run(db => db.DropAndCreateTable <User>());

            //Register application services
            container.Register(new TodoRepository());
            container.Register <ITwitterGateway>(new TwitterGateway());

            //Configure Custom User Defined REST Paths for your services
            ConfigureServiceRoutes();

            //Change the default ServiceStack configuration
            //const Feature disableFeatures = Feature.Jsv | Feature.Soap;
            SetConfig(new EndpointHostConfig {
                //EnableFeatures = Feature.All.Remove(disableFeatures),
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    ContentType.Html
                },
            });

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

            //Set MVC to use the same Funq IOC as ServiceStack
            ControllerBuilder.Current.SetControllerFactory(new FunqControllerFactory(container));
            ServiceStackController.CatchAllController = reqCtx => container.TryResolve <HomeController>();
        }
Beispiel #24
0
        protected void ConfigureMessageServiceForReports <T>(Funq.Container container) where T : Reports.Dto.ReportDataRequestDto
        {
            Routes.Add <T>("/GetReportData");
            container.Resolve <IMessageService>().RegisterHandler <T>(m =>
            {
                var req = new BasicRequest
                {
                    Verb = HttpMethods.Post
                };

                req.Headers["X-ss-id"] = m.GetBody().SessionId;
                var response           = ExecuteMessage(m, req);
                return(response);
            });
        }
Beispiel #25
0
        private void btnGetData_Click(object sender, EventArgs e)
        {
            string token =
                "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6IjMwMzc4M2ViLWIyNWYtNDU5MC05M2NmLTFhNmZjMzQ5Yjk1OSIsImlhdCI6MTU5MTMxNTIyMCwic3ViIjoiZGV2ZWxvcGVyLzcyODgzMmI1LTI4NzgtYTJlZi01MTQ0LTUyNTM5N2U3YzI4NiIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjk0LjIxLjM0LjEwOSJdLCJ0eXBlIjoiY2xpZW50In1dfQ.OgBZEinxO9LZ51E8mgPZKT_UiWsNt6IvZgr-1wNfZZINkv-vQvtN6vNFaTHXIecCao5RwAh3QHOAWjQS_fhulg";

            Funq.Container container = CocCore.Instance(token).Container;
            ICocCoreClans  clansCore = container.Resolve <ICocCoreClans>();

            var clan = clansCore.GetClans(txtTag.Text);

            txtName.Text       = clan.Name;
            txtLocation.Text   = clan.Location.Name;
            txtType.Text       = clan.Type;
            txtClanLevel.Text  = clan.ClanLevel.ToString();
            txtClanPoints.Text = clan.ClanPoints.ToString();
            txtWarWins.Text    = clan.WarWins.ToString();
        }
Beispiel #26
0
        public static void ConfigureAuth(List <IPlugin> Plugins, Funq.Container container)
        {
            //Enable and register existing services you want this host to make use of.
            //Look in Web.config for examples on how to configure your oauth proviers, e.g. oauth.facebook.AppId, etc.
            var appSettings = new AppSettings();

            //Register all Authentication methods you want to enable for this web app.
            Plugins.Add(new AuthFeature(
                            () => new AuthUserSession(), //Use your own typed Custom UserSession type
                            new IAuthProvider[] {
                new CredentialsAuthProvider()
            }));

            //Provide service for new users to register so they can login with supplied credentials.
            Plugins.Add(new RegistrationFeature());

            //Create a DB Factory configured to access the UserAuth SQL Server DB
            var connStr = appSettings.Get("MYSQL_CONNECTION_STRING", //AppHarbor or Local connection string
                                          ConfigUtils.GetConnectionString("UserAuth"));

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(connStr, //ConnectionString in Web.Config
                                             ServiceStack.OrmLite.MySql.MySqlDialectProvider.Instance)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            //Store User Data into the referenced SqlServer database
            container.Register <IUserAuthRepository>(c =>
                                                     new OrmLiteAuthRepository(c.Resolve <IDbConnectionFactory>())); //Use OrmLite DB Connection to persist the UserAuth and AuthProvider info

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IUserAuthRepository>();                         //If using and RDBMS to persist UserAuth, we must create required tables

            if (appSettings.Get("RecreateAuthTables", false))
            {
                authRepo.DropAndReCreateTables(); //Drop and re-create all Auth and registration tables
            }
            else
            {
                authRepo.CreateMissingTables();   //Create only the missing tables
            }
        }
Beispiel #27
0
        public override void Configure(Funq.Container container)
        {
            SetConfig(new EndpointHostConfig {
                DebugMode = true
            });

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(
                                                          "~/reports.sqlite".MapHostAbsolutePath(),
                                                          SqliteOrmLiteDialectProvider.Instance));

            container.Register(new AppConfig(new ConfigurationResourceManager()));

            //Create Report table if not exists
            container.Resolve <IDbConnectionFactory>().Exec(dbCmd =>
            {
                dbCmd.CreateTable <Report>(false);
                dbCmd.CreateTable <RequestInfoResponse>(false);
            });
        }
Beispiel #28
0
        private void WireupPostgresServer(Funq.Container container)
        {
            Container = container;

            container.Register <PostgreConfig> (c => {
                var cnf = new PostgreConfig {
                    Host     = "localhost",
                    Username = "******",
                    Password = "******",
                    Port     = 5432,
                    Database = "rainy"
                };
                return(cnf);
            });

            container.Register <IDbConnectionFactory> (c => {
                var connection_string = container.Resolve <PostgreConfig> ().ConnectionString;
                return(new OrmLiteConnectionFactory(connection_string, PostgreSqlDialect.Provider));
            });
        }
Beispiel #29
0
        private void WireupSqliteTestserver(Funq.Container container)
        {
            Container = container;

            container.Register <SqliteConfig> (c => {
                var test_db_file = "/tmp/rainy-test.db";
                if (File.Exists(test_db_file))
                {
                    File.Delete(test_db_file);
                }

                SqliteConfig cnf = new SqliteConfig()
                {
                    File = test_db_file
                };
                return(cnf);
            });
            container.Register <IDbConnectionFactory> (c => {
                var connection_string = container.Resolve <SqliteConfig> ().ConnectionString;
                return(new OrmLiteConnectionFactory(connection_string, SqliteDialect.Provider));
            });
        }
Beispiel #30
0
            public override void Configure(Funq.Container container)
            {
                Routes
                .Add <Hello>("/hello")
                .Add <Hello>("/hello/{Name}");
                helloService = container.Resolve <HelloService>();

                AuthFeature authFeature = new AuthFeature(() => new AuthUserSession(), new IAuthProvider[] { new BasicAuthProvider(), new TwitterAuthProvider(new AppSettings()), });

                //authFeature.HtmlRedirect
                Plugins.Add(authFeature);
                MemoryCacheClient memoryCacheClient = new MemoryCacheClient();

                container.Register <ICacheClient>(memoryCacheClient);

                var userRepository = new InMemoryAuthRepository();

                container.Register <IUserAuthRepository>(userRepository);

                string hash;
                string salt;
                string password = "******";

                new SaltedHash().GetHashAndSaltString(password, out hash, out salt);
                userRepository.CreateUserAuth(
                    new UserAuth {
                    Id           = 1,
                    DisplayName  = "JoeUser",
                    Email        = "*****@*****.**",
                    UserName     = "******",
                    FirstName    = "Joe",
                    LastName     = "User",
                    PasswordHash = hash,
                    Salt         = salt,
                }, password);
                //IHttpResult authenticationRequired = helloService.AuthenticationRequired(); // ????
            }