コード例 #1
0
        // initializes a new instance of the UmbracoContext class
        // internal for unit tests
        // otherwise it's used by EnsureContext above
        // warn: does *not* manage setting any IUmbracoContextAccessor
        internal UmbracoContext(HttpContextBase httpContext,
                                IPublishedSnapshotService publishedSnapshotService,
                                WebSecurity webSecurity,
                                IUmbracoSettingsSection umbracoSettings,
                                IEnumerable <IUrlProvider> urlProviders,
                                IGlobalSettings globalSettings,
                                IVariationContextAccessor variationContextAccessor)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }
            if (publishedSnapshotService == null)
            {
                throw new ArgumentNullException(nameof(publishedSnapshotService));
            }
            if (webSecurity == null)
            {
                throw new ArgumentNullException(nameof(webSecurity));
            }
            if (umbracoSettings == null)
            {
                throw new ArgumentNullException(nameof(umbracoSettings));
            }
            if (urlProviders == null)
            {
                throw new ArgumentNullException(nameof(urlProviders));
            }
            VariationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
            _globalSettings          = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings));

            // ensure that this instance is disposed when the request terminates, though we *also* ensure
            // this happens in the Umbraco module since the UmbracoCOntext is added to the HttpContext items.
            //
            // also, it *can* be returned by the container with a PerRequest lifetime, meaning that the
            // container *could* also try to dispose it.
            //
            // all in all, this context may be disposed more than once, but DisposableObject ensures that
            // it is ok and it will be actually disposed only once.
            httpContext.DisposeOnPipelineCompleted(this);

            ObjectCreated    = DateTime.Now;
            UmbracoRequestId = Guid.NewGuid();
            HttpContext      = httpContext;
            Security         = webSecurity;

            // beware - we cannot expect a current user here, so detecting preview mode must be a lazy thing
            _publishedSnapshot = new Lazy <IPublishedSnapshot>(() => publishedSnapshotService.CreatePublishedSnapshot(PreviewToken));

            // set the urls...
            // NOTE: The request will not be available during app startup so we can only set this to an absolute URL of localhost, this
            // is a work around to being able to access the UmbracoContext during application startup and this will also ensure that people
            // 'could' still generate URLs during startup BUT any domain driven URL generation will not work because it is NOT possible to get
            // the current domain during application startup.
            // see: http://issues.umbraco.org/issue/U4-1890
            //
            OriginalRequestUrl = GetRequestFromContext()?.Url ?? new Uri("http://localhost");
            CleanedUmbracoUrl  = UriUtility.UriToUmbraco(OriginalRequestUrl);
            UrlProvider        = new UrlProvider(this, umbracoSettings.WebRouting, urlProviders, variationContextAccessor);
        }
コード例 #2
0
        internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings, IServerRegistrar serverRegistrar)
        {
            // try umbracoSettings:settings/web.routing/@umbracoApplicationUrl
            // which is assumed to:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            var url = settings.WebRouting.UmbracoApplicationUrl;

            if (url.IsNullOrWhiteSpace() == false)
            {
                var umbracoApplicationUrl = url.TrimEnd(Constants.CharArrays.ForwardSlash);
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (using web.routing/@umbracoApplicationUrl)", umbracoApplicationUrl);
                return(umbracoApplicationUrl);
            }

            // try the server registrar
            // which is assumed to return a URL that:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            url = serverRegistrar.GetCurrentServerUmbracoApplicationUrl();
            if (url.IsNullOrWhiteSpace() == false)
            {
                var umbracoApplicationUrl = url.TrimEnd(Constants.CharArrays.ForwardSlash);
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (IServerRegistrar)", umbracoApplicationUrl);
                return(umbracoApplicationUrl);
            }

            // else give up...
            return(null);
        }
コード例 #3
0
 public LogScrubber(IBackgroundTaskRunner <RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
                    ApplicationContext appContext, IUmbracoSettingsSection settings)
     : base(runner, delayMilliseconds, periodMilliseconds)
 {
     _appContext = appContext;
     _settings   = settings;
 }
        private static void SetUmbracoSettings(IUmbracoSettingsSection umbracoSettingsSection)
        {
            var type   = typeof(UmbracoConfig);
            var method = type.GetMethod("SetUmbracoSettings", BindingFlags.Instance | BindingFlags.NonPublic);

            method.Invoke(UmbracoConfig.For, new object[] { umbracoSettingsSection });
        }
