Exemplo n.º 1
0
        public async Task GenerateLinkSuccess()
        {
            //Arrange
            var playerName     = "Test Name";
            var playerRegion   = "Test Region";
            var generatLinkDto = new GenerateLinkDto
            {
                Api      = "Test Api",
                Nickname = playerName,
                Server   = playerRegion
            };
            var mockRiotService = new Mock <IRiotApiService>();

            mockRiotService.Setup(rs => rs.FetchPlayerId(playerName, playerRegion)).ReturnsAsync("ID");
            var mockSendgridService = new Mock <ISendgridService>();
            var controller          = new WebPageController(mockRiotService.Object, mockSendgridService.Object);

            controller.ControllerContext = new ControllerContext {
                HttpContext = new DefaultHttpContext()
            };

            //Act
            var result = await controller.GenerateLink(generatLinkDto);

            //Assert
            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);

            Assert.Equal("Link", redirectToActionResult.ActionName);
        }
Exemplo n.º 2
0
        public async Task GenerateLinkRegionNotFound()
        {
            //Arrange
            var playerName     = "Test Name";
            var playerRegion   = "Test Region";
            var generatLinkDto = new GenerateLinkDto
            {
                Nickname = playerName,
                Server   = playerRegion
            };
            var mockRiotService = new Mock <IRiotApiService>();

            mockRiotService.Setup(rs => rs.FetchPlayerId(playerName, playerRegion)).ThrowsAsync(new RegionNotFoundException());
            var mockSendgridService = new Mock <ISendgridService>();
            var controller          = new WebPageController(mockRiotService.Object, mockSendgridService.Object);

            //Act
            var result = await controller.GenerateLink(generatLinkDto);

            //Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            viewResult.ViewData.ModelState.TryGetValue("RegionNotFound", out var error);
            Assert.Equal("Selected region not found.", error.Errors[0].ErrorMessage);
        }
Exemplo n.º 3
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            settings.Converters.Add(new IsoDateTimeConverter());
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);


            // Load shared hub into application domain, initializing default status and exception handlers
            try
            {
                using (new SharedHub(
                           (message, updateType) => Program.LogStatus(message, true),
                           ex => Program.LogException(ex)
                           )) { }
            }
            catch (Exception ex)
            {
                Program.LogException(new SecurityException($"Failed to load Shared Hub: {ex.Message}", ex));
            }

            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemes = AuthenticationSchemes.IntegratedWindowsAuthentication;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            AppModel appModel = new AppModel();

            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, appModel.Global.DefaultWebPage, appModel, typeof(AppModel));

            // Make sure any hosted exceptions get propagated to service error handling
            httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler());

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 4
0
        private void HandleRequestForTimersWebPage(HttpListenerRequest request, HttpListenerResponse response)
        {
            if (_optionsService.Options.IsWebClockEnabled)
            {
                _apiThrottler.CheckRateLimit(ApiRequestType.ClockPage, request);

                var controller = new WebPageController(WebPageTypes.Timers);
                controller.HandleRequestForWebPage(response);
            }
        }
Exemplo n.º 5
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            try
            {
                using (new SecurityHub()) { }
            }
            catch (Exception ex)
            {
                throw new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex);
            }

            // Configure Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

#if DEBUG
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromMinutes(30);
#endif

            // Enable cross-domain scripting
            app.UseCors(CorsOptions.AllowAll);

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 6
0
        private void HandleRequestForClockWebPageTimerData(
            HttpListenerRequest request,
            HttpListenerResponse response)
        {
            if (_optionsService.Options.IsWebClockEnabled)
            {
                _apiThrottler.CheckRateLimit(ApiRequestType.ClockData, request);

                var timerInfo = new TimerInfoEventArgs();
                OnRequestForTimerDataEvent(timerInfo);

                WebPageController.HandleRequestForTimerData(response, timerInfo, _dateTimeService.Now());
            }
        }
