protected AbstractVirtualPathProviderBase(IAppHost appHost) { if (appHost == null) throw new ArgumentNullException("appHost"); AppHost = appHost; }
public void Register(IAppHost appHost) { appHost.Register<INativeTypesMetadata>( new NativeTypesMetadata(appHost.Metadata, MetadataTypesConfig)); appHost.RegisterService<NativeTypesService>(); }
public void AfterPluginsLoaded(IAppHost appHost) { var container = appHost.GetContainer(); if (container.Exists<IpModuleManager>()) { var manager = container.Resolve<IpModuleManager>(); manager.DeviceStatusChanged += (sender, args) => { var cb = container.Resolve<IParadoxEventCallbacks>(); cb.PutDeviceUpdate(args.Device); }; manager.PartitionStatusChanged += (sender, args) => { var cb = container.Resolve<IParadoxEventCallbacks>(); cb.PutPartitionUpdate(args.Partition); }; } else { logger.Error("Cannot find Ip Module Manager to register device and partition status changes events for MQTT"); } }
public void Register(IAppHost appHost) { appHost.GlobalResponseFilters.Add(filter); if (ApplyToMessaging) appHost.GlobalMessageResponseFilters.Add(filter); }
/// <summary> /// /// </summary> /// <param name="appHost"></param> public void Register(IAppHost appHost) { var inMemoryProvider = new RecursiveInMemoryVirtualPathProvider(appHost); // Create a "Views" directory for dumping all our discovered views in var viewsDir = new InMemoryVirtualDirectory(inMemoryProvider, inMemoryProvider.rootDirectory) { DirName = "Views", files = new List<InMemoryVirtualFile>(), dirs = new List<InMemoryVirtualDirectory>() }; inMemoryProvider.rootDirectory.dirs.Add(viewsDir); foreach (var asm in _assemblies) { foreach (string resource in asm.GetManifestResourceNames()) { // Get just the file name. Internally, ServiceStack dumps all these in a giant "/Views" directory anyway, so let's just do that. string path = string.Join(".", resource.Split('.').Reverse().Take(2).Reverse()); viewsDir.AddFile(path, new StreamReader(asm.GetManifestResourceStream(resource)).ReadToEnd()); } } var razorPlugin = new RazorFormat { VirtualPathProvider = inMemoryProvider, EnableLiveReload = false }; appHost.LoadPlugin(razorPlugin); }
public void Register(IAppHost appHost) { if (ResourceFilterPattern != null) SwaggerResourcesService.resourceFilterRegex = new Regex(ResourceFilterPattern, RegexOptions.Compiled); appHost.RegisterService(typeof (SwaggerResourcesService), new string[] {"/resources"}); appHost.RegisterService(typeof(SwaggerApiService), new string[] { "/resource/{Name*}" }); }
/// <summary> /// Activate the validation mechanism, so every request DTO with an existing validator /// will be validated. /// </summary> /// <param name="appHost">The app host</param> public void Register(IAppHost appHost) { if (Enabled) return; Enabled = true; var filter = new ValidationFilters(); appHost.RequestFilters.Add(filter.RequestFilter); }
public void Register(IAppHost appHost) { appHost.Routes.Add(typeof(GetAssetClassRequest), "/rest/assetclasses", "GET"); appHost.Routes.Add(typeof(GetAssetClassRequest), "/rest/assetclasses/{AssetClass}", "GET"); appHost.RegisterService(typeof(AssetClassService), ""); }
public S3VirtualPathProvider(IAmazonS3 client, string bucketName, IAppHost appHost) : base(appHost) { this.AmazonS3 = client; this.BucketName = bucketName; this.rootDirectory = new S3VirtualDirectory(this, null); }
/// <summary> /// /// </summary> /// <param name="appHost"></param> public void Register( IAppHost appHost ) { Verify.ArgumentNotNull(appHost, "appHost"); _appHost = appHost; _appHost.GlobalRequestFilters.Add((req, res, dto) => ProcessRequest(req, res, dto)); }
public void Register(IAppHost appHost) { // Get all of the services in this assembly that inherit from ServiceStackService GetType().Assembly.GetTypes().Where(a => a.BaseType == typeof(Service)).ToList() // Register the Service .Each(service => appHost.RegisterService(service)); }
public AspNetWindowsAuthProvider(IAppHost appHost) { Provider = Name; AuthRealm = Realm; AllRoles = new List<string>(); LimitAccessToRoles = new List<string>(); if (!(appHost is AppHostBase)) { throw new NotSupportedException( "AspNetWindowsAuthProvider is only supported on ASP.NET hosts"); } //Add all pre-defined Roles used to in App to 'AllRoles' appHost.AfterInitCallbacks.Add(host => { var requiredRoles = host.Metadata.OperationsMap .SelectMany(x => x.Key.AllAttributes<RequiredRoleAttribute>() .Concat(x.Value.ServiceType.AllAttributes<RequiredRoleAttribute>())) .SelectMany(x => x.RequiredRoles); requiredRoles.Each(x => AllRoles.AddIfNotExists(x)); }); }
public void Register(IAppHost appHost) { appHost.CatchAllHandlers.Add(ProcessRequest); appHost.GetPlugin<MetadataFeature>() .AddDebugLink("?debug=requestinfo", "Request Info"); }
public void AfterPluginsLoaded(IAppHost appHost) { var container = appHost.GetContainer(); if (container.Exists<IpModuleManager>()) { var manager = container.Resolve<IpModuleManager>(); manager.DeviceStatusChanged += (sender, args) => { logger.DebugFormat("{0}:{1}[{2}]", args.Device.Name, args.Device.Status, args.Device.ZoneId); var settings = container.Resolve<SmartThingsSettings>(); var cb = new SmartThingsCallbacks(settings); cb.PutDeviceUpdate(args.Device); }; manager.PartitionStatusChanged += (sender, args) => { logger.DebugFormat("{0}:{1}", args.Partition.Name, args.Partition.Status); var settings = container.Resolve<SmartThingsSettings>(); var cb = new SmartThingsCallbacks(settings); cb.PutPartitionUpdate(args.Partition); }; } else { logger.Error("Cannot find Ip Module Manager to register device and partition status changes events for SmartThings"); } }
public void Register(IAppHost appHost) { if (alreadyConfigured) return; alreadyConfigured = true; appHost.GlobalRequestFilters.Add(ExtractTokenFromRequestFilter); }
public void Register(IAppHost appHost) { appHost.RegisterService<RequestLogsService>(AtRestPath); var requestLogger = RequestLogger ?? new InMemoryRollingRequestLogger(Capacity); requestLogger.EnableSessionTracking = EnableSessionTracking; requestLogger.EnableResponseTracking = EnableResponseTracking; requestLogger.EnableRequestBodyTracking = EnableRequestBodyTracking; requestLogger.EnableErrorTracking = EnableErrorTracking; requestLogger.RequiredRoles = RequiredRoles; requestLogger.ExcludeRequestDtoTypes = ExcludeRequestDtoTypes; requestLogger.HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes; appHost.Register(requestLogger); if (EnableRequestBodyTracking) { appHost.PreRequestFilters.Insert(0, (httpReq, httpRes) => { httpReq.UseBufferedStream = EnableRequestBodyTracking; }); } appHost.GetPlugin<MetadataFeature>() .AddDebugLink(AtRestPath, "Request Logs"); }
public void Register(IAppHost appHost) { appHost.CatchAllHandlers.Add(ProcessRequest); appHost.GetPlugin<MetadataFeature>() .AddDebugLink($"?{Keywords.Debug}={Keywords.RequestInfo}", "Request Info"); }
public void Register( IAppHost appHost ) { this.AppHost = appHost; this.ViewManager = new ViewManager( appHost, this.ViewConfig ); this.BuildManager = new BuildManager( appHost, this.BuildConfig ); this.PageResolver = new PageResolver( appHost, this.ResolveConfig, this.ViewManager, this.BuildManager ); }
public void Register(IAppHost appHost) { if (isInstalled) return; isInstalled = true; if (!string.IsNullOrEmpty(allowedOrigins) && allowOriginWhitelist == null) appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowOrigin, allowedOrigins); if (!string.IsNullOrEmpty(allowedMethods)) appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowMethods, allowedMethods); if (!string.IsNullOrEmpty(allowedHeaders)) appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowHeaders, allowedHeaders); if (allowCredentials) appHost.Config.GlobalResponseHeaders.Add(HttpHeaders.AllowCredentials, "true"); if (allowOriginWhitelist != null) { appHost.GlobalRequestFilters.Add((httpReq, httpRes, requestDto) => { var origin = httpReq.Headers.Get("Origin"); if (allowOriginWhitelist.Contains(origin)) { httpRes.AddHeader(HttpHeaders.AllowOrigin, origin); } }); } }
public void Register(IAppHost appHost) { appHost.RegisterService<Users.Service>(); appHost.GetContainer().RegisterAutoWiredType(typeof(Users.Service)); //appHost.GetContainer().Register<Users.Service>((c) => new Users.Service(c.Resolve<IBus>())); appHost.GetContainer().RegisterValidators(typeof(Plugin).Assembly); }
/// <summary> /// Adding the files service routes /// </summary> /// <param name="appHost">The service stack appHost</param> public void Register(IAppHost appHost) { if (appHost == null) throw new ArgumentNullException("appHost"); appHost.RegisterService<FilesWebService>(); appHost.Routes.Add<FilesGetRequest>("/files-api", ApplyTo.Get); }
public void Register(IAppHost appHost) { appHost.RegisterService<RequestLogsService>(AtRestPath); appHost.Register(RequestLogger ?? new InMemoryRollingRequestLogger(Capacity) { HideRequestBodyForRequestDtoTypes = HideRequestBodyForRequestDtoTypes }); }
public void Configure(IAppHost appHost) { var settingsProvider = new SettingsProvider(new RoamingAppDataStorage("Paradox")); var mySettings = settingsProvider.GetSettings<SmartThingsSettings>(); var container = appHost.GetContainer(); container.Register(mySettings); container.RegisterAs<SmartThingsCallbacks, IParadoxEventCallbacks>(); }
public void Register(IAppHost appHost) { if (alreadyConfigured) return; alreadyConfigured = true; //Add permanent and session cookies if not already set. appHost.RequestFilters.Add(AddSessionIdToRequestFilter); }
/// <summary> /// Initializes and register serializers /// </summary> /// <param name="appHost">The app host object to register with.</param> public static void Register(IAppHost appHost) { var serializer = new MessagePackSerializer(); appHost.ContentTypeFilters.Register(ContentType, (requestContext, response, stream) => serializer.SerializeToStream(response, stream), serializer.DeserializeFromStream); }
/// <summary> /// Activate the validation mechanism, so every request DTO with an existing validator /// will be validated. /// </summary> /// <param name="appHost">The app host</param> public void Register(IAppHost appHost) { if (!appHost.GlobalRequestFilters.Contains(ValidationFilters.RequestFilter)) appHost.GlobalRequestFilters.Add(ValidationFilters.RequestFilter); if (!appHost.GlobalMessageRequestFilters.Contains(ValidationFilters.RequestFilter)) appHost.GlobalMessageRequestFilters.Add(ValidationFilters.RequestFilter); }
/// <summary> Adds a request filter to apphost </summary> /// <param name="appHost"> the app host</param> public void Register(IAppHost appHost) { appHost.RequestFilters.Add( (request, response, dto) => { if (!AcceptedRequests.Contains(request.ContentType, StringComparer.OrdinalIgnoreCase)) { response.StatusCode = 406; response.Close(); } }); }
public FileSystemVirtualPathProvider(IAppHost appHost, DirectoryInfo rootDirInfo) : base(appHost) { if (rootDirInfo == null) throw new ArgumentNullException("rootDirInfo"); this.RootDirInfo = rootDirInfo; Initialize(); }
public ResourceVirtualPathProvider(IAppHost appHost, Assembly backingAssembly) : base(appHost) { if (backingAssembly == null) throw new ArgumentNullException("backingAssembly"); this.BackingAssembly = backingAssembly; Initialize(); }
public MultiVirtualPathProvider(IAppHost appHost, params IVirtualPathProvider[] childProviders) : base(appHost) { if (childProviders == null || childProviders.Length == 0) throw new ArgumentException("childProviders"); this.ChildProviders = new List<IVirtualPathProvider>(childProviders); Initialize(); }
public void AfterInit(IAppHost appHost) { appHost.Resolve <IMessageService>().Start(); }
public void Register(IAppHost appHost) { hasRegistered = true; AuthenticateService.Init(sessionFactory, AuthProviders); var unitTest = appHost == null; if (unitTest) { return; } if (HostContext.StrictMode) { var sessionInstance = sessionFactory(); if (TypeSerializer.HasCircularReferences(sessionInstance)) { throw new StrictModeException($"User Session {sessionInstance.GetType().Name} cannot have circular dependencies", "sessionFactory", StrictModeCodes.CyclicalUserSession); } } appHost.RegisterServices(ServiceRoutes); var sessionFeature = RegisterPlugins.OfType <SessionFeature>().First(); sessionFeature.SessionExpiry = SessionExpiry; sessionFeature.PermanentSessionExpiry = PermanentSessionExpiry; appHost.LoadPlugin(RegisterPlugins.ToArray()); if (IncludeAuthMetadataProvider && appHost.TryResolve <IAuthMetadataProvider>() == null) { appHost.Register <IAuthMetadataProvider>(new AuthMetadataProvider()); } AuthProviders.OfType <IAuthPlugin>().Each(x => x.Register(appHost, this)); AuthenticateService.HtmlRedirect = HtmlRedirect; AuthenticateService.HtmlRedirectAccessDenied = HtmlRedirectAccessDenied; AuthenticateService.HtmlRedirectReturnParam = HtmlRedirectReturnParam; AuthenticateService.HtmlRedirectReturnPathOnly = HtmlRedirectReturnPathOnly; AuthenticateService.AuthResponseDecorator = AuthResponseDecorator; if (ValidateFn != null) { AuthenticateService.ValidateFn = ValidateFn; } var authNavItems = AuthProviders.Select(x => (x as AuthProvider)?.NavItem).Where(x => x != null); if (!ViewUtils.NavItemsMap.TryGetValue("auth", out var navItems)) { ViewUtils.NavItemsMap["auth"] = navItems = new List <NavItem>(); } var isDefaultHtmlRedirect = HtmlRedirect == "~/" + LocalizedStrings.Login.Localize(); if (IncludeDefaultLogin && isDefaultHtmlRedirect && !appHost.VirtualFileSources.FileExists("/login.html")) { appHost.VirtualFileSources.GetMemoryVirtualFiles().WriteFile("/login.html", Templates.HtmlTemplates.GetLoginTemplate()); // required when not using feature like SharpPagesFeature to auto map /login => /login.html appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => pathInfo == "/login" ? new Host.Handlers.StaticFileHandler(HostContext.VirtualFileSources.GetFile("/login.html")) : null); } navItems.AddRange(authNavItems); appHost.AddToAppMetadata(meta => { meta.Plugins.Auth = new AuthInfo { HasAuthSecret = (appHost.Config.AdminAuthSecret != null).NullIfFalse(), HasAuthRepository = appHost.GetContainer().Exists <IAuthRepository>().NullIfFalse(), IncludesRoles = IncludeRolesInAuthenticateResponse.NullIfFalse(), IncludesOAuthTokens = IncludeOAuthTokensInAuthenticateResponse.NullIfFalse(), HtmlRedirect = HtmlRedirect?.TrimStart('~'), ServiceRoutes = ServiceRoutes.ToMetadataServiceRoutes(routes => { var register = appHost.GetPlugin <RegistrationFeature>(); if (register != null) { routes[nameof(RegisterService)] = new [] { register.AtRestPath } } ; }), AuthProviders = AuthenticateService.GetAuthProviders().Map(x => new MetaAuthProvider { Type = x.Type, Name = x.Provider, NavItem = (x as AuthProvider)?.NavItem, Meta = x.Meta, }) }; }); }
public CrudEventsExecutor(IAppHost appHost) : base(appHost) { }
public static void Init(IAppHost appHost, Func <IAuthSession> sessionFactory, params IAuthProvider[] authProviders) { AuthService.Init(appHost, sessionFactory, authProviders); }
private static IRepository GetRepository(IAppHost appHost) { return(LocalMachineFileRepository.FromSettings(appHost.AppSettings)); }
public abstract IMessageService CreateMqServer(IAppHost host, int retryCount = 1);
public static void RegisterRequestBinder <TRequest>(this IAppHost appHost, Func <IRequest, object> binder) { appHost.RequestBinders[typeof(TRequest)] = binder; }
public static void RegisterService <TService>(this IAppHost appHost, params string[] atRestPaths) { appHost.RegisterService(typeof(TService), atRestPaths); }
public static T GetPlugin <T>(this IAppHost appHost) where T : class, IPlugin { return(appHost.Plugins.FirstOrDefault(x => x is T) as T); }
public static bool HasPlugin <T>(this IAppHost appHost) where T : class, IPlugin { return(appHost.Plugins.FirstOrDefault(x => x is T) != null); }
public static bool HasMultiplePlugins <T>(this IAppHost appHost) where T : class, IPlugin { return(appHost.Plugins.Count(x => x is T) > 1); }
public void Register(IAppHost appHost) { if (ResourceFilterPattern != null) { OpenApiService.resourceFilterRegex = new Regex(ResourceFilterPattern, RegexOptions.Compiled); } if (SecurityDefinitions == null && OperationSecurity == null) { var useBasicAuth = appHost.GetPlugin <AuthFeature>()?.AuthProviders ?.Any(x => x.Provider == AuthenticateService.BasicProvider) == true; if (!useBasicAuth) { UseBearerSecurity = true; } else { UseBasicSecurity = true; } } OpenApiService.UseCamelCaseSchemaPropertyNames = UseCamelCaseSchemaPropertyNames; OpenApiService.UseLowercaseUnderscoreSchemaPropertyNames = UseLowercaseUnderscoreSchemaPropertyNames; OpenApiService.DisableAutoDtoInBodyParam = DisableAutoDtoInBodyParam; OpenApiService.ApiDeclarationFilter = ApiDeclarationFilter; OpenApiService.OperationFilter = OperationFilter; OpenApiService.SchemaFilter = SchemaFilter; OpenApiService.SchemaPropertyFilter = SchemaPropertyFilter; OpenApiService.AnyRouteVerbs = AnyRouteVerbs.ToArray(); OpenApiService.InlineSchemaTypesInNamespaces = InlineSchemaTypesInNamespaces.ToArray(); OpenApiService.SecurityDefinitions = SecurityDefinitions; OpenApiService.OperationSecurity = OperationSecurity; appHost.RegisterService(typeof(OpenApiService), "/openapi"); if (!DisableSwaggerUI) { appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => { IVirtualFile indexFile; IVirtualFile patchFile = null; IVirtualFile patchPreLoadFile = null; pathInfo = pathInfo.TrimStart('/'); switch (pathInfo) { case "swagger-ui/": case "swagger-ui/default.html": indexFile = appHost.VirtualFileSources.GetFile("/swagger-ui/index.html"); patchFile = appHost.VirtualFileSources.GetFile("/swagger-ui/patch.js"); patchPreLoadFile = appHost.VirtualFileSources.GetFile("/swagger-ui/patch-preload.js"); break; default: indexFile = null; break; } if (indexFile != null) { var html = indexFile.ReadAllText(); var injectJs = patchFile?.ReadAllText(); var injectPreloadJs = patchPreLoadFile?.ReadAllText(); return(new CustomResponseHandler((req, res) => { res.ContentType = MimeTypes.HtmlUtf8; //use alt HTML ContentType so it's not overridden when Feature.Html is removed var resourcesUrl = req.ResolveAbsoluteUrl("~/openapi"); html = html.Replace("http://petstore.swagger.io/v2/swagger.json", resourcesUrl) .Replace("ApiDocs", HostContext.ServiceName) .Replace("<span class=\"logo__title\">swagger</span>", $"<span class=\"logo__title\">{HostContext.ServiceName}</span>") .Replace("http://swagger.io", LogoHref ?? "./"); if (LogoUrl != null) { html = html.Replace("images/logo_small.png", LogoUrl); } if (injectPreloadJs != null) { html = html.Replace("window.swaggerUi.load();", injectPreloadJs + "\n\n window.swaggerUi.load();"); } if (injectJs != null) { html = html.Replace("</body>", "<script type='text/javascript'>" + injectJs + "</script></body>"); } return html; })); } return(pathInfo.StartsWith("/swagger-ui/") ? new StaticFileHandler() : null); }); } }
public void Register(IAppHost appHost) { appHost.RegisterAs <CustomRegistrationValidator, IValidator <Register> >(); }
public void Register(IAppHost appHost) { appHost.ContentTypeFilters.Register(ContentType.BaijiJson, WrappedBaijiJsonSerializer.Serialize, WrappedBaijiJsonSerializer.Deserialize); }
public void Register(IAppHost appHost) { if (ResourceFilterPattern != null) { OpenApiService.resourceFilterRegex = new Regex(ResourceFilterPattern, RegexOptions.Compiled); } OpenApiService.UseCamelCaseSchemaPropertyNames = UseCamelCaseSchemaPropertyNames; OpenApiService.UseLowercaseUnderscoreSchemaPropertyNames = UseLowercaseUnderscoreSchemaPropertyNames; OpenApiService.DisableAutoDtoInBodyParam = DisableAutoDtoInBodyParam; OpenApiService.ApiDeclarationFilter = ApiDeclarationFilter; OpenApiService.OperationFilter = OperationFilter; OpenApiService.SchemaFilter = SchemaFilter; OpenApiService.SchemaPropertyFilter = SchemaPropertyFilter; OpenApiService.AnyRouteVerbs = AnyRouteVerbs.ToArray(); appHost.RegisterService(typeof(OpenApiService), "/openapi"); if (!DisableSwaggerUI) { var swaggerUrl = "swagger-ui/"; appHost.GetPlugin <MetadataFeature>() .AddPluginLink(swaggerUrl, "Swagger UI"); appHost.CatchAllHandlers.Add((httpMethod, pathInfo, filePath) => { IVirtualFile indexFile; IVirtualFile patchFile = null; switch (pathInfo) { case "/swagger-ui": case "/swagger-ui/": case "/swagger-ui/default.html": indexFile = appHost.VirtualFileSources.GetFile("/swagger-ui/index.html"); patchFile = appHost.VirtualFileSources.GetFile("/swagger-ui/patch.js"); break; default: indexFile = null; break; } if (indexFile != null) { var html = indexFile.ReadAllText(); var injectJs = patchFile?.ReadAllText(); return(new CustomResponseHandler((req, res) => { res.ContentType = MimeTypes.Html; var resourcesUrl = req.ResolveAbsoluteUrl("~/openapi"); html = html.Replace("http://petstore.swagger.io/v2/swagger.json", resourcesUrl) .Replace("ApiDocs", HostContext.ServiceName) .Replace("<span class=\"logo__title\">swagger</span>", $"<span class=\"logo__title\">{HostContext.ServiceName}</span>") .Replace("http://swagger.io", LogoHref ?? "./"); if (LogoUrl != null) { html = html.Replace("images/logo_small.png", LogoUrl); } if (injectJs != null) { html = html.Replace("</body>", "<script type='text/javascript'>" + injectJs + "</script></body>"); } return html; })); } return(pathInfo.StartsWith("/swagger-ui") ? new StaticFileHandler() : null); }); } }
public virtual Service SetAppHost(IAppHost appHost) { this.resolver = appHost; return(this); }
public void Configure(IAppHost appHost) { appHost.Config.EmbeddedResourceSources.Add(typeof(OpenApiFeature).GetAssembly()); }
/// <summary> /// Get an IAppHost container. /// Note: Registering dependencies should only be done during setup/configuration /// stage and remain immutable there after for thread-safety. /// </summary> /// <param name="appHost"></param> /// <returns></returns> public static Container GetContainer(this IAppHost appHost) { var hasContainer = appHost as IHasContainer; return(hasContainer != null ? hasContainer.Container : null); }
public void Register(IAppHost appHost) { }