コード例 #5
0
        private IBackgroundTask RegisterTaskRunner(IUmbracoSettingsSection settings)
        {
            var task = new ScheduledTasks(_tasksRunner, 60000, 60000, _runtime, settings, _logger);

            _tasksRunner.TryAdd(task);
            return(task);
        }
コード例 #6
0
 /// <summary>
 /// Constructor - can be used for testing
 /// </summary>
 /// <param name="umbracoSettings"></param>
 /// <param name="baseRestSettings"></param>
 /// <param name="dashboardSettings"></param>
 /// <param name="healthChecks"></param>
 public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IBaseRestSection baseRestSettings, IDashboardSection dashboardSettings, IHealthChecks healthChecks)
 {
     SetHealthCheckSettings(healthChecks);
     SetUmbracoSettings(umbracoSettings);
     SetBaseRestExtensions(baseRestSettings);
     SetDashboardSettings(dashboardSettings);
 }
コード例 #7
0
        protected ServiceContext GetServiceContext(IUmbracoSettingsSection umbracoSettings, ILogger logger)
        {
            //get the mocked service context to get the mocked domain service
            var svcCtx = MockHelper.GetMockedServiceContext();

            var domainService = Mock.Get(svcCtx.DomainService);

            //setup mock domain service
            domainService.Setup(service => service.GetAll(It.IsAny <bool>()))
            .Returns((bool incWildcards) => new[]
            {
                new UmbracoDomain("domain1.com/")
                {
                    Id = 1, LanguageId = LangDeId, RootContentId = 1001, LanguageIsoCode = "de-DE"
                },
                new UmbracoDomain("domain1.com/en")
                {
                    Id = 1, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"
                },
                new UmbracoDomain("domain1.com/fr")
                {
                    Id = 1, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"
                }
            });

            return(svcCtx);
        }
コード例 #8
0
 public ReportSiteTask(IBackgroundTaskRunner <RecurringTaskBase> runner, int delayBeforeWeStart, int howOftenWeRepeat, IProfilingLogger logger, IUmbracoSettingsSection settings)
     : base(runner, delayBeforeWeStart, howOftenWeRepeat)
 {
     _logger     = logger;
     _httpClient = new HttpClient();
     _settings   = settings;
 }
コード例 #9
0
        public ContextMocker(string[] qKeys = null)
        {
            ILogger     loggerMock   = Mock.Of <ILogger>();
            IProfiler   profilerMock = Mock.Of <IProfiler>();
            IDictionary dictionary   = Mock.Of <IDictionary>();// this is related to injecting the dictionary into the mocked UmbracoHelper

            var session         = new Mock <HttpSessionStateBase>();
            var contextBaseMock = new Mock <HttpContextBase>();

            contextBaseMock.Setup(ctx => ctx.Session).Returns(session.Object);
            contextBaseMock.SetupGet(ctx => ctx.Items).Returns(dictionary);//// this is related to injecting the dictionary into the mocked UmbracoHelper

            if (qKeys != null)
            {
                var requestMock = new Mock <HttpRequestBase>();
                requestMock.SetupGet(r => r.Url).Returns(new Uri("http://imaginary.com"));
                var mockedQstring = new Mock <NameValueCollection>();

                foreach (var k in qKeys)
                {
                    mockedQstring.Setup(r => r.Get(It.Is <string>(s => s.Contains(k)))).Returns("example_value_" + k);
                }

                requestMock.SetupGet(r => r.QueryString).Returns(mockedQstring.Object);
                contextBaseMock.SetupGet(p => p.Request).Returns(requestMock.Object);
            }

            WebSecurity             webSecurityMock            = new Mock <WebSecurity>(null, null).Object;
            IUmbracoSettingsSection umbracoSettingsSectionMock = Mock.Of <IUmbracoSettingsSection>();

            HttpContextBaseMock    = contextBaseMock.Object;
            ApplicationContextMock = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(loggerMock, profilerMock));
            UmbracoContextMock     = UmbracoContext.EnsureContext(contextBaseMock.Object, ApplicationContextMock, webSecurityMock, umbracoSettingsSectionMock, Enumerable.Empty <IUrlProvider>(), true);
        }