Exemplo n.º 7
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            settings.Converters.Add(new IsoDateTimeConverter());
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            using (new SecurityHub()) { }

            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemes = AuthenticationSchemes.Ntlm;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            AppModel appModel = new AppModel();

            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, appModel.Global.DefaultWebPage, appModel, typeof(AppModel));

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            app.Use <AuthenticationMiddleware>(new AuthenticationOptions()
            {
                AnonymousResourceExpression           = "(?!)",
                AuthFailureRedirectResourceExpression = "(?!)"
            });

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 8
0
        public async Task GenerateLinkModelStateInvalid()
        {
            //Arrange
            var generatLinkDto      = new GenerateLinkDto();
            var mockRiotService     = new Mock <IRiotApiService>();
            var mockSendgridService = new Mock <ISendgridService>();
            var controller          = new WebPageController(mockRiotService.Object, mockSendgridService.Object);

            controller.ModelState.AddModelError("Testing Error", "Error");

            //Act
            var result = await controller.GenerateLink(generatLinkDto);

            //Assert
            var viewResult = Assert.IsType <ViewResult>(result);

            viewResult.ViewData.ModelState.TryGetValue("Testing Error", out var error);
            Assert.Equal("Error", error.Errors[0].ErrorMessage);
        }
Exemplo n.º 9
0
        public async Task ContactSucces()
        {
            //Arrange
            var contactDto = new ContactDto
            {
                Email   = "*****@*****.**",
                Message = "Test Message",
                Name    = "Test Name"
            };
            var mockRiotService     = new Mock <IRiotApiService>();
            var mockSendgridService = new Mock <ISendgridService>();

            mockSendgridService.Setup(s => s.SendMail(contactDto)).Verifiable();
            var controller = new WebPageController(mockRiotService.Object, mockSendgridService.Object);

            //Act
            var result = await controller.Contact(contactDto);

            //Assert
            var redirectToActionResult = Assert.IsType <RedirectToActionResult>(result);

            mockSendgridService.Verify();
            Assert.Equal("EmailSend", redirectToActionResult.ActionName);
        }
Exemplo n.º 10
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);
            AppModel model = Program.Host.Model;

            // Load security hub into application domain before establishing SignalR hub configuration, initializing default status and exception handlers
            try
            {
                using (new SecurityHub(
                           (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType),
                           ex => Program.Host.LogException(ex)
                           )) { }
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex));
            }

            // Load shared hub into application domain, initializing default status and exception handlers
            try
            {
                using (new SharedHub(
                           (message, updateType) => Program.Host.LogWebHostStatusMessage(message, updateType),
                           ex => Program.Host.LogException(ex)
                           )) { }
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new SecurityException($"Failed to load Shared Hub: {ex.Message}", ex));
            }

            // Load Modbus assembly
            try
            {
                // Make embedded resources of Modbus poller available to web server
                using (ModbusPoller poller = new ModbusPoller())
                    WebExtensions.AddEmbeddedResourceAssembly(poller.GetType().Assembly);

                ModbusPoller.RestoreConfigurations(FilePath.GetAbsolutePath("ModbusConfigs"));
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new InvalidOperationException($"Failed to load Modbus assembly: {ex.Message}", ex));
            }

            // Configure Windows Authentication for self-hosted web service
            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, model, typeof(AppModel));

            // Make sure any hosted exceptions get propagated to service error handling
            httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler());

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Enable GSF session management
            httpConfig.EnableSessions(AuthenticationOptions);

            // Enable GSF role-based security authentication
            app.UseAuthentication(AuthenticationOptions);

            // Enable cross-domain scripting default policy - controllers can manually
            // apply "EnableCors" attribute to class or an action to override default
            // policy configured here
            try
            {
                if (!string.IsNullOrWhiteSpace(model.Global.DefaultCorsOrigins))
                {
                    httpConfig.EnableCors(new EnableCorsAttribute(model.Global.DefaultCorsOrigins, model.Global.DefaultCorsHeaders, model.Global.DefaultCorsMethods)
                    {
                        SupportsCredentials = model.Global.DefaultCorsSupportsCredentials
                    });
                }
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new InvalidOperationException($"Failed to establish default CORS policy: {ex.Message}", ex));
            }

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Map custom API controllers
            try
            {
                using (new GrafanaController()) { }

                httpConfig.Routes.MapHttpRoute(
                    name: "CustomAPIs",
                    routeTemplate: "api/{controller}/{action}/{id}",
                    defaults: new { action = "Index", id = RouteParameter.Optional }
                    );
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new InvalidOperationException($"Failed to initialize custom API controllers: {ex.Message}", ex));
            }

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
 public void SetUp()
 {
     _webPageHelper     = new Mock <IWebPageHelper>();
     _webPageController = new WebPageController(_webPageHelper.Object);
 }
