Exemplo n.º 1
0
    public void RuntimeState_All_Routes(RuntimeLevel level)
    {
        var routes    = GetRoutes(level);
        var endpoints = new TestRouteBuilder();

        routes.CreateRoutes(endpoints);

        Assert.AreEqual(2, endpoints.DataSources.Count);
        var route = endpoints.DataSources.First();

        Assert.AreEqual(2, route.Endpoints.Count);

        var endpoint0 = (RouteEndpoint)route.Endpoints[0];

        Assert.AreEqual($"{routes.GetPreviewHubRoute()}/negotiate", endpoint0.RoutePattern.RawText);
        var endpoint1 = (RouteEndpoint)route.Endpoints[1];

        Assert.AreEqual($"{routes.GetPreviewHubRoute()}", endpoint1.RoutePattern.RawText);

        var endpoint3             = (RouteEndpoint)endpoints.DataSources.Last().Endpoints[0];
        var previewControllerName = ControllerExtensions.GetControllerName <PreviewController>();

        Assert.AreEqual(
            $"umbraco/{previewControllerName.ToLowerInvariant()}/{{action}}/{{id?}}",
            endpoint3.RoutePattern.RawText);
        Assert.AreEqual(Constants.Web.Mvc.BackOfficeArea, endpoint3.RoutePattern.Defaults["area"]);
        Assert.AreEqual("Index", endpoint3.RoutePattern.Defaults[ActionToken]);
        Assert.AreEqual(previewControllerName, endpoint3.RoutePattern.Defaults[ControllerToken]);
        Assert.AreEqual(
            endpoint3.RoutePattern.Defaults["area"],
            typeof(PreviewController).GetCustomAttribute <AreaAttribute>(false).RouteValue);
    }
Exemplo n.º 2
0
    public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
    {
        var sut = CreateInstructionProcessTask(runtimeLevel);
        await sut.PerformExecuteAsync(null);

        VerifyMessengerNotSynced();
    }
        private TouchServerTask CreateTouchServerTask(RuntimeLevel runtimeLevel = RuntimeLevel.Run, string applicationUrl = ApplicationUrl, bool useElection = true)
        {
            var mockRequestAccessor = new Mock <IHostingEnvironment>();

            mockRequestAccessor.SetupGet(x => x.ApplicationMainUrl).Returns(!string.IsNullOrEmpty(applicationUrl) ? new Uri(ApplicationUrl) : null);

            var mockRunTimeState = new Mock <IRuntimeState>();

            mockRunTimeState.SetupGet(x => x.Level).Returns(runtimeLevel);

            var mockLogger = new Mock <ILogger <TouchServerTask> >();

            _mockServerRegistrationService = new Mock <IServerRegistrationService>();

            var settings = new GlobalSettings
            {
                DatabaseServerRegistrar = new DatabaseServerRegistrarSettings
                {
                    StaleServerTimeout = _staleServerTimeout,
                }
            };

            IServerRoleAccessor roleAccessor = useElection
                ? new ElectedServerRoleAccessor(_mockServerRegistrationService.Object)
                : new SingleServerRoleAccessor();

            return(new TouchServerTask(
                       mockRunTimeState.Object,
                       _mockServerRegistrationService.Object,
                       mockRequestAccessor.Object,
                       mockLogger.Object,
                       Options.Create(settings),
                       roleAccessor));
        }
        public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
        {
            TouchServerTask sut = CreateTouchServerTask(runtimeLevel: runtimeLevel);
            await sut.PerformExecuteAsync(null);

            VerifyServerNotTouched();
        }
        public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
        {
            ScheduledPublishing sut = CreateScheduledPublishing(runtimeLevel: runtimeLevel);
            await sut.PerformExecuteAsync(null);

            VerifyScheduledPublishingNotPerformed();
        }