コード例 #10
0
        public UserPasswordPolicy(MembershipProviderBase provider, IUmbracoSettingsSection umbracoSettings) : base(provider)
        {
            if (umbracoSettings != null)
            {
                ForgotPasswordLinkAvailable = umbracoSettings.Security.AllowPasswordReset;
                DisableAlternativeTemplates = umbracoSettings.WebRouting.DisableAlternativeTemplates;
                DisableFindContentById      = umbracoSettings.WebRouting.DisableFindContentByIdPath;
            }

            if (int.TryParse(ConfigurationManager.AppSettings["umbracoTimeOutInMinutes"], out int timeout))
            {
                UmbracoTimeoutInMinutes = timeout;
            }

            if (bool.TryParse(ConfigurationManager.AppSettings["umbracoUseSSL"], out bool umbracoUseSSL))
            {
                UmbracoUseSSL = umbracoUseSSL;
            }

            if (ConfigurationManager.GetSection("system.web/httpRuntime") is HttpRuntimeSection httpRuntimeSection)
            {
                MaxRequestLength = httpRuntimeSection.MaxRequestLength;
            }

            // TODO: MaxAllowedContentLength
            // TODO: MaxRequestLengthUmbraco
            // TODO: MaxAllowedContentLengthUmbraco
        }
コード例 #11
0
        public override void Initialize()
        {
            base.Initialize();

            //generate new mock settings and assign so we can configure in individual tests
            _umbracoSettings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(_umbracoSettings);

            var url = "/test";

            var lookup  = new Umbraco.Web.Routing.ContentFinderByNiceUrl();
            var lookups = new Umbraco.Web.Routing.IContentFinder[] { lookup };

            var t = Template.MakeNew("test", new User(0));

            var umbracoContext = GetUmbracoContext(url, t.Id);
            var urlProvider    = new UrlProvider(umbracoContext, _umbracoSettings.WebRouting, new IUrlProvider[] { new DefaultUrlProvider() });
            var routingContext = new RoutingContext(
                umbracoContext,
                lookups,
                new FakeLastChanceFinder(),
                urlProvider);

            //assign the routing context back to the umbraco context
            umbracoContext.RoutingContext = routingContext;

            ////assign the routing context back to the umbraco context
            //umbracoContext.RoutingContext = routingContext;
            Umbraco.Web.UmbracoContext.Current = routingContext.UmbracoContext;
        }
コード例 #12
0
 public ScheduledTasks(IBackgroundTaskRunner <RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
                       IRuntimeState runtime, IUmbracoSettingsSection settings, IProfilingLogger logger)
     : base(runner, delayMilliseconds, periodMilliseconds)
 {
     _runtime  = runtime;
     _settings = settings;
     _logger   = logger;
 }
コード例 #13
0
        public override void Initialize()
        {
            base.Initialize();

            //generate new mock settings and assign so we can configure in individual tests
            _umbracoSettings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(_umbracoSettings);
        }
コード例 #14
0
        /// <summary>
        /// Creates a standalone UmbracoContext instance
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="applicationContext"></param>
        /// <param name="webSecurity"></param>
        /// <param name="umbracoSettings"></param>
        /// <param name="urlProviders"></param>
        /// <param name="preview"></param>
        /// <returns>
        /// A new instance of UmbracoContext
        /// </returns>
        public static UmbracoContext CreateContext(
            HttpContextBase httpContext,
            ApplicationContext applicationContext,
            WebSecurity webSecurity,
            IUmbracoSettingsSection umbracoSettings,
            IEnumerable <IUrlProvider> urlProviders,
            bool?preview)
        {
            if (httpContext == null)
            {
                throw new ArgumentNullException("httpContext");
            }
            if (applicationContext == null)
            {
                throw new ArgumentNullException("applicationContext");
            }
            if (webSecurity == null)
            {
                throw new ArgumentNullException("webSecurity");
            }
            if (umbracoSettings == null)
            {
                throw new ArgumentNullException("umbracoSettings");
            }
            if (urlProviders == null)
            {
                throw new ArgumentNullException("urlProviders");
            }

            var umbracoContext = new UmbracoContext(
                httpContext,
                applicationContext,
                new Lazy <IPublishedCaches>(() => PublishedCachesResolver.Current.Caches, false),
                webSecurity,
                preview);

            // create the RoutingContext, and assign
            var routingContext = new RoutingContext(
                umbracoContext,

                //TODO: Until the new cache is done we can't really expose these to override/mock
                new Lazy <IEnumerable <IContentFinder> >(() => ContentFinderResolver.Current.Finders),
                new Lazy <IContentFinder>(() => ContentLastChanceFinderResolver.Current.Finder),

                // create the nice urls provider
                // there's one per request because there are some behavior parameters that can be changed
                new Lazy <UrlProvider>(
                    () => new UrlProvider(
                        umbracoContext,
                        umbracoSettings.WebRouting,
                        urlProviders),
                    false));

            //assign the routing context back
            umbracoContext.RoutingContext = routingContext;

            return(umbracoContext);
        }