Exemplo n.º 12
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub into application domain before establishing SignalR hub configuration
            try
            {
                using (new SecurityHub()) { }
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex));
            }


            // Configure Windows Authentication for self-hosted web service
            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

            // Make sure any hosted exceptions get propagated to service error handling
            httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler());

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Enable GSF session management
            httpConfig.EnableSessions(AuthenticationOptions);

            // Enable GSF role-based security authentication
            app.UseAuthentication(AuthenticationOptions);

            // Enable cross-domain scripting
            app.UseCors(CorsOptions.AllowAll);

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Map custom API controllers
            try
            {
                httpConfig.Routes.MapHttpRoute(
                    name: "Controllers",
                    routeTemplate: "api/{controller}/{action}/{modelName}/{id}",
                    defaults: new {
                    action    = "Index",
                    id        = RouteParameter.Optional,
                    modelName = RouteParameter.Optional
                }
                    );

                httpConfig.Routes.MapHttpRoute(
                    name: "Summary",
                    routeTemplate: "Summary/{*stuff}",
                    defaults: new
                {
                    action     = "GetPage",
                    controller = "Main"
                }
                    );
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new InvalidOperationException($"Failed to initialize custom API controllers: {ex.Message}", ex));
            }


            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 13
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            try
            {
                using (new SecurityHub()) { }
            }
            catch (Exception ex)
            {
                throw new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex);
            }

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

            // Make sure any hosted exceptions get propagated to service error handling
            httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler());

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Enable GSF session management
            httpConfig.EnableSessions(AuthenticationOptions);

            // Enable GSF role-based security authentication
            app.UseAuthentication(AuthenticationOptions);


            // Enable cross-domain scripting default policy - controllers can manually
            // apply "EnableCors" attribute to class or an action to override default
            // policy configured here
            try
            {
                if (!string.IsNullOrWhiteSpace(Program.Host.Model.Global.DefaultCorsOrigins))
                {
                    httpConfig.EnableCors(new EnableCorsAttribute(Program.Host.Model.Global.DefaultCorsOrigins, Program.Host.Model.Global.DefaultCorsHeaders, Program.Host.Model.Global.DefaultCorsMethods)
                    {
                        SupportsCredentials = Program.Host.Model.Global.DefaultCorsSupportsCredentials
                    });
                }
            }
            catch (Exception ex)
            {
                Program.Host.LogException(new InvalidOperationException($"Failed to establish default CORS policy: {ex.Message}", ex));
            }

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 14
0
        public void Configuration(IAppBuilder app)
        {
            app.Use((context, next) =>
            {
                context.Response.Headers.Remove("Server");
                return(next.Invoke());
            });

            app.UseStageMarker(PipelineStage.PostAcquireState);

            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            using (new SecurityHub()) { }

            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = AuthenticationSchemeForClient;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

#if DEBUG
            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;
#endif

            app.Use <AuthenticationMiddleware>(new AuthenticationOptions()
            {
                SessionToken = "session",
                AuthFailureRedirectResourceExpression = "(?!)",
                AnonymousResourceExpression           = "^/api/(?:JSONApi|Grafana)"
            });

            string allowedDomainList = ConfigurationFile.Current.Settings["systemSettings"]["AllowedDomainList"]?.Value;

            if (allowedDomainList == "*")
            {
                app.UseCors(CorsOptions.AllowAll);
            }
            else if ((object)allowedDomainList != null)
            {
                httpConfig.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute(allowedDomainList, "*", "*"));
            }


            CsvDownloadHandler.LogExceptionHandler     = Program.Host.HandleException;
            HowlCSVDownloadHandler.LogExceptionHandler = Program.Host.HandleException;
            HowlCSVUploadHandler.LogExceptionHandler   = Program.Host.HandleException;

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Set configuration to use reflection to setup routes
            ControllerConfig.Register(httpConfig);

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            httpConfig.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 15
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            using (new SecurityHub()) { }
            using (new openXDA.Adapters.JSONApiController()) { }
            //using (new GrafanaController()) { }

            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = AuthenticationSchemeForClient;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