Exemplo n.º 6
0
        public void RuntimeState_Install(RuntimeLevel level)
        {
            InstallAreaRoutes routes = GetInstallAreaRoutes(level);
            var endpoints            = new TestRouteBuilder();

            routes.CreateRoutes(endpoints);

            Assert.AreEqual(2, endpoints.DataSources.Count);
            EndpointDataSource route = endpoints.DataSources.First();

            Assert.AreEqual(2, route.Endpoints.Count);

            var endpoint1 = (RouteEndpoint)route.Endpoints[0];

            Assert.AreEqual($"install/api/{{action}}/{{id?}}", endpoint1.RoutePattern.RawText);
            Assert.AreEqual(Constants.Web.Mvc.InstallArea, endpoint1.RoutePattern.Defaults[AreaToken]);
            Assert.AreEqual("Index", endpoint1.RoutePattern.Defaults[ActionToken]);
            Assert.AreEqual(ControllerExtensions.GetControllerName <InstallApiController>(), endpoint1.RoutePattern.Defaults[ControllerToken]);
            Assert.AreEqual(endpoint1.RoutePattern.Defaults[AreaToken], typeof(InstallApiController).GetCustomAttribute <AreaAttribute>(false).RouteValue);

            var endpoint2 = (RouteEndpoint)route.Endpoints[1];

            Assert.AreEqual($"install/{{action}}/{{id?}}", endpoint2.RoutePattern.RawText);
            Assert.AreEqual(Constants.Web.Mvc.InstallArea, endpoint2.RoutePattern.Defaults[AreaToken]);
            Assert.AreEqual("Index", endpoint2.RoutePattern.Defaults[ActionToken]);
            Assert.AreEqual(ControllerExtensions.GetControllerName <InstallController>(), endpoint2.RoutePattern.Defaults[ControllerToken]);
            Assert.AreEqual(endpoint2.RoutePattern.Defaults[AreaToken], typeof(InstallController).GetCustomAttribute <AreaAttribute>(false).RouteValue);

            EndpointDataSource fallbackRoute = endpoints.DataSources.Last();

            Assert.AreEqual(1, fallbackRoute.Endpoints.Count);

            Assert.AreEqual("Fallback {*path:nonfile}", fallbackRoute.Endpoints[0].ToString());
        }
Exemplo n.º 7
0
    private static Mock <IRuntimeState> CreateMockRuntimeState(RuntimeLevel runtimeLevel)
    {
        var mockRuntimeState = new Mock <IRuntimeState>();

        mockRuntimeState.SetupGet(x => x.Level).Returns(runtimeLevel);
        return(mockRuntimeState);
    }
Exemplo n.º 8
0
        public async Task Does_Not_Execute_When_Runtime_State_Is_Not_Run(RuntimeLevel runtimeLevel)
        {
            HealthCheckNotifier sut = CreateHealthCheckNotifier(runtimeLevel: runtimeLevel);
            await sut.PerformExecuteAsync(null);

            VerifyNotificationsNotSent();
        }
Exemplo n.º 9
0
        public static IRuntimeState MockRuntimeState(RuntimeLevel level)
        {
            var runtimeState = Mock.Of <IRuntimeState>();

            Mock.Get(runtimeState).Setup(x => x.Level).Returns(level);
            return(runtimeState);
        }
Exemplo n.º 10
0
        public void UmbracoApplicationEndRequest(HttpContext context, RuntimeLevel runtimeLevel)
        {
            if (runtimeLevel != RuntimeLevel.Run)
            {
                return;
            }

            if (ShouldProfile(context.Request))
            {
                Stop();

                if (MiniProfilerContext.Value is not null)
                {
                    // if this is the first request, append the startup profiler
                    var first = Interlocked.Exchange(ref _first, 1) == 0;
                    if (first)
                    {
                        var startupDuration = _startupProfiler.Root.DurationMilliseconds.GetValueOrDefault();
                        MiniProfilerContext.Value.DurationMilliseconds += startupDuration;
                        MiniProfilerContext.Value.GetTimingHierarchy().First().DurationMilliseconds += startupDuration;
                        MiniProfilerContext.Value.Root.AddChild(_startupProfiler.Root);

                        _startupProfiler = null;
                    }
                }
            }
        }
        private BackOfficeHandler CreateHandler(RuntimeLevel runtimeLevel = RuntimeLevel.Run, bool currentUserIsAuthenticated = false, bool currentUserIsApproved = false)
        {
            Mock <IBackOfficeSecurityAccessor> mockBackOfficeSecurityAccessor = CreateMockBackOfficeSecurityAccessor(currentUserIsAuthenticated, currentUserIsApproved);
            Mock <IRuntimeState> mockRuntimeState = CreateMockRuntimeState(runtimeLevel);

            return(new BackOfficeHandler(mockBackOfficeSecurityAccessor.Object, mockRuntimeState.Object));
        }