コード例 #15
0
 public TestServices(HttpRequestMessage httpRequestMessage, UmbracoContext umbracoContext, ITypedPublishedContentQuery publishedContentQuery, ServiceContext serviceContext, BaseSearchProvider searchProvider, IUmbracoSettingsSection umbracoSettings)
 {
     HttpRequestMessage    = httpRequestMessage;
     UmbracoContext        = umbracoContext;
     PublishedContentQuery = publishedContentQuery;
     ServiceContext        = serviceContext;
     SearchProvider        = searchProvider;
     UmbracoSettings       = umbracoSettings;
 }
コード例 #16
0
        private IBackgroundTask RegisterLogScrubber(IUmbracoSettingsSection settings)
        {
            // log scrubbing
            // install on all, will only run on non-replica servers
            var task = new LogScrubber(_scrubberRunner, DefaultDelayMilliseconds, LogScrubber.GetLogScrubbingInterval(settings, _logger), _runtime, _auditService, settings, _scopeProvider, _logger);

            _scrubberRunner.TryAdd(task);
            return(task);
        }
コード例 #17
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RuntimeState"/> class.
 /// </summary>
 public RuntimeState(ILogger logger, IUmbracoSettingsSection settings, IGlobalSettings globalSettings,
                     Lazy <IMainDom> mainDom, Lazy <IServerRegistrar> serverRegistrar)
 {
     _logger          = logger;
     _settings        = settings;
     _globalSettings  = globalSettings;
     _mainDom         = mainDom;
     _serverRegistrar = serverRegistrar;
 }
        private void SetupUmbraco()
        {
            settings = SettingsForTests.GenerateMockSettings();
            SettingsForTests.ConfigureSettings(settings);

            routingContext = GetRoutingContext("http://localhost", -1, new RouteData());
            umbracoContext = routingContext.UmbracoContext;
            umbracoContext.PublishedContentRequest = new PublishedContentRequest(new Uri("http://localhost"), routingContext,
                                                                                 settings.WebRouting, (s) => new[] { "Kunde" });
        }
コード例 #19
0
ファイル: LogScrubber.cs プロジェクト: swedishkid/umbraco
 public LogScrubber(IBackgroundTaskRunner <RecurringTaskBase> runner, int delayMilliseconds, int periodMilliseconds,
                    IRuntimeState runtime, IAuditService auditService, IUmbracoSettingsSection settings, IScopeProvider scopeProvider, IProfilingLogger logger)
     : base(runner, delayMilliseconds, periodMilliseconds)
 {
     _runtime       = runtime;
     _auditService  = auditService;
     _settings      = settings;
     _scopeProvider = scopeProvider;
     _logger        = logger;
 }
コード例 #20
0
        /// <summary>
        /// Gets an Umbraco Context instance for non pipeline requiests.
        /// </summary>
        /// <returns>The <see cref="UmbracoContext"/></returns>
        private UmbracoContext EnsureUmbracoContext()
        {
            HttpContextBase            context         = this.HttpContext;
            ApplicationContext         application     = ApplicationContext.Current;
            WebSecurity                security        = new WebSecurity(context, application);
            IUmbracoSettingsSection    umbracoSettings = UmbracoConfig.For.UmbracoSettings();
            IEnumerable <IUrlProvider> providers       = UrlProviderResolver.Current.Providers;

            return(UmbracoContext.EnsureContext(context, application, security, umbracoSettings, providers, false));
        }
