Exemple #1
0
        private void ConfigureAuth(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();

            //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 AspNetWindowsAuthProvider(this)
                {
                    LoadUserAuthFilter       = LoadUserAuthInfo,
                    AllowAllWindowsAuthUsers = true
                },
                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
                new GoogleOAuth2Provider(appSettings),      //Sign-in with Google OAuth2 Provider
                new LinkedInOAuth2Provider(appSettings),    //Sign-in with LinkedIn OAuth2 Provider
                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
                new OdnoklassnikiAuthProvider(appSettings), //Sign-in with Odnoklassniki OAuth Provider
            }));

#if HTTP_LISTENER
            //Required for DotNetOpenAuth in HttpListener
            OpenIdOAuthProvider.OpenIdApplicationStore = new InMemoryOpenIdApplicationStore();
#endif

            //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
            Plugins.Add(new CustomRegisterPlugin());

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

            var authRepo = (OrmLiteAuthRepository)container.Resolve <IAuthRepository>();                         //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
            }
            authRepo.CreateUserAuth(new UserAuth
            {
                DisplayName = "Credentials",
                FirstName   = "First",
                LastName    = "Last",
                FullName    = "First Last",
                Email       = "*****@*****.**",
            }, "test");

            Plugins.Add(new RequestLogsFeature());
        }
Exemple #2
0
 public override void Configure(Container container)
 {
     Plugins.Add(new ValidationFeature());
     container.RegisterValidators(typeof(UserValidator).GetAssembly());
 }