Exemplo n.º 12
0
    public void RuntimeState_No_Routes(RuntimeLevel level)
    {
        var routes    = GetBackOfficeAreaRoutes(level);
        var endpoints = new TestRouteBuilder();

        routes.CreateRoutes(endpoints);

        Assert.AreEqual(0, endpoints.DataSources.Count);
    }
Exemplo n.º 13
0
 private void ReportRuntime(RuntimeLevel level, string message)
 {
     if (_reported && _reportedLevel == level)
     {
         return;
     }
     _reported      = true;
     _reportedLevel = level;
     _logger.Warn <UmbracoModule>(message);
 }
Exemplo n.º 14
0
 private static void ReportRuntime(ILogger <InstallController> logger, RuntimeLevel level, string message)
 {
     if (_reported && _reportedLevel == level)
     {
         return;
     }
     _reported      = true;
     _reportedLevel = level;
     logger.LogWarning(message);
 }
Exemplo n.º 15
0
        public void Configure(RuntimeLevel level, RuntimeLevelReason reason, Exception bootFailedException = null)
        {
            Level  = level;
            Reason = reason;

            if (bootFailedException != null)
            {
                BootFailedException = new BootFailedException(bootFailedException.Message, bootFailedException);
            }
        }
Exemplo n.º 16
0
    private PreviewRoutes GetRoutes(RuntimeLevel level)
    {
        var globalSettings = new GlobalSettings();
        var routes         = new PreviewRoutes(
            Options.Create(globalSettings),
            Mock.Of <IHostingEnvironment>(x =>
                                          x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
            Mock.Of <IRuntimeState>(x => x.Level == level));

        return(routes);
    }
        private BackOfficeAreaRoutes GetBackOfficeAreaRoutes(RuntimeLevel level)
        {
            var globalSettings = new GlobalSettings();
            var routes         = new BackOfficeAreaRoutes(
                Options.Create(globalSettings),
                Mock.Of <IHostingEnvironment>(x => x.ToAbsolute(It.IsAny <string>()) == "/umbraco" && x.ApplicationVirtualPath == string.Empty),
                Mock.Of <IRuntimeState>(x => x.Level == level),
                new UmbracoApiControllerTypeCollection(() => new[] { typeof(Testing1Controller) }));

            return(routes);
        }
Exemplo n.º 18
0
        /// <summary>
        /// Initializes the edit mode menu, and sets the activate level metadata.
        /// </summary>
        /// <param name="levelMetadata"></param>
        public void BeginEdit(RuntimeLevel level)
        {
            if (Activate)
            {
                return;
            }

            activateLevel         = level;
            activateLevelMetadata = level.LevelMetadata;

            CreateMenu();
        }
Exemplo n.º 19
0
        public void UmbracoApplicationBeginRequest(HttpContext context, RuntimeLevel runtimeLevel)
        {
            if (runtimeLevel != RuntimeLevel.Run)
            {
                return;
            }

            if (ShouldProfile(context.Request))
            {
                Start();
            }
        }
Exemplo n.º 20
0
        private void StopEditing()
        {
            if (!Activate)
            {
                return;
            }

            CameraManager.Stop();

            activateLevel         = null;
            activateLevelMetadata = null;
        }
        private ScheduledPublishing CreateScheduledPublishing(
            bool enabled = true,
            RuntimeLevel runtimeLevel = RuntimeLevel.Run,
            ServerRole serverRole     = ServerRole.Single,
            bool isMainDom            = true)
        {
            if (enabled)
            {
                Suspendable.ScheduledPublishing.Resume();
            }
            else
            {
                Suspendable.ScheduledPublishing.Suspend();
            }

            var mockRunTimeState = new Mock <IRuntimeState>();

            mockRunTimeState.SetupGet(x => x.Level).Returns(runtimeLevel);

            var mockServerRegistrar = new Mock <IServerRoleAccessor>();

            mockServerRegistrar.Setup(x => x.CurrentServerRole).Returns(serverRole);

            var mockMainDom = new Mock <IMainDom>();

            mockMainDom.SetupGet(x => x.IsMainDom).Returns(isMainDom);

            _mockContentService = new Mock <IContentService>();

            var mockUmbracoContextFactory = new Mock <IUmbracoContextFactory>();

            mockUmbracoContextFactory.Setup(x => x.EnsureUmbracoContext()).Returns(new UmbracoContextReference(null, false, null));

            _mockLogger = new Mock <ILogger <ScheduledPublishing> >();

            var mockServerMessenger = new Mock <IServerMessenger>();

            var mockScopeProvider = new Mock <IScopeProvider>();

            mockScopeProvider
            .Setup(x => x.CreateScope(It.IsAny <IsolationLevel>(), It.IsAny <RepositoryCacheMode>(), It.IsAny <IEventDispatcher>(), It.IsAny <IScopedNotificationPublisher>(), It.IsAny <bool?>(), It.IsAny <bool>(), It.IsAny <bool>()))
            .Returns(Mock.Of <IScope>());

            return(new ScheduledPublishing(
                       mockRunTimeState.Object,
                       mockMainDom.Object,
                       mockServerRegistrar.Object,
                       _mockContentService.Object,
                       mockUmbracoContextFactory.Object,
                       _mockLogger.Object,
                       mockServerMessenger.Object,
                       mockScopeProvider.Object));
        }
Exemplo n.º 22
0
        private InstructionProcessTask CreateInstructionProcessTask(RuntimeLevel runtimeLevel = RuntimeLevel.Run)
        {
            var mockRunTimeState = new Mock <IRuntimeState>();

            mockRunTimeState.SetupGet(x => x.Level).Returns(runtimeLevel);

            var mockLogger = new Mock <ILogger <InstructionProcessTask> >();

            _mockDatabaseServerMessenger = new Mock <IServerMessenger>();

            var settings = new GlobalSettings();

            return(new InstructionProcessTask(mockRunTimeState.Object, _mockDatabaseServerMessenger.Object, mockLogger.Object, Options.Create(settings)));
        }
Exemplo n.º 23
0
        public void UmbracoApplicationBeginRequest(HttpContext context, RuntimeLevel runtimeLevel)
        {
            if (runtimeLevel != RuntimeLevel.Run)
            {
                return;
            }

            if (ShouldProfile(context.Request))
            {
                Start();
                ICookieManager cookieManager = GetCookieManager(context);
                cookieManager.ExpireCookie(WebProfileCookieKey); //Ensure we expire the cookie, so we do not reuse the old potential value saved
            }
        }
        private Dictionary <string, object> GetModelsBuilderSettings(RuntimeLevel level)
        {
            if (level != RuntimeLevel.Run)
            {
                return(null);
            }

            var settings = new Dictionary <string, object>
            {
                { "enabled", UmbracoConfig.For.ModelsBuilder().Enable }
            };

            return(settings);
        }
 private HealthCheckNotifier CreateHealthCheckNotifier(
     bool enabled = true,
     RuntimeLevel runtimeLevel = RuntimeLevel.Run,
     ServerRole serverRole     = ServerRole.Single,
     bool isMainDom            = true,
     bool notificationEnabled  = true)
 {
     var settings = new HealthChecksSettings
     {
         Notification = new HealthChecksNotificationSettings
         {
             Enabled        = enabled,
             DisabledChecks = new List <DisabledHealthCheckSettings> {
                 new() { Id = Guid.Parse(Check3Id) }
             },
         },
Exemplo n.º 26
0
        private void BeginLevelLoad()
        {
            if (Level == null)
            {
                if (IsLevelLoaded)
                {
                    IsLevelLoaded = false;
                }

                return;
            }

            if (!IsLevelLoaded)
            {
                if (!Game.IsScreenFadingOut)
                {
                    Game.FadeScreenOut(screenFadeTime);
                }

                if (Game.IsScreenFadedOut)
                {
                    // DEBUGGING
                    Game.Player.Character.Position       = Level.LevelMetadata.Position;
                    Game.Player.Character.FreezePosition = true;

                    if (initialLevel != null)
                    {
                        initialLevel.Stop();

                        initialLevel = null;
                    }

                    LoadLevel(Level);

                    IsLevelLoaded = true;

                    if (SpaceLevelEditor.Activate)
                    {
                        SpaceLevelEditor.Init();
                    }

                    Game.FadeScreenIn(screenFadeTime);
                }
            }
        }
Exemplo n.º 27
0
        private void OnFileSelected(object sender, NativeMenuItemEventArgs e)
        {
            if (e.MenuItem == null)
            {
                return;
            }

            var levelMetadata = (SpaceLevel)e.MenuItem.Tag;

            if (levelMetadata == null)
            {
                return;
            }

            Level = new RuntimeLevel(levelMetadata);

            SpaceLevelEditor.BeginEdit(Level);
        }
Exemplo n.º 28
0
        public void UmbracoApplicationEndRequest(HttpContext context, RuntimeLevel runtimeLevel)
        {
            if (runtimeLevel != RuntimeLevel.Run)
            {
                return;
            }

            if (ShouldProfile(context.Request))
            {
                Stop();

                if (MiniProfilerContext.Value is not null)
                {
                    // if this is the first request, append the startup profiler
                    var first = Interlocked.Exchange(ref _first, 1) == 0;
                    if (first)
                    {
                        if (_startupProfiler is not null)
                        {
                            AddSubProfiler(_startupProfiler);
                        }

                        _startupProfiler = null;
                    }

                    ICookieManager cookieManager = GetCookieManager(context);
                    var            cookieValue   = cookieManager.GetCookieValue(WebProfileCookieKey);

                    if (cookieValue is not null)
                    {
                        AddSubProfiler(MiniProfiler.FromJson(cookieValue));
                    }

                    //If it is a redirect to a relative path (local redirect)
                    if (context.Response.StatusCode == (int)HttpStatusCode.Redirect &&
                        context.Response.Headers.TryGetValue(Microsoft.Net.Http.Headers.HeaderNames.Location, out var location) &&
                        !location.Contains("://"))
                    {
                        MiniProfilerContext.Value.Root.Name = "Before Redirect";
                        cookieManager.SetCookieValue(WebProfileCookieKey, MiniProfilerContext.Value.ToJson());
                    }
                }
            }
        }
        public void RuntimeState_All_Routes(RuntimeLevel level)
        {
            BackOfficeAreaRoutes routes = GetBackOfficeAreaRoutes(level);
            var endpoints = new TestRouteBuilder();

            routes.CreateRoutes(endpoints);

            Assert.AreEqual(1, endpoints.DataSources.Count);
            EndpointDataSource route = endpoints.DataSources.First();

            Assert.AreEqual(3, route.Endpoints.Count);

            AssertMinimalBackOfficeRoutes(route);

            var    endpoint4         = (RouteEndpoint)route.Endpoints[2];
            string apiControllerName = ControllerExtensions.GetControllerName <Testing1Controller>();

            Assert.AreEqual($"umbraco/backoffice/api/{apiControllerName.ToLowerInvariant()}/{{action}}/{{id?}}", endpoint4.RoutePattern.RawText);
            Assert.IsFalse(endpoint4.RoutePattern.Defaults.ContainsKey(AreaToken));
            Assert.IsFalse(endpoint4.RoutePattern.Defaults.ContainsKey(ActionToken));
            Assert.AreEqual(apiControllerName, endpoint4.RoutePattern.Defaults[ControllerToken]);
        }
        private void InstallServerVars(RuntimeLevel level)
        {
            // register our url - for the backoffice api
            ServerVariablesParser.Parsing += (sender, serverVars) =>
            {
                if (!serverVars.ContainsKey("umbracoUrls"))
                {
                    throw new Exception("Missing umbracoUrls.");
                }
                var umbracoUrlsObject = serverVars["umbracoUrls"];
                if (umbracoUrlsObject == null)
                {
                    throw new Exception("Null umbracoUrls");
                }
                if (!(umbracoUrlsObject is Dictionary <string, object> umbracoUrls))
                {
                    throw new Exception("Invalid umbracoUrls");
                }

                if (!serverVars.ContainsKey("umbracoPlugins"))
                {
                    throw new Exception("Missing umbracoPlugins.");
                }
                if (!(serverVars["umbracoPlugins"] is Dictionary <string, object> umbracoPlugins))
                {
                    throw new Exception("Invalid umbracoPlugins");
                }

                if (HttpContext.Current == null)
                {
                    throw new InvalidOperationException("HttpContext is null");
                }
                var urlHelper = new UrlHelper(new RequestContext(new HttpContextWrapper(HttpContext.Current), new RouteData()));

                umbracoUrls["modelsBuilderBaseUrl"] = urlHelper.GetUmbracoApiServiceBaseUrl <ModelsBuilderBackOfficeController>(controller => controller.BuildModels());
                umbracoPlugins["modelsBuilder"]     = GetModelsBuilderSettings(level);
            };
        }