コード例 #21
0
        // internal for tests
        internal static bool TrySetApplicationUrl(ApplicationContext appContext, IUmbracoSettingsSection settings)
        {
            var logger = appContext.ProfilingLogger.Logger;

            // try umbracoSettings:settings/web.routing/@umbracoApplicationUrl
            // which is assumed to:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            var url = settings.WebRouting.UmbracoApplicationUrl;

            if (url.IsNullOrWhiteSpace() == false)
            {
                appContext._umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + appContext.UmbracoApplicationUrl + " (using web.routing/@umbracoApplicationUrl)");
                return(true);
            }

            // try umbracoSettings:settings/scheduledTasks/@baseUrl
            // which is assumed to:
            // - end with SystemDirectories.Umbraco
            // - NOT contain any scheme (because, legacy)
            // - end or not with a slash, it will be taken care of
            // eg "mysite.com/umbraco"
            url = settings.ScheduledTasks.BaseUrl;
            if (url.IsNullOrWhiteSpace() == false)
            {
                var ssl = GlobalSettings.UseSSL ? "s" : "";
                url = "http" + ssl + "://" + url;
                appContext._umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + appContext.UmbracoApplicationUrl + " (using scheduledTasks/@baseUrl)");
                return(true);
            }

            // try the server registrar
            // which is assumed to return a url that:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            var resolver  = ServerRegistrarResolver.HasCurrent ? ServerRegistrarResolver.Current : null;
            var registrar = resolver == null ? null : resolver.Registrar as IServerRegistrar2;

            url = registrar == null ? null : registrar.GetCurrentServerUmbracoApplicationUrl();
            if (url.IsNullOrWhiteSpace() == false)
            {
                appContext._umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: " + appContext.UmbracoApplicationUrl + " (IServerRegistrar)");
                return(true);
            }

            // else give up...
            return(false);
        }
コード例 #22
0
        /// <summary>
        /// Sets the default configuration.
        /// </summary>
        /// <returns>The short string helper.</returns>
        public DefaultShortStringHelperConfig WithDefault(IUmbracoSettingsSection umbracoSettings)
        {
            ForceSafeAliases     = umbracoSettings.Content.ForceSafeAliases;
            UrlReplaceCharacters = umbracoSettings.RequestHandler.CharCollection
                                   .Where(x => string.IsNullOrEmpty(x.Char) == false)
                                   .ToDictionary(x => x.Char, x => x.Replacement);

            var urlSegmentConvertTo = CleanStringType.Utf8;

            if (umbracoSettings.RequestHandler.ConvertUrlsToAscii)
            {
                urlSegmentConvertTo = CleanStringType.Ascii;
            }
            if (umbracoSettings.RequestHandler.TryConvertUrlsToAscii)
            {
                urlSegmentConvertTo = CleanStringType.TryAscii;
            }

            return(WithConfig(CleanStringType.UrlSegment, new Config
            {
                PreFilter = ApplyUrlReplaceCharacters,
                PostFilter = x => CutMaxLength(x, 240),
                IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', // letter, digit or underscore
                StringType = urlSegmentConvertTo | CleanStringType.LowerCase,
                BreakTermsOnUpper = false,
                Separator = '-'
            }).WithConfig(CleanStringType.FileName, new Config
            {
                PreFilter = ApplyUrlReplaceCharacters,
                IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', // letter, digit or underscore
                StringType = CleanStringType.Utf8 | CleanStringType.LowerCase,
                BreakTermsOnUpper = false,
                Separator = '-'
            }).WithConfig(CleanStringType.Alias, new Config
            {
                PreFilter = ApplyUrlReplaceCharacters,
                IsTerm = (c, leading) => leading
                    ? char.IsLetter(c)                       // only letters
                    : (char.IsLetterOrDigit(c) || c == '_'), // letter, digit or underscore
                StringType = CleanStringType.Ascii | CleanStringType.UmbracoCase,
                BreakTermsOnUpper = false
            }).WithConfig(CleanStringType.UnderscoreAlias, new Config
            {
                PreFilter = ApplyUrlReplaceCharacters,
                IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', // letter, digit or underscore
                StringType = CleanStringType.Ascii | CleanStringType.UmbracoCase,
                BreakTermsOnUpper = false
            }).WithConfig(CleanStringType.ConvertCase, new Config
            {
                PreFilter = null,
                IsTerm = (c, leading) => char.IsLetterOrDigit(c) || c == '_', // letter, digit or underscore
                StringType = CleanStringType.Ascii,
                BreakTermsOnUpper = true
            }));
        }