Exemple #3
0
            public override void Configure(Container container)
            {
                SetConfig(new HostConfig
                {
                    DebugMode = true
                });

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

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

                    db.DropAndCreateTable <Customer>();
                    db.InsertAll(QueryData.Customers);
                }

                Plugins.Add(new SharpPagesFeature
                {
                    ApiPath = "/api",
                    Args    =
                    {
                        ["products"] = QueryData.Products,
                    },
                    ScriptMethods =
                    {
                        new DbScriptsAsync(),
                        new AutoQueryScripts(),
                    },
                });

                Plugins.Add(new AutoQueryDataFeature {
                    MaxLimit = 100
                }
                            .AddDataSource(ctx => ctx.ServiceSource <Product>(ctx.ConvertTo <GetAllProducts>()))
                            );

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

                var files = TemplateFiles[0];

                files.WriteFile("_layout.html", @"
<html>
<body id=root>
{{ page }}
{{ htmlErrorDebug }}
</body>
</html>
");
                files.WriteFile("autoquery-data-products.html", @"
{{ 'category,orderBy,take' | importRequestParams }}{{ { category, orderBy, take } | withoutNullValues | sendToAutoQuery('QueryProducts') 
   | toResults | select: { it.ProductName }\n }}");

                files.WriteFile("autoquery-rockstars.html", @"
{{ { qs.age, qs.orderBy, qs.take } | withoutNullValues | sendToAutoQuery('QueryTemplateRockstars') 
   | toResults | select: { it.FirstName } { it.LastName }\n }}");

                files.WriteFile("autoquery-customer.html", @"
{{ { qs.customerId } | sendToAutoQuery('QueryCustomers') 
     | toResults | select: { it.CustomerId }: { it.CompanyName }, { it.City }\n }}");

                files.WriteFile("autoquery-customers.html", @"
{{ { qs.countryIn, qs.orderBy } | sendToAutoQuery('QueryCustomers') 
     | toResults | select: { it.CustomerId }: { it.CompanyName }, { it.Country }\n }}");

                files.WriteFile("autoquery-top5-de-uk.html", @"
{{ { countryIn:['UK','Germany'], orderBy:'customerId', take:5 } | sendToAutoQuery('QueryCustomers') 
     | toResults | select: { it.CustomerId }: { it.CompanyName }, { it.Country }\n }}");

                files.WriteFile("api/customers.html", @"
{{ 'id,city,country' | importRequestParams }}
{{ qs.limit ?? 100   | assignTo: limit }}

{{ 'select CustomerId, CompanyName, City, Country from Customer' | assignTo: sql }}

{{ PathArgs | endIfEmpty | useFmt('{0} where CustomerId = @id', sql) | dbSingle({ id: PathArgs[0] }) 
            | return }}

{{ id       | endIfEmpty | use('CustomerId = @id')   | addTo: filters }}
{{ city     | endIfEmpty | use('City = @city')       | addTo: filters }}
{{ country  | endIfEmpty | use('Country = @country') | addTo: filters }}
{{ filters  | endIfEmpty | useFmt('{0} where {1}', sql, join(filters, ' and ')) | assignTo: sql }}

{{ sql      | appendFmt(' ORDER BY CompanyName {0}', sqlLimit(limit)) 
            | dbSelect({ country, city, id }) 
            | return }}
");
            }
Exemple #4
0
 public override void Configure(Container container)
 {
     Plugins.Add(new DtoGenFeature());
 }
 protected void RegisterPlugin(IReactorPlugin plugin)
 {
     Plugins.Add(plugin);
 }
Exemple #6
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)
        {
            SetConfig(new HostConfig
            {
                //EnableFeatures = Feature.All.Remove(Feature.Metadata),
                //DebugMode = false
            });

            JsConfig.IncludeNullValues = false;
            JsConfig.ExcludeTypeInfo   = true;
            JsConfig.DateHandler       = DateHandler.ISO8601;

            #region Database
            var dbFactory = new OrmLiteConnectionFactory(
                AppSettings.Get("dbConnectionString", ""), SqlServer2008Dialect.Provider);

            container.Register <IDbConnectionFactory>(dbFactory);

            OrmLiteConfig.StringFilter = s => s.Trim();
            #endregion

            #region Plugins
            Plugins.Add(new CorsFeature(
                            allowedHeaders: "Content-Type, Allow, Authorization"));

            Plugins.Add(new OpenApiFeature()
            {
                ApiDeclarationFilter = declaration =>
                {
                    declaration.Info.Title = "Universal Catalogs";
                    //declaration.Info.Contact = new ServiceStack.Api.OpenApi.Specification.OpenApiContact()
                    //{
                    //    Email = "*****@*****.**",
                    //    Name = "Alfredo Pacheco"
                    //};
                    declaration.Info.Description = "";
                },
                OperationFilter = (verb, op) =>
                {
                    switch (verb)
                    {
                    case "POST":
                        op.Parameters.RemoveAll(p => p.Name == "Id");
                        op.Parameters.RemoveAll(p => p.Name == "RowVersion");
                        break;

                    default:
                        break;
                    }
                    op.Parameters.RemoveAll(p => p.Name == "EntityName");
                    op.Parameters.RemoveAll(p => p.Name == "EF_State");
                }
            });

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

            #region Auth
            var authProviders = new List <IAuthProvider>
            {
                new JwtAuthProvider(AppSettings)
                {
                    RequireSecureConnection = false,
                    AllowInQueryString      = true
                },
                new CredentialsAuthProvider()
            };

            var authFeature = new AuthFeature(SessionFactory, authProviders.ToArray());
            Plugins.Add(authFeature);

            //var authRepo = new OrmLiteAuthRepository(dbFactory);
            //container.Register<IUserAuthRepository>(authRepo);

            //authRepo.InitSchema();

            //Plugins.Add(new RegistrationFeature());

            //var admin = authRepo.GetUserAuthByUserName("admin");
            //if (admin == null)
            //    authRepo.CreateUserAuth(new UserAuth
            //    {
            //        UserName = "******",
            //        Roles = new List<string> { RoleNames.Admin }
            //    }, "admin");
            #endregion

            //TODO:
            //Done. Global Response Filter: CommonResponse.
            //Done. Cache.
            //Done. Transactions.
            //Logging.
            //Batched requests.
            //attachments
            //Profiler.
            //Versioning.
            //Compression.
            //Autoquery.
            //stripe.com

            #region Cache
            //container.Register<ICacheClient>(new MemoryCacheClient());
            #endregion

            #region App
            //container.Register(c => dbFactory.Open());
            //container.Register(c => c.Resolve<IDbConnectionFactory>().OpenDbConnection()).ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <RevisionLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogTypeLogic>().ReusedWithin(ReuseScope.Request);
            container.Register <IEmailService>(i => new MailgunService()).ReusedWithin(ReuseScope.Request);

            //This App:
            ///start:generated:di<<<
            container.RegisterAutoWired <ActivityLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <ApprovalLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <EmailLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <AdvancedSortLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogTypeLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <CatalogTypeFieldLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <FilterDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <SortDataLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <TaskLogic>().ReusedWithin(ReuseScope.Request);
            container.RegisterAutoWired <TokenLogic>().ReusedWithin(ReuseScope.Request);
            ///end:generated:di<<<
            #endregion
        }
Exemple #7
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            var nativeTypes = this.GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));

            // Change ServiceStack configuration
            this.SetConfig(new HostConfig
            {
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Html
                },

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
#if !DEBUG
                // Show StackTraces in service responses during development
                DebugMode = true,
#endif
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/")
            {
                CaptureSynchronizationContext = true,
            });

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

            Plugins.Add(new AutoQueryFeature());
            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature(allowedMethods: "GET, POST, PUT, DELETE, PATCH, OPTIONS"));

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

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

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

            dbFactory.RegisterConnection("SqlServer",
                                         new OrmLiteConnectionFactory(
                                             "Server={0};Database=test;User Id=test;Password=test;".Fmt(Environment.GetEnvironmentVariable("CI_HOST")),
                                             SqlServerDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            //JavaGenerator.AddGsonImport = true;
        }
Exemple #8
0
        private static void RegisterPluginInstance(IPlugin plugin)
        {
            var pluginType = plugin.GetType();

            if (plugin.MinVersion > Version)
            {
                MessageBox.Show(string.Format("The plugin {0} couldn't be loaded because it needs the interface version {1}.\nThe current interface version is {2}.", plugin.UniqueName, plugin.MinVersion, Version));
            }

            Plugins.Add(plugin);

            if (typeof(IPersistentPlugin).IsAssignableFrom(pluginType))
            {
                var persistentPlugin    = (IPersistentPlugin)plugin;
                var persistentDirectory = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @".\PersistentPlugins\", plugin.UniqueName);

                if (!Directory.Exists(persistentDirectory))
                {
                    Directory.CreateDirectory(persistentDirectory);
                }

                persistentPlugin.PersistentDirectory = persistentDirectory;
            }

            if (typeof(IDataPlugin).IsAssignableFrom(pluginType))
            {
                var dataPlugin = (IDataPlugin)plugin;
                var ids        = dataPlugin.DataIdentifiers;

                foreach (var id in ids.Distinct())
                {
                    if (!DataPlugins.ContainsKey(id))
                    {
                        DataPlugins.Add(id, new List <IDataPlugin>());
                    }

                    DataPlugins[id].Add(dataPlugin);
                }

                if (typeof(IDynamicDataPlugin).IsAssignableFrom(pluginType))
                {
                    var dynamicDataPlugin = (IDynamicDataPlugin)dataPlugin;

                    dynamicDataPlugin.DataIdentifiersChanged = () =>
                    {
                        DataPlugins = DataPlugins.ToDictionary(x => x.Key, x => x.Value.Where(y => y != dynamicDataPlugin).ToList()).Where(x => x.Value.Count != 0).ToDictionary(x => x.Key, x => x.Value);

                        var newIds = dynamicDataPlugin.DataIdentifiers;

                        foreach (var id in newIds.Distinct())
                        {
                            if (!DataPlugins.ContainsKey(id))
                            {
                                DataPlugins.Add(id, new List <IDataPlugin>());
                            }

                            DataPlugins[id].Add(dynamicDataPlugin);
                        }
                    };
                }
            }

            if (typeof(IFilePlugin).IsAssignableFrom(pluginType))
            {
                var filePlugin = (IFilePlugin)plugin;
                var ids        = filePlugin.FileIdentifiers;

                foreach (var id in ids.Distinct())
                {
                    if (!FilePlugins.ContainsKey(id))
                    {
                        FilePlugins.Add(id, new List <IFilePlugin>());
                    }

                    FilePlugins[id].Add(filePlugin);
                }

                if (typeof(IDynamicDataPlugin).IsAssignableFrom(pluginType))
                {
                    var dynamicFilePlugin = (IDynamicFilePlugin)filePlugin;

                    dynamicFilePlugin.DataIdentifiersChanged = () =>
                    {
                        FilePlugins = FilePlugins.ToDictionary(x => x.Key, x => x.Value.Where(y => y != dynamicFilePlugin).ToList()).Where(x => x.Value.Count != 0).ToDictionary(x => x.Key, x => x.Value);

                        var newIds = dynamicFilePlugin.FileIdentifiers;

                        foreach (var id in newIds.Distinct())
                        {
                            if (!DataPlugins.ContainsKey(id))
                            {
                                FilePlugins.Add(id, new List <IFilePlugin>());
                            }

                            FilePlugins[id].Add(dynamicFilePlugin);
                        }
                    };
                }
            }

            if (typeof(IDataUIRequester).IsAssignableFrom(pluginType))
            {
                var dataUIRequester = (IDataUIRequester)plugin;
                dataUIRequester.DataUIRequest = GetUIElement;
            }

            if (typeof(IFileUIRequester).IsAssignableFrom(pluginType))
            {
                var fileUIRequester = (IFileUIRequester)plugin;
                fileUIRequester.FileUIRequest = GetUIElement;
            }

            if (typeof(IPluginLoader).IsAssignableFrom(pluginType))
            {
                var pluginLoader = (IPluginLoader)plugin;
                pluginLoader.RegisterPlugin = (newPlugin) =>
                {
                    RegisterPluginInstance(newPlugin);
                    if (newPlugin is ILateActivatedPlugin)
                    {
                        ((ILateActivatedPlugin)newPlugin).ActivateLate();
                    }
                };
            }

            if (typeof(IPluginUnloader).IsAssignableFrom(pluginType))
            {
                var pluginUnloader = (IPluginUnloader)plugin;
                pluginUnloader.UnloadPlugin = UnloadPlugin;
            }

            if (typeof(IPluginRequester).IsAssignableFrom(pluginType))
            {
                var pluginRequester = (IPluginRequester)plugin;
                pluginRequester.PluginsRequest     = () => { return(Plugins.ToArray()); };
                pluginRequester.DataPluginsRequest = (string dataId) => { return(DataPlugins[dataId].ToArray()); };
                pluginRequester.FilePluginsRequest = (string fileId) => { return(FilePlugins[fileId].ToArray()); };
            }

            if (typeof(IIdRequester).IsAssignableFrom(pluginType))
            {
                var idRequester = (IIdRequester)plugin;
                idRequester.DataIdsRequest = () => { return(DataPlugins.Keys.ToArray()); };
                idRequester.FileIdsRequest = () => { return(FilePlugins.Keys.ToArray()); };
            }

            if (typeof(IPluginPrioritiser).IsAssignableFrom(pluginType))
            {
                var pluginPrioritiser = (IPluginPrioritiser)plugin;
                pluginPrioritiser.DataIdPluginPriorityChange = (dataId, plugins) =>
                {
                    if (plugins.Length != dataId.Length)
                    {
                        throw new ArgumentException("Must specify all plugins for dataId.");
                    }
                    foreach (var dataPlugin in DataPlugins[dataId])
                    {
                        if (!plugins.Contains(dataPlugin))
                        {
                            throw new ArgumentException("Must specify all plugins for dataId.");
                        }
                    }

                    DataPlugins[dataId].Clear();
                    DataPlugins[dataId].AddRange(plugins);
                };
                pluginPrioritiser.FileIdPluginPriorityChange = (fileId, plugins) =>
                {
                    if (plugins.Length != fileId.Length)
                    {
                        throw new ArgumentException("Must specify all plugins for fileId.");
                    }
                    foreach (var filePlugin in FilePlugins[fileId])
                    {
                        if (!plugins.Contains(filePlugin))
                        {
                            throw new ArgumentException("Must specify all plugins for fileId.");
                        }
                    }

                    FilePlugins[fileId].Clear();
                    FilePlugins[fileId].AddRange(plugins);
                };
            }
        }
Exemple #9
0
            public override void Configure(Container container)
            {
                SetConfig(new HostConfig
                {
                    DebugMode      = true,
                    ForbiddenPaths = { "/plugins" }
                });

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

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

                Plugins.Add(new SharpPagesFeature
                {
                    Args =
                    {
                        ["products"] = QueryData.Products,
                    }
                });

                var files = TemplateFiles[0];

                files.WriteFile("_layout.html", @"
<html>
<body id=root>
{{ page }}
</body>
</html>
");
                files.WriteFile("custom_layout.html", @"
<html>
<body id=custom>
{{ page }}
</body>
</html>
");
                files.WriteFile("layout-with-sidebar.html", @"
<html>
<body id=sidebar>
{{ 'sidebar' | partial({ links: { 'a.html': 'A Page', 'b.html': 'B Page' } }) }}
{{ page }}
</body>
</html>
");
                files.WriteFile("dir/_layout.html", @"
<html>
<body id=dir>
{{ page }}
</body>
</html>
");
                files.WriteFile("alt-layout.html", @"
<html>
<body id=alt-layout>
{{ page }}
</body>
</html>
");
                files.WriteFile("dir/alt-layout.html", @"
<html>
<body id=dir-alt-layout>
{{ page }}
</body>
</html>
");
                files.WriteFile("alt/alt-layout.html", @"
<html>
<body id=alt-alt-layout>
{{ page }}
</body>
</html>
");
                files.WriteFile("dir/dir-page.html", @"
<h1>Dir Page</h1>
");

                files.WriteFile("dir/alt-dir-page.html", @"<!--
layout: alt-layout
-->

<h1>Alt Dir Page</h1>
");

                files.WriteFile("dir/alt-layout-alt-dir-page.html", @"<!--
layout: alt/alt-layout
-->

<h1>Alt Layout Alt Dir Page</h1>
");

                files.WriteFile("index.html", @"
<h1>The Home Page</h1>
");

                files.WriteFile("direct-page.html", @"
<h1>Direct Page</h1>
");
                files.WriteFile("shadowed-page.html", @"
<h1>Shadowed Template Page</h1>
");

                files.WriteFile("shadowed/index.html", @"
<h1>Shadowed Index Page</h1>
");
                files.WriteFile("requestinfo-page.html", @"
<h1>The Request Info Page</h1>
<p>{{ 'requestInfo' | partial }}</p>
");

                files.WriteFile("dir/dir-partial.html", @"
<h2>Dir Partial</h2>
");
                files.WriteFile("dir/dir-page-partial.html", @"
<h1>Dir Page Partial</h1>
{{ 'dir-partial' | partial }}
");

                files.WriteFile("dir/dir-file.txt", @"
<h2>Dir File</h2>
");
                files.WriteFile("dir/dir-page-file.html", @"
<h1>Dir Page File</h1>
{{ 'dir-file.txt' | includeFile }}
");
                files.WriteFile("dir/dir-page-file-cache.html", @"
<h1>Dir Page File Cache</h1>
{{ 'dir-file.txt' | includeFileWithCache }}
");

                files.WriteFile("rockstar-details.html", @"{{ it.FirstName }} {{ it.LastName }} ({{ it.Age }})");

                files.WriteFile("rockstar-gateway.html", @"
{{ { qs.id, qs.firstName } | ensureAnyArgsNotNull | sendToGateway('GetRockstarTemplate') | assignTo: rockstar }}
{{ rockstar | ifExists     | selectPartial: rockstar-details }}
{{ rockstar | endIfExists  | select: No rockstar with id: { qs.id } }}
{{ htmlError }}
");

                files.WriteFile("rockstar-gateway-publish.html", @"
{{ 'id,firstName,lastName,age' | importRequestParams }}{{ { id, firstName, lastName, age } | ensureAllArgsNotNull | publishToGateway('AddRockstarTemplate') }}
{{ 'rockstar-gateway' | partial({ firstName }) }}
{{ htmlError }}");

                files.WriteFile("plugins/dll.txt", "Forbidden File");
            }
Exemple #10
0
        private void ConfigureAuth(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();

            Plugins.Add(new EncryptedMessagesFeature
            {
                PrivateKeyXml = "<RSAKeyValue><Modulus>s1/rrg2UxchL5O4yFKCHTaDQgr8Bfkr1kmPf8TCXUFt4WNgAxRFGJ4ap1Kc22rt/k0BRJmgC3xPIh7Z6HpYVzQroXuYI6+q66zyk0DRHG7ytsoMiGWoj46raPBXRH9Gj5hgv+E3W/NRKtMYXqq60hl1DvtGLUs2wLGv15K9NABc=</Modulus><Exponent>AQAB</Exponent><P>6CiNjgn8Ov6nodG56rCOXBoSGksYUf/2C8W23sEBfwfLtKyqTbTk3WolBj8sY8QptjwFBF4eaQiFdVLt3jg08w==</P><Q>xcuu4OGTcSOs5oYqyzsQrOAys3stMauM2RYLIWqw7JGEF1IV9LBwbaW/7foq2dG8saEI48jxcskySlDgq5dhTQ==</Q><DP>KqzhsH13ZyTOjblusox37shAEaNCOjiR8wIKJpJWAxLcyD6BI72f4G+VlLtiHoi9nikURwRCFM6jMbjnztSILw==</DP><DQ>H4CvW7XRy+VItnaL/k5r+3zB1oA51H1kM3clUq8xepw6k5RJVu17GpuZlAeSJ5sWGJxzVAQ/IG8XCWsUPYAgyQ==</DQ><InverseQ>vTLuAT3rSsoEdNwZeH2/JDEWmQ1NGa5PUq1ak1UbDD0snhsfJdLo6at3isRqEtPVsSUK6I07Nrfkd6okGhzGDg==</InverseQ><D>M8abO9lVuSVQqtsKf6O6inDB3wuNPcwbSE8l4/O3qY1Nlq96wWd0DZK0UNqXXdnDQFjPU7uwIH4QYwQMCeoejl3dZlllkyvKVa3jihImDD++qgswX2DmHGDqTIkVABf1NF730gqTmt1kqXoVp5Y+VcO7CZPEygIQyTK4WwYlRjk=</D></RSAKeyValue>"
            });

            //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 AspNetWindowsAuthProvider(this) {
                //    LoadUserAuthFilter = LoadUserAuthInfo,
                //    AllowAllWindowsAuthUsers = true
                //},
                new CredentialsAuthProvider {      //HTML Form post of UserName/Password credentials
                    SkipPasswordVerificationForInProcessRequests = true,
                    //CustomValidationFilter = authCtx =>
                    //    authCtx.Request.UserHostAddress.StartsWith("175.45.17")
                    //        ? HttpResult.Redirect("https://youtu.be/dQw4w9WgXcQ")
                    //        : null
                },
                new JwtAuthProvider(appSettings),
                new ApiKeyAuthProvider(appSettings),
                new DigestAuthProvider(appSettings),            //Sign-in with Digest Auth
                new BasicAuthProvider(),                        //Sign-in with Basic Auth

                new TwitterAuthProvider(appSettings),           //Sign-in with Twitter
                new FacebookAuthProvider(appSettings),          //Sign-in with Facebook
                new GoogleAuthProvider(appSettings),            //Sign-in with Google OAuth
                new GithubAuthProvider(appSettings),            //Sign-in with GitHub OAuth Provider
                new MicrosoftGraphAuthProvider(appSettings),    //Sign-in with Microsoft Graph OAuth
                new LinkedInAuthProvider(appSettings),          //Sign-in with LinkedIn
                new YandexAuthProvider(appSettings),            //Sign-in with Yandex OAuth Provider
                new VkAuthProvider(appSettings),                //Sign-in with VK.com OAuth Provider
                new OdnoklassnikiAuthProvider(appSettings),     //Sign-in with Odnoklassniki OAuth Provider

                new GoogleOAuth2Provider(appSettings),          //Sign-in with Google OAuth2 Provider (with DotNetOpenAuth)
                new LinkedInOAuth2Provider(appSettings),        //Sign-in with LinkedIn OAuth2 Provider
                new FourSquareOAuth2Provider(appSettings),      //Sign-in with FourSquare OAuth2 Provider
                new GoogleOpenIdOAuthProvider(appSettings),     //Sign-in with Google OpenId
                new YahooOpenIdOAuthProvider(appSettings),      //Sign-in with Yahoo OpenId
                new OpenIdOAuthProvider(appSettings),           //Sign-in with Custom OpenId
            }));

#if HTTP_LISTENER
            //Required for DotNetOpenAuth in HttpListener
            OpenIdOAuthProvider.OpenIdApplicationStore = new InMemoryOpenIdApplicationStore();
#endif

            //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
            //Plugins.Add(new CustomRegisterPlugin());

            var authRepo = CreateOrmLiteAuthRepo(container, appSettings);    //works with / or /basic
            //var authRepo = CreateRavenDbAuthRepo(container, appSettings);  //works with /basic
            //var authRepo = CreateRedisAuthRepo(container, appSettings);    //works with /basic
            //AuthProvider.ValidateUniqueUserNames = false;

            try
            {
                authRepo.CreateUserAuth(new CustomUserAuth
                {
                    Custom      = "CustomUserAuth",
                    DisplayName = "Credentials",
                    FirstName   = "First",
                    LastName    = "Last",
                    FullName    = "First Last",
                    Email       = "*****@*****.**",
                }, "test");

                authRepo.CreateUserAuth(new CustomUserAuth
                {
                    Custom      = "CustomUserAuth",
                    DisplayName = "Credentials",
                    FirstName   = "First",
                    LastName    = "Last",
                    FullName    = "First Last",
                    UserName    = "******",
                }, "test");
            }
            catch (Exception) { }

            Plugins.Add(new RequestLogsFeature());

            this.GlobalResponseFilters.Add((req, res, responseDto) =>
            {
                var authResponse = responseDto as AuthenticateResponse;
                if (authResponse != null)
                {
                    authResponse.Meta = new Dictionary <string, string> {
                        { "foo", "bar" }
                    };
                }
            });
        }
Exemple #11
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());

            var UsePostgreSql = false;

            if (UsePostgreSql)
            {
                container.Register <IDbConnectionFactory>(
                    new OrmLiteConnectionFactory(
                        "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)
                });
            }

            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,
            });
        }
        internal void LoadPlugins()
        {
            // Default it is the directory we are executing, and below.
            string pluginDirectoryPaths = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath);

            pluginDirectoryPaths = @"./Plugins/";//Config.GetProperty("PluginDirectory", pluginDirectoryPaths);

            foreach (string dirPath in pluginDirectoryPaths.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
            {
                if (dirPath == null)
                {
                    continue;
                }

                string pluginDirectory = Path.GetFullPath(dirPath);

                _currentPath = pluginDirectory;

                AppDomain currentDomain = AppDomain.CurrentDomain;
                currentDomain.AssemblyResolve += MyResolveEventHandler;

                List <string> pluginPaths = new List <string>();
                pluginPaths.AddRange(Directory.GetFiles(pluginDirectory, "*.dll", SearchOption.AllDirectories));
                pluginPaths.AddRange(Directory.GetFiles(pluginDirectory, "*.exe", SearchOption.AllDirectories));

                foreach (string pluginPath in pluginPaths)
                {
                    Assembly newAssembly = Assembly.LoadFile(pluginPath);

                    Type[] types = newAssembly.GetExportedTypes();
                    foreach (Type type in types)
                    {
                        try
                        {
                            // If no PluginAttribute and does not implement IPlugin interface, not a valid plugin
                            if (!type.IsDefined(typeof(PluginAttribute), true) && !typeof(IPlugin).IsAssignableFrom(type))
                            {
                                continue;
                            }

                            if (type.IsDefined(typeof(PluginAttribute), true))
                            {
                                PluginAttribute pluginAttribute = Attribute.GetCustomAttribute(type, typeof(PluginAttribute), true) as PluginAttribute;
                                if (pluginAttribute != null)
                                {
                                    // if (!Config.GetProperty(pluginAttribute.PluginName + ".Enabled", true)) continue;
                                }
                            }
                            ConstructorInfo ctor = type.GetConstructor(Type.EmptyTypes);
                            if (ctor == null)
                            {
                                continue;
                            }

                            object plugin = ctor.Invoke(null);
                            Plugins.Add(plugin);
                        }
                        catch (Exception ex)
                        {
                            Log.WarnFormat($"Failed loading plugin type {type} as a plugin.");
                            Log.Debug("Plugin loader caught exception, but is moving on.", ex);
                        }
                    }
                }
            }
        }
Exemple #13
0
        /// <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)
        {
            SetConfig(new HostConfig {
                AddRedirectParamsToQueryString = true,
                WebHostUrl = "http://techstacks.io", //for sitemap.xml urls
            });

            JsConfig.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());

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

            RegisterTypedRequestFilter <IRegisterStats>((req, res, dto) =>
                                                        dbFactory.RegisterPageView(dto.GetStatsId()));
        }
 public override void Configure(Funq.Container container)
 {
     Plugins.Add(new SimpleServerEventsFeature()
     {
     });
 }
Exemple #15
0
        public void AddPlugins(string DirectoryName)
        {
            DirectoryInfo di = new DirectoryInfo(DirectoryName);

            FileInfo[] dllfiles = di.GetFiles("*.dll");
            System.Reflection.Assembly assembly = null;
            VisualPascalABCPlugins.IVisualPascalABCPlugin Plugin;
            foreach (FileInfo fi in dllfiles)
            {
                switch (fi.Name.ToLower())
                {
                case "avalondock.dll":
                case "codecompletion.dll":
                case "compiler.dll":
                case "compilertools.dll":
                case "debuggercore.dll":
                case "netgenerator.dll":
                case "treeconverter.dll":
                case "pascalabcparser.dll":
                case "syntaxtree.dll":
                case "semantictree.dll":
                case "weifenluo.winformsui.docking.dll":
                case "pluginssupport.dll":
                case "localization.dll":
                    continue;
                }
                if (fi.Name.StartsWith("NETXP.", StringComparison.InvariantCultureIgnoreCase) || fi.Name.StartsWith("Mono.", StringComparison.InvariantCultureIgnoreCase) || fi.Name.StartsWith("ICSharpCode.", StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }
                try
                {
                    assembly = System.Reflection.Assembly.LoadFile(fi.FullName);
                    try
                    {
                        Type[] types = assembly.GetTypes();

                        foreach (Type type in types)
                        {
                            if (type.Name.IndexOf("VisualPascalABCPlugin") >= 0 && type.IsClass)
                            {
                                Object obj = Activator.CreateInstance(type, workbench);
                                if (obj is VisualPascalABCPlugins.IVisualPascalABCPlugin)
                                {
                                    Plugin = obj as VisualPascalABCPlugins.IVisualPascalABCPlugin;
                                    Plugins.Add(Plugin);
                                    VisualEnvironmentCompiler.BeginInvoke(new AddInGuiDelegate(AddInGUI), Plugin);
                                }
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        ErrorList.Add(new PluginLoadingError(fi.FullName, e));
                    }
                }
                catch (Exception e)
                {
                    //если dll не нетовская
                }
            }
        }
Exemple #16
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)
        {
            Plugins.Add(new GrpcFeature(App));

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

            Plugins.Add(new LispReplTcpServer {
//                RequireAuthSecret = true,
                AllowScriptingOfAllTypes = true,
            });

            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,
                AdminAuthSecret  = "secretz",
            });

            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
        }
 public override void Configure(Container container)
 {
     Plugins.Add(new TemplatePagesFeature());
 }
Exemple #18
0
 public override void Configure(Container container)
 {
     Plugins.Add(new SwaggerFeature());
 }
Exemple #19
0
 public override void Configure(Funq.Container container)
 {
     Plugins.Add(new ServiceStack.Razor.RazorFormat());
 }
Exemple #20
0
 private void ConfigureRazor()
 {
     Plugins.Add(new RazorFormat
     {
     });
 }
Exemple #21
0
            public override void Configure(Container container)
            {
                Plugins.Add(new TemplatePagesFeature());

                var files = TemplateFiles[0];

                files.WriteFile("_layout.html", @"
<html>
<body id=root>
{{ page }}
{{ htmlErrorDebug }}
</body>
</html>
");

                files.WriteFile("alt-layout.html", @"
<html>
<body id=alt-root>
{{ page }}
{{ htmlErrorDebug }}
</body>
</html>
");

                files.WriteFile("Views/_layout.html", @"
<html>
<body id=views>
{{ page }}
{{ htmlErrorDebug }}
</body>
</html>
");

                files.WriteFile("Views/TemplateViewPageRequest.html", @"
<h1>TemplateViewPageRequest</h1>
<p>Name: {{ Name }}</p>
");

                files.WriteFile("Views/TemplateViewPageRequest.html", @"
<h1>TemplateViewPageRequest</h1>
<p>Name: {{ Name }}</p>
");

                files.WriteFile("Views/TemplateViewPageResponse.html", @"
<h1>TemplateViewPageResponse</h1>
<p>Name: {{ Name }}</p>
");

                files.WriteFile("Views/nested/TemplateViewPageNested.html", @"
<h1>TemplateViewPageNested</h1>
<p>Name: {{ Name }}</p>
");

                files.WriteFile("Views/nested/sub/TemplateViewPageNestedSub.html", @"
<h1>TemplateViewPageNestedSub</h1>
<p>Name: {{ Name }}</p>
");
                files.WriteFile("Views/nested/sub/_layout.html", @"
<html>
<body id=views-nested-sub>
{{ page }}
{{ htmlErrorDebug }}
</body>
</html>
");
            }
Exemple #22
0
            public override void Configure(Container container)
            {
                IocShared.Configure(this);

                JsConfig.EmitCamelCaseNames = true;

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

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

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

                    var secureRequests = dto as IRequiresSession;
                    if (secureRequests != null)
                    {
                        res.ReturnAuthRequired();
                    }
                });

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

                Plugins.Add(new ValidationFeature());
                Plugins.Add(new SessionFeature());
                Plugins.Add(new ProtoBufFormat());
                Plugins.Add(new SwaggerFeature());
                Plugins.Add(new RequestLogsFeature());

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


                //var onlyEnableFeatures = Feature.All.Remove(Feature.Jsv | Feature.Soap);
                SetConfig(new HostConfig {
                    GlobalResponseHeaders =
                    {
                        { "Access-Control-Allow-Origin",  "*"                               },
                        { "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
                        { "Access-Control-Allow-Headers", "Content-Type, X-Requested-With"  },
                    },
                    AdminAuthSecret = AuthTestsBase.AuthSecret,
                    //EnableFeatures = onlyEnableFeatures,
                    DebugMode = true, //Show StackTraces for easier debugging
                });

                if (StartMqHost)
                {
                    var redisManager = new BasicRedisClientManager();
                    var mqHost       = new RedisMqServer(redisManager);
                    mqHost.RegisterHandler <Reverse>(ServiceController.ExecuteMessage);
                    mqHost.Start();
                    this.Container.Register((IMessageService)mqHost);
                }
            }
Exemple #23
0
        // Configure your AppHost with the necessary configuration and dependencies your App needs
        public override void Configure(Container container)
        {
            Plugins.Add(new SessionFeature());
            //Plugins.Add(new CorsFeature());
            Plugins.Add(GetCors());

            Plugins.Add(new AuthFeature(() => new AuthUserSession(),
                                        new IAuthProvider[] {
                //new BasicAuthProvider(),
                new CredentialsAuthProvider()
                // ,
                // new CredentialsAuthProvider(), //HTML Form post of UserName/Password credentials
            }));

            //container.RegisterAs<CustomAuthEvents,IAuthEvents>();

            Plugins.Add(new RegistrationFeature());

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

            container.Register <IDbConnectionFactory>(c =>
                                                      new OrmLiteConnectionFactory(Helper.LoadConnSgring().connString, SqlServer2012Dialect.Provider));

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

            // container.Resolve<IAuthRepository>().InitSchema(); // Create any missing UserAuth tables

            //var userRep = new InMemoryAuthRepository();
            //container.Register<IUserAuthRepository>(userRep);



            // Plugins.Add(new AuthFeature(() => new AuthUserSession(),
            //     new IAuthProvider[] {
            //        new BasicAuthProvider(), //Sign-in with HTTP Basic Auth
            //         new CredentialsAuthProvider() //HTML Form post of UserName/Password credentials
            // }));

            // Plugins.Add(new AuthFeature(() => new AuthUserSession(),
            //             new IAuthProvider[] {
            //             new JwtAuthProvider(AppSettings) { AuthKey = AesUtils.CreateKey() },
            //             new CredentialsAuthProvider(AppSettings)
            //                     }));

            // Plugins.Add(new AuthFeature(...,
            //     new IAuthProvider[] {
            //         new JwtAuthProvider(AppSettings) { AuthKey = AesUtils.CreateKey() },
            //         new CredentialsAuthProvider(AppSettings),
            //         //...
            //     }));

            // Plugins.Add(new RegistrationFeature());

            // container.Register<ICacheClient>(new MemoryCacheClient());
            // var userRep = new InMemoryAuthRepository();
            // container.Register<IUserAuthRepository>(userRep);

            SetConfig(new HostConfig
            {
                DefaultRedirectPath = "/metadata",
                DebugMode           = AppSettings.Get(nameof(HostConfig.DebugMode), false)
            });
        }
Exemple #24
0
        public override void Configure(Container containerFunq)
        {
            Log.Info("Configure AppHost");
            new Module().Init(UnityServiceLocator.Instance);

            var container = UnityServiceLocator.Instance;

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

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

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

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

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


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

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


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

            Log.Info("Configure AppHost finished");
        }
Exemple #25
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
//            EnableBuffering();

            this.CustomErrorHttpHandlers[HttpStatusCode.NotFound] = new RazorHandler("/Views/TestErrorNotFound");

            // Change ServiceStack configuration
            SetConfig(new HostConfig
            {
                DebugMode = true,
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = { MimeTypes.Html },
                CompressFilesWithExtensions     = { "js", "css" },
                UseCamelCase    = true,
                AdminAuthSecret = "secretz",
                //HandlerFactoryPath = "CheckWeb", //when hosted on IIS
                //AllowJsConfig = false,

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/"));

            Plugins.Add(new TemplatePagesFeature
            {
                MetadataDebugAdminRole = RoleNames.AllowAnyUser,
                TemplatesAdminRole     = RoleNames.AllowAnon,
            });

            //ProxyFetureTests
            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/proxy/test"),
                            resolveUrl: req => "http://test.servicestack.net".CombineWith(req.RawUrl.Replace("/test", "/"))));

            Plugins.Add(new ProxyFeature(
                            matchingRequests: req => req.PathInfo.StartsWith("/techstacks"),
                            resolveUrl: req => "http://techstacks.io".CombineWith(req.RawUrl.Replace("/techstacks", "/"))));

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

            Plugins.Add(new AutoQueryDataFeature()
                        .AddDataSource(ctx => ctx.MemorySource(GetRockstars())));

            //Plugins.Add(new AdminFeature());

            Plugins.Add(new PostmanFeature());
            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, X-Args"));

            Plugins.Add(new ServerEventsFeature
            {
                LimitToAuthenticatedUsers = true
            });

            GlobalRequestFilters.Add((req, res, dto) =>
            {
                if (dto is AlwaysThrowsGlobalFilter)
                {
                    throw new Exception(dto.GetType().Name);
                }
            });

            Plugins.Add(new RequestLogsFeature
            {
                RequestLogger          = new CsvRequestLogger(),
                EnableResponseTracking = true
            });

            Plugins.Add(new DynamicallyRegisteredPlugin());

            container.Register <IDbConnectionFactory>(
                new OrmLiteConnectionFactory(":memory:", SqliteDialect.Provider));
            //container.Register<IDbConnectionFactory>(
            //    new OrmLiteConnectionFactory("Server=localhost;Database=test;User Id=test;Password=test;", SqlServerDialect.Provider));

            using (var db = container.Resolve <IDbConnectionFactory>().Open())
            {
                db.DropAndCreateTable <Rockstar>();
                db.InsertAll(GetRockstars());

                db.DropAndCreateTable <AllTypes>();
                db.Insert(new AllTypes
                {
                    Id       = 1,
                    Int      = 2,
                    Long     = 3,
                    Float    = 1.1f,
                    Double   = 2.2,
                    Decimal  = 3.3m,
                    DateTime = DateTime.Now,
                    Guid     = Guid.NewGuid(),
                    TimeSpan = TimeSpan.FromMilliseconds(1),
                    String   = "String"
                });
            }

            Plugins.Add(new MiniProfilerFeature());

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

            dbFactory.RegisterConnection("SqlServer",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Database=test;User Id=test;Password=test;",
                                             SqlServerDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            dbFactory.RegisterConnection("pgsql",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
                                             PostgreSqlDialect.Provider));

            using (var db = dbFactory.OpenDbConnection("pgsql"))
            {
                db.DropAndCreateTable <Rockstar>();
                db.DropAndCreateTable <PgRockstar>();

                db.Insert(new Rockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1
                });
                db.Insert(new PgRockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1
                });
            }

            //this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml");

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

            this.StartUpErrors.Add(new ResponseStatus("Mock", "Startup Error"));

            //PreRequestFilters.Add((req, res) =>
            //{
            //    if (req.PathInfo.StartsWith("/metadata") || req.PathInfo.StartsWith("/swagger-ui"))
            //    {
            //        var session = req.GetSession();
            //        if (!session.IsAuthenticated)
            //        {
            //            res.StatusCode = (int)HttpStatusCode.Unauthorized;
            //            res.EndRequest();
            //        }
            //    }
            //});

            Plugins.Add(new ProtoBufFormat());
        }
Exemple #26
0
        public void LoadPlugin(string path)
        {
            Assembly assembly = Assembly.LoadFrom(path);

            try
            {
                foreach (Type type in assembly.GetTypes())
                {
                    if (type.IsPublic && type.IsClass && !type.IsAbstract && type.GetInterface(typeof(IPlugin).FullName) != null)
                    {
                        IPlugin plugin;
                        try
                        {
                            plugin = (IPlugin)assembly.CreateInstance(type.FullName);
                        }
                        catch (Exception e)
                        {
                            throw new PluginLoadException(string.Format(Properties.Resources.Msg_PluginInstantiationException, type.FullName), e);
                        }

                        if (GetPlugin(plugin.Guid) != null)
                        {
                            plugin.Dispose();
                            throw new PluginLoadException(string.Format(Properties.Resources.Msg_PluginRegistrationException_DuplicateGuid, type.FullName, plugin.Guid));
                        }

                        Plugins.Add(plugin);

                        if (plugin is IImportPlugin importPlugin)
                        {
                            ImportPlugins.Add(importPlugin);
                        }
                        if (plugin is IExportPlugin exportPlugin)
                        {
                            ExportPlugins.Add(exportPlugin);
                        }
                        if (plugin is IStartPlugin startPlugin)
                        {
                            StartPlugins.Add(startPlugin);
                        }
                        if (plugin is IHostConncet hc)
                        {
                            try
                            {
                                hc.Initialize(this);
                            }
                            catch (Exception e)
                            {
                                throw new PluginLoadException(string.Format(Properties.Resources.Msg_PluginHostConnectionException, type.FullName), e);
                            }
                        }

                        OnPluginLoaded(new PluginEventArgs(plugin));
                    }
                }
            }
            catch (PluginLoadException pluginloadException)
            {
                string message = pluginloadException.Message + (string.IsNullOrEmpty(pluginloadException.InnerException?.Message) ? "" : Environment.NewLine + Environment.NewLine) + pluginloadException.InnerException?.Message;
                MessageBox.Show(message, getAssemblyTitle(assembly), MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (ReflectionTypeLoadException reflectionTypeLoadException)
            {
                string message = reflectionTypeLoadException.Message + Environment.NewLine + Environment.NewLine + "LoaderExceptions:" + Environment.NewLine;

                foreach (Exception loaderException in reflectionTypeLoadException.LoaderExceptions)
                {
                    message += loaderException.Message + Environment.NewLine;
                }
                MessageBox.Show(message, getAssemblyTitle(assembly), MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (TargetInvocationException targetInvocationException)
            {
                MessageBox.Show(targetInvocationException.InnerException.Message, getAssemblyTitle(assembly), MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            catch (Exception e)
            {
                string message = e.Message + (string.IsNullOrEmpty(e.StackTrace) ? "" : Environment.NewLine + Environment.NewLine) + e.StackTrace;
                MessageBox.Show(message, Properties.Resources.Error, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            string getAssemblyTitle(Assembly _assembly)
            {
                object[] attributes = _assembly.GetCustomAttributes(typeof(AssemblyTitleAttribute), false);
                if (attributes.Length > 0)
                {
                    AssemblyTitleAttribute titleAttribute = (AssemblyTitleAttribute)attributes[0];
                    if (titleAttribute.Title != "")
                    {
                        return(titleAttribute.Title);
                    }
                }
                return(Path.GetFileNameWithoutExtension(_assembly.CodeBase));
            }
        }
Exemple #27
0
        public static async Task LoadPlugins(string xmlText)
        {
            var doc = new XmlDocument();

            doc.LoadXml(xmlText);

            var pluginsInformation = new List <CXmlPluginInformation>();

            foreach (XmlElement entryList in doc.GetElementsByTagName("*"))
            {
                if (entryList.Name.ToLower() == "plugin" ||
                    entryList.Name.ToLower() == "service")
                {
                    CXmlPluginInformation conf = new CXmlPluginInformation();
                    foreach (XmlElement element in entryList)
                    {
                        if (element.Name.ToLower() == "entry")
                        {
                            conf.entryPath = element.InnerText;
                        }
                        if (element.Name.ToLower() == "serviceclassname")
                        {
                            conf.className = element.InnerText;
                        }
                        if (element.Name.ToLower() == "isservice" &&
                            (element.InnerText.ToLower() == "true" ||
                             element.InnerText.ToLower() == "1"))
                        {
                            conf.isService = true;
                        }
                        if (element.Name.ToLower() == "servicetype")
                        {
                            conf.serviceType = element.InnerText;
                        }
                    }

                    pluginsInformation.Add(conf);
                }
            }

            var alreadyLoadedAssemblies = new Dictionary <string, Assembly>();

            foreach (var pluginInfo in pluginsInformation)
            {
                if (!alreadyLoadedAssemblies.TryGetValue($"{(pluginInfo.isService ? "s" : "p")}" + pluginInfo.entryPath, out var assembly))
                {
                    assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(RunningPath + $"{(pluginInfo.isService ? "services" : "plugins")}/" + pluginInfo.entryPath);
                }
                alreadyLoadedAssemblies[$"{(pluginInfo.isService ? "s" : "p")}" + pluginInfo.entryPath] = assembly;

                if (!pluginInfo.isService)
                {
                    var pluginTypes = assembly.GetTypes().Where(t => typeof(CPlugin).IsAssignableFrom(t));
                    foreach (var pluginType in pluginTypes)
                    {
                        var pl = Activator.CreateInstance(pluginType) as CPlugin;
                        await pl.Init();

                        Plugins.Add(pl);
                    }
                }
                else
                {
                    if (GlobalServices.ContainsKey(pluginInfo.serviceType))
                    {
                        throw new DoubleServiceTypeException();
                    }

                    var serviceTypes = assembly.GetTypes().Where(t => typeof(CService).IsAssignableFrom(t) && t.Name == pluginInfo.className);
                    foreach (var serviceType in serviceTypes)
                    {
                        if (serviceType.GetInterfaces().Contains(typeof(IServiceStartAutomatically)))
                        {
                            if (serviceType.GetInterfaces().Contains(typeof(IServiceGlobalSingleton)))
                            {
                                var s = Activator.CreateInstance(serviceType) as IServiceGlobalSingleton;
                                await s.ControllerLoad();

                                GlobalServices[pluginInfo.serviceType] = s as CService;
                            }
                        }

                        servicesTypeFound.Add(serviceType);
                        servicesInformation[serviceType] = pluginInfo;
                    }
                }
            }
        }
Exemple #28
0
 public override void Configure(Funq.Container container)
 {
     Plugins.Add(new CorsFeature());
     Plugins.Add(new PostmanFeature());
 }
Exemple #29
0
        /// <summary>
        /// Configure the Web Application host.
        /// </summary>
        /// <param name="container">The container.</param>
        public override void Configure(Container container)
        {
            var nativeTypes = this.GetPlugin <NativeTypesFeature>();

            nativeTypes.MetadataTypesConfig.ExportTypes.Add(typeof(DayOfWeek));
            nativeTypes.MetadataTypesConfig.IgnoreTypes.Add(typeof(IgnoreInMetadataConfig));
            nativeTypes.InitializeCollectionsForType = NativeTypesFeature.DontInitializeAutoQueryCollections;
            //nativeTypes.MetadataTypesConfig.GlobalNamespace = "Check.ServiceInterface";

            // Change ServiceStack configuration
            this.SetConfig(new HostConfig
            {
                //UseHttpsLinks = true,
                AppendUtf8CharsetOnContentTypes = new HashSet <string> {
                    MimeTypes.Html
                },
                //AllowJsConfig = false,

                // Set to return JSON if no request content type is defined
                // e.g. text/html or application/json
                //DefaultContentType = MimeTypes.Json,
#if !DEBUG
                // Show StackTraces in service responses during development
                DebugMode = true,
#endif
                // Disable SOAP endpoints
                //EnableFeatures = Feature.All.Remove(Feature.Soap)
                //EnableFeatures = Feature.All.Remove(Feature.Metadata)
            });

            container.Register <IServiceClient>(c =>
                                                new JsonServiceClient("http://localhost:55799/")
            {
                CaptureSynchronizationContext = true,
            });

            // Configure JSON serialization properties.
            this.ConfigureSerialization(container);

            // Configure ServiceStack database connections.
            this.ConfigureDataConnection(container);

            // Configure ServiceStack Authentication plugin.
            this.ConfigureAuth(container);

            // Configure ServiceStack Fluent Validation plugin.
            this.ConfigureValidation(container);

            // Configure ServiceStack Razor views.
            this.ConfigureView(container);

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

            Plugins.Add(new AutoQueryDataFeature()
                        .AddDataSource(ctx => ctx.MemorySource(GetRockstars())));

            Plugins.Add(new AdminFeature());

            Plugins.Add(new PostmanFeature());
            Plugins.Add(new CorsFeature(allowedMethods: "GET, POST, PUT, DELETE, PATCH, OPTIONS"));

            Plugins.Add(new RequestLogsFeature {
                RequestLogger = new CsvRequestLogger(),
            });

            Plugins.Add(new DynamicallyRegisteredPlugin());

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

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

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

            dbFactory.RegisterConnection("SqlServer",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Database=test;User Id=test;Password=test;",
                                             SqlServerDialect.Provider)
            {
                ConnectionFilter = x => new ProfiledDbConnection(x, Profiler.Current)
            });

            dbFactory.RegisterConnection("pgsql",
                                         new OrmLiteConnectionFactory(
                                             "Server=localhost;Port=5432;User Id=test;Password=test;Database=test;Pooling=true;MinPoolSize=0;MaxPoolSize=200",
                                             PostgreSqlDialect.Provider));

            using (var db = dbFactory.OpenDbConnection("pgsql"))
            {
                db.DropAndCreateTable <Rockstar>();
                db.DropAndCreateTable <PgRockstar>();

                db.Insert(new Rockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Connection", Age = 1
                });
                db.Insert(new PgRockstar {
                    Id = 1, FirstName = "PostgreSQL", LastName = "Named Connection", Age = 1
                });
            }

            this.GlobalHtmlErrorHttpHandler = new RazorHandler("GlobalErrorHandler.cshtml");

            //JavaGenerator.AddGsonImport = true;
        }
Exemple #30
0
 private void ConfigureConverter()
 {
     //Common
     Plugins.Add(new CommonConverters());
 }