#if DEBUG
            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;
#endif

            string allowedDomainList = ConfigurationFile.Current.Settings["systemSettings"]["AllowedDomainList"]?.Value;

            if (allowedDomainList == "*")
            {
                app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
            }
            else if ((object)allowedDomainList != null)
            {
                httpConfig.EnableCors(new System.Web.Http.Cors.EnableCorsAttribute(allowedDomainList, "*", "*"));
            }

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Map custom API controllers
            httpConfig.Routes.MapHttpRoute(
                name: "CustomAPIs",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }
Exemplo n.º 16
0
        public void Configuration(IAppBuilder app)
        {
            // Modify the JSON serializer to serialize dates as UTC - otherwise, timezone will not be appended
            // to date strings and browsers will select whatever timezone suits them
            JsonSerializerSettings settings = JsonUtility.CreateDefaultSerializerSettings();

            settings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;
            JsonSerializer serializer = JsonSerializer.Create(settings);

            GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

            // Load security hub in application domain before establishing SignalR hub configuration
            try
            {
                using (new SecurityHub()) { }
            }
            catch (Exception ex)
            {
                throw new SecurityException($"Failed to load Security Hub, validate database connection string in configuration file: {ex.Message}", ex);
            }

            // Configuration Windows Authentication for self-hosted web service
            HttpListener listener = (HttpListener)app.Properties["System.Net.HttpListener"];

            listener.AuthenticationSchemeSelectorDelegate = AuthenticationSchemeForClient;

            HubConfiguration  hubConfig  = new HubConfiguration();
            HttpConfiguration httpConfig = new HttpConfiguration();

            // Setup resolver for web page controller instances
            httpConfig.DependencyResolver = WebPageController.GetDependencyResolver(WebServer.Default, Program.Host.DefaultWebPage, new AppModel(), typeof(AppModel));

            // Make sure any hosted exceptions get propagated to service error handling
            httpConfig.Services.Replace(typeof(IExceptionHandler), new HostedExceptionHandler());

            // Enabled detailed client errors
            hubConfig.EnableDetailedErrors = true;

            // Load ServiceHub SignalR class
            app.MapSignalR(hubConfig);

            // Map specific historian instance API controllers
            httpConfig.Routes.MapHttpRoute(
                name: "InstanceAPIs",
                routeTemplate: "instance/{instanceName}/{controller}/{action}/{id}",
                defaults: new { action = "Index", id = RouteParameter.Optional }
                );

            // Map custom API controllers
            httpConfig.Routes.MapHttpRoute(
                name: "CustomAPIs",
                routeTemplate: "api/{controller}/{action}/{id}",
                defaults: new { action = "Index", id = RouteParameter.Optional }
                );

            // Set configuration to use reflection to setup routes
            httpConfig.MapHttpAttributeRoutes();

            // Load the WebPageController class and assign its routes
            app.UseWebApi(httpConfig);

            // Check for configuration issues before first request
            httpConfig.EnsureInitialized();
        }