コード例 #23
0
ファイル: UmbracoSupport.cs プロジェクト: soreng/UmbMapper
        private void Setup()
        {
            ILogger                 loggerMock                 = Mock.Of <ILogger>();
            IProfiler               profilerMock               = Mock.Of <IProfiler>();
            HttpContextBase         contextBaseMock            = Mock.Of <HttpContextBase>();
            WebSecurity             webSecurityMock            = new Mock <WebSecurity>(null, null).Object;
            IUmbracoSettingsSection umbracoSettingsSectionMock = Mock.Of <IUmbracoSettingsSection>();

            ApplicationContext.Current = new ApplicationContext(CacheHelper.CreateDisabledCacheHelper(), new ProfilingLogger(loggerMock, profilerMock));
            UmbracoContext.Current     = UmbracoContext.EnsureContext(contextBaseMock, ApplicationContext.Current, webSecurityMock, umbracoSettingsSectionMock, Enumerable.Empty <IUrlProvider>(), true);
        }
コード例 #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="UmbracoContextFactory"/> class.
        /// </summary>
        public UmbracoContextFactory(IUmbracoContextAccessor umbracoContextAccessor, IPublishedSnapshotService publishedSnapshotService, IVariationContextAccessor variationContextAccessor, IDefaultCultureAccessor defaultCultureAccessor, IUmbracoSettingsSection umbracoSettings, IGlobalSettings globalSettings, UrlProviderCollection urlProviders, IUserService userService)
        {
            _umbracoContextAccessor   = umbracoContextAccessor ?? throw new ArgumentNullException(nameof(umbracoContextAccessor));
            _publishedSnapshotService = publishedSnapshotService ?? throw new ArgumentNullException(nameof(publishedSnapshotService));
            _variationContextAccessor = variationContextAccessor ?? throw new ArgumentNullException(nameof(variationContextAccessor));
            _defaultCultureAccessor   = defaultCultureAccessor ?? throw new ArgumentNullException(nameof(defaultCultureAccessor));

            _umbracoSettings = umbracoSettings ?? throw new ArgumentNullException(nameof(umbracoSettings));
            _globalSettings  = globalSettings ?? throw new ArgumentNullException(nameof(globalSettings));
            _urlProviders    = urlProviders ?? throw new ArgumentNullException(nameof(urlProviders));
            _userService     = userService ?? throw new ArgumentNullException(nameof(userService));
        }
コード例 #25
0
        ///  <summary>
        ///  Ensures that there is a "current" UmbracoContext.
        ///  </summary>
        /// <param name="umbracoContextAccessor"></param>
        /// <param name="httpContext">An http context.</param>
        /// <param name="publishedSnapshotService">A published snapshot service.</param>
        /// <param name="webSecurity">A security helper.</param>
        /// <param name="umbracoSettings">The umbraco settings.</param>
        /// <param name="urlProviders">Some url providers.</param>
        /// <param name="globalSettings"></param>
        /// <param name="replace">A value indicating whether to replace the existing context.</param>
        ///  <returns>The "current" UmbracoContext.</returns>
        ///  <remarks>
        ///  fixme - this needs to be clarified
        ///
        ///  If <paramref name="replace"/> is true then the "current" UmbracoContext is replaced
        ///  with a new one even if there is one already. See <see cref="WebRuntimeComponent"/>. Has to do with
        ///  creating a context at startup and not being able to access httpContext.Request at that time, so
        ///  the OriginalRequestUrl remains unspecified until <see cref="UmbracoModule"/> replaces the context.
        ///
        ///  This *has* to be done differently!
        ///
        ///  See http://issues.umbraco.org/issue/U4-1890, http://issues.umbraco.org/issue/U4-1717
        ///
        ///  </remarks>
        // used by
        // UmbracoModule BeginRequest (since it's a request it has an UmbracoContext)
        //   in BeginRequest so *late* ie *after* the HttpApplication has started (+ init? check!)
        // WebRuntimeComponent (and I'm not quite sure why)
        // -> because an UmbracoContext seems to be required by UrlProvider to get the "current" published snapshot?
        //    note: at startup not sure we have an HttpContext.Current
        //          at startup not sure we have an httpContext.Request => hard to tell "current" url
        //          should we have a post-boot event of some sort for ppl that *need* ?!
        //          can we have issues w/ routing context?
        // and tests
        // can .ContentRequest be null? of course!
        public static UmbracoContext EnsureContext(
            IUmbracoContextAccessor umbracoContextAccessor,
            HttpContextBase httpContext,
            IPublishedSnapshotService publishedSnapshotService,
            WebSecurity webSecurity,
            IUmbracoSettingsSection umbracoSettings,
            IEnumerable <IUrlProvider> urlProviders,
            IGlobalSettings globalSettings,
            IVariationContextAccessor variationContextAccessor,
            bool replace = false)
        {
            if (umbracoContextAccessor == null)
            {
                throw new ArgumentNullException(nameof(umbracoContextAccessor));
            }
            if (httpContext == null)
            {
                throw new ArgumentNullException(nameof(httpContext));
            }
            if (publishedSnapshotService == null)
            {
                throw new ArgumentNullException(nameof(publishedSnapshotService));
            }
            if (webSecurity == null)
            {
                throw new ArgumentNullException(nameof(webSecurity));
            }
            if (umbracoSettings == null)
            {
                throw new ArgumentNullException(nameof(umbracoSettings));
            }
            if (urlProviders == null)
            {
                throw new ArgumentNullException(nameof(urlProviders));
            }
            if (globalSettings == null)
            {
                throw new ArgumentNullException(nameof(globalSettings));
            }

            // if there is already a current context, return if not replacing
            var current = umbracoContextAccessor.UmbracoContext;

            if (current != null && replace == false)
            {
                return(current);
            }

            // create & assign to accessor, dispose existing if any
            umbracoContextAccessor.UmbracoContext?.Dispose();
            return(umbracoContextAccessor.UmbracoContext = new UmbracoContext(httpContext, publishedSnapshotService, webSecurity, umbracoSettings, urlProviders, globalSettings, variationContextAccessor));
        }
コード例 #26
0
 public static UmbracoContext GetUmbracoContext(ApplicationContext applicationContext   = null, IWebRoutingSection webRoutingSettings   = null, HttpContextBase httpContext = null, WebSecurity webSecurity = null,
                                                IUmbracoSettingsSection settingsSection = null, IEnumerable <IUrlProvider> urlProviders = null)
 {
     httpContext        = httpContext ?? new Mock <HttpContextBase>().Object;
     applicationContext = applicationContext ?? GetApplicationContext();
     return(UmbracoContext.EnsureContext(
                httpContext,
                applicationContext,
                webSecurity ?? GetWebSecurity(http: httpContext, application: applicationContext),
                settingsSection ?? Mock.Of <IUmbracoSettingsSection>(section => section.WebRouting == (webRoutingSettings ?? GetBasicWebRoutingSettings())),
                urlProviders ?? Enumerable.Empty <IUrlProvider>(),
                true));
 }
コード例 #27
0
        public UserPasswordPolicy GetPasswordPolicy()
        {
            UsersMembershipProvider userMembershipProvider = Membership.Providers["UsersMembershipProvider"] as UsersMembershipProvider;

            if (userMembershipProvider == null)
            {
                return(null);
            }

            IUmbracoSettingsSection umbracoSettings = UmbracoConfig.For.UmbracoSettings();

            return(new UserPasswordPolicy(userMembershipProvider, umbracoSettings));
        }
コード例 #28
0
        internal static string TryGetApplicationUrl(IUmbracoSettingsSection settings, ILogger logger, IGlobalSettings globalSettings, IServerRegistrar serverRegistrar)
        {
            // try umbracoSettings:settings/web.routing/@umbracoApplicationUrl
            // which is assumed to:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            var url = settings.WebRouting.UmbracoApplicationUrl;

            if (url.IsNullOrWhiteSpace() == false)
            {
                var umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (using web.routing/@umbracoApplicationUrl)", umbracoApplicationUrl);
                return(umbracoApplicationUrl);
            }

            // try umbracoSettings:settings/scheduledTasks/@baseUrl
            // which is assumed to:
            // - end with SystemDirectories.Umbraco
            // - NOT contain any scheme (because, legacy)
            // - end or not with a slash, it will be taken care of
            // eg "mysite.com/umbraco"
            url = settings.ScheduledTasks.BaseUrl;
            if (url.IsNullOrWhiteSpace() == false)
            {
                var ssl = globalSettings.UseHttps ? "s" : "";
                url = "http" + ssl + "://" + url;
                var umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (using scheduledTasks/@baseUrl)", umbracoApplicationUrl);
                return(umbracoApplicationUrl);
            }

            // try the server registrar
            // which is assumed to return a url that:
            // - end with SystemDirectories.Umbraco
            // - contain a scheme
            // - end or not with a slash, it will be taken care of
            // eg "http://www.mysite.com/umbraco"
            url = serverRegistrar.GetCurrentServerUmbracoApplicationUrl();
            if (url.IsNullOrWhiteSpace() == false)
            {
                var umbracoApplicationUrl = url.TrimEnd('/');
                logger.Info(TypeOfApplicationUrlHelper, "ApplicationUrl: {UmbracoAppUrl} (IServerRegistrar)", umbracoApplicationUrl);
                return(umbracoApplicationUrl);
            }

            // else give up...
            return(null);
        }
コード例 #29
0
 public ContentTypeMapDefinition(CommonMapper commonMapper, PropertyEditorCollection propertyEditors, IDataTypeService dataTypeService, IFileService fileService,
                                 IContentTypeService contentTypeService, IMediaTypeService mediaTypeService, IMemberTypeService memberTypeService,
                                 ILogger logger, IUmbracoSettingsSection umbracoSettingsSection)
 {
     _commonMapper           = commonMapper;
     _propertyEditors        = propertyEditors;
     _dataTypeService        = dataTypeService;
     _fileService            = fileService;
     _contentTypeService     = contentTypeService;
     _mediaTypeService       = mediaTypeService;
     _memberTypeService      = memberTypeService;
     _logger                 = logger;
     _umbracoSettingsSection = umbracoSettingsSection;
 }
コード例 #30
0
 /// <summary>
 /// Initializes a new instance of the <see cref="UserGroupsApiController"/> class.
 /// </summary>
 public UserGroupsApiController(IUmbracoSettingsSection umbracoSettings,
                                IGlobalSettings globalSettings,
                                IUmbracoContextAccessor umbracoContextAccessor,
                                ISqlContext sqlContext,
                                ServiceContext services,
                                AppCaches appCaches,
                                IProfilingLogger logger,
                                IRuntimeState runtimeState,
                                UmbracoHelper umbracoHelper,
                                IUserService userService, IKeyValueService keyValueService) : base(globalSettings, umbracoContextAccessor, sqlContext, services, appCaches, logger, runtimeState, umbracoHelper)
 {
     _userService     = userService;
     _keyValueService = keyValueService;
 }
コード例 #31
0
 //ONLY for unit testing
 internal void SetUmbracoSettings(IUmbracoSettingsSection value)
 {
     _umbracoSettings = value;
 }
コード例 #32
0
        internal RepositoryFactory(bool disableAllCache, IUmbracoSettingsSection settings)
        {
            _disableAllCache = disableAllCache;
            _settings = settings;

        }
コード例 #33
0
        // umbracoSettings

        /// <summary>
        /// Sets the umbraco settings singleton to the object specified
        /// </summary>
        /// <param name="settings"></param>
        public static void ConfigureSettings(IUmbracoSettingsSection settings)
        {
            UmbracoConfig.For.SetUmbracoSettings(settings);
        }
コード例 #34
0
 /// <summary>
 /// Constructor - can be used for testing
 /// </summary>
 /// <param name="umbracoSettings"></param>
 /// <param name="baseRestSettings"></param>
 /// <param name="dashboardSettings"></param>
 public UmbracoConfig(IUmbracoSettingsSection umbracoSettings, IBaseRestSection baseRestSettings, IDashboardSection dashboardSettings)
 {
     SetUmbracoSettings(umbracoSettings);
     SetBaseRestExtensions(baseRestSettings);
     SetDashboardSettings(dashboardSettings);
 }
コード例 #35
0
 private static void SetUmbracoSettings(IUmbracoSettingsSection umbracoSettingsSection)
 {
     var type = typeof (UmbracoConfig);
     var method = type.GetMethod("SetUmbracoSettings", BindingFlags.Instance | BindingFlags.NonPublic);
     method.Invoke(UmbracoConfig.For, new object[] {umbracoSettingsSection});
 }