private void Process(PublishedContentRequest request) { //Are we rendering a published content (sanity check)? if (request?.PublishedContent == null) { return; } //Are there any experiments running var experiments = new GetApplicableCachedExperiments { ContentId = request.PublishedContent.Id }.ExecuteAsync().Result; //variations of the same content will be applied in the order the experiments were created, //if they override the same property variation of the newest experiment wins var variationsToApply = new List <IPublishedContentVariation>(); foreach (var experiment in experiments) { var experimentId = experiment.GoogleExperiment.Id; //Has the user been previously exposed to this experiment? var assignedVariationId = GetAssignedVariation(request, experiment.Id); if (assignedVariationId != null) { var variation = GetVariation(request, experiment, assignedVariationId.Value); if (variation != null) { variationsToApply.Add(new PublishedContentVariation(variation, experimentId, assignedVariationId.Value)); } } //Should the user be included in the experiment? else if (ShouldVisitorParticipate(experiment)) { //Choose a variation for the user var variationId = SelectVariation(experiment); var variation = GetVariation(request, experiment, variationId); if (variation != null) { variationsToApply.Add(new PublishedContentVariation(variation, experimentId, variationId)); } } else { //should we assign -1 as variation (remember we showed nothing? - maybe in case we decide to exclude if say only 60% traffic is covered) } } //the visitor is excluded or we didn't find the content needed for variations, just show original if (variationsToApply.Count <= 0) { return; } var variedContent = new VariedContent(request.PublishedContent, variationsToApply.ToArray()); request.PublishedContent = variedContent; request.TrySetTemplate(variedContent.GetTemplateAlias()); }
public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest != null) { var url = contentRequest.Uri.AbsoluteUri; var path = contentRequest.Uri.GetAbsolutePathDecoded(); var urlParts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); if (urlParts.Length == 2) { var rootNodes = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot(); var courseNode = rootNodes .DescendantsOrSelf(nameof(Course)) .FirstOrDefault(x => x.UrlName == urlParts.Last()); if (courseNode != null) { if (contentRequest.RoutingContext.UmbracoContext.HttpContext.User.Identity.IsAuthenticated) { var username = contentRequest.RoutingContext.UmbracoContext.HttpContext.User.Identity.Name; } contentRequest.PublishedContent = courseNode; var templateSet = contentRequest.TrySetTemplate("StudentCoursePage"); } } return(contentRequest.PublishedContent != null); } return(false); }
public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest == null) { return(false); } var url = contentRequest.Uri.GetAbsolutePathDecoded(); var urlParts = url.ToDelimitedList("/"); if (urlParts.Count > 1) { var forumName = urlParts[urlParts.Count - 2]; var rootNodes = contentRequest.RoutingContext.UmbracoContext .ContentCache.GetAtRoot(); // make this a cache thing (for speed!) var forums = rootNodes.DescendantsOrSelf("forum"); var forumContent = forums.Where(x => x.UrlName.InvariantEquals(forumName)) .FirstOrDefault(); if (forumContent != null) { var postParts = urlParts.Last().ToDelimitedList("-"); if (postParts.Count > 1) { var postId = postParts.First(); if (int.TryParse(postId, out int id)) { var service = UserContentContext.Current.Instances[Forums.Instance] .Service; var post = service.Get(id); if (post == null) { return(false); } var context = contentRequest.RoutingContext.UmbracoContext.HttpContext.Items["postKey"] = post.Key; } } contentRequest.PublishedContent = forumContent; contentRequest.TrySetTemplate("forumThread"); } } return(contentRequest.PublishedContent != null); }
public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest == null) { return(false); } var url = contentRequest.Uri.AbsolutePath.TrimEnd(new char[] { '/', ' ' }); LogHelper.Info <AuthContentFinder>("url: {0}", () => url); switch (url.ToLower()) { case AuthUrls.Login: contentRequest.PublishedContent = GetHomepage(contentRequest.RoutingContext); contentRequest.TrySetTemplate(TemplateAliases.Login); break; case AuthUrls.Register: contentRequest.PublishedContent = GetHomepage(contentRequest.RoutingContext); contentRequest.TrySetTemplate(TemplateAliases.Register); break; case AuthUrls.Reset: contentRequest.PublishedContent = GetHomepage(contentRequest.RoutingContext); contentRequest.TrySetTemplate(TemplateAliases.Reset); break; case AuthUrls.Verify: contentRequest.PublishedContent = GetHomepage(contentRequest.RoutingContext); contentRequest.TrySetTemplate(TemplateAliases.Verify); break; } return(contentRequest.PublishedContent != null); }
public void GetUmbracoRouteValues_Find_Custom_Controller() { var router = new UmbracoRouter(Mock.Of <IRouter>()); var httpCtxAccessor = new Mock <IHttpContextAccessor>(); var httpContext = new Mock <HttpContext>(); httpContext.Setup(context => context.Request).Returns(Mock.Of <HttpRequest>()); httpCtxAccessor.Setup(accessor => accessor.HttpContext).Returns(httpContext.Object); var umbCtx = new UmbracoContext(httpCtxAccessor.Object); var urlProvider = new UrlProvider(umbCtx, Enumerable.Empty <IUrlProvider>()); var routingCtx = new RoutingContext(Enumerable.Empty <IContentFinder>(), Mock.Of <ILastChanceContentFinder>(), urlProvider); var templateService = new Mock <ITemplateService>(); templateService.Setup(service => service.GetTemplate("Hello")).Returns(Mock.Of <ITemplate>(template => template.Alias == "Hello")); var pcr = new PublishedContentRequest(routingCtx, templateService.Object, Mock.Of <ILoggerFactory>(), httpCtxAccessor.Object) { PublishedContent = new PublishedContent() { ContentType = "Custom" } }; pcr.TrySetTemplate("Hello"); umbCtx.Initialize(pcr); var actionDescriptors = new Mock <IActionDescriptorsCollectionProvider>(); actionDescriptors.Setup(provider => provider.ActionDescriptors).Returns(new ActionDescriptorsCollection( new List <ActionDescriptor>() { new ControllerActionDescriptor() { Name = "Hello", ControllerName = "Custom", ControllerTypeInfo = typeof(UmbracoController).GetTypeInfo() } }, 0)); var result = router.GetUmbracoRouteValues(umbCtx, new UmbracoControllerTypeCollection(actionDescriptors.Object)); Assert.Equal("Custom", result.ControllerName); Assert.Equal("Hello", result.ActionName); }
private void SetTemplate(PublishedContentRequest contentRequest, string template, bool forceTemplate) { if (contentRequest.PublishedContent == null) { return; } if (contentRequest.TemplateAlias == null || string.IsNullOrWhiteSpace(contentRequest.TemplateAlias) || forceTemplate) { if (!string.IsNullOrWhiteSpace(template)) { var isValidTemplate = System.IO.File.Exists(HttpContext.Current.Server.MapPath(template)); if (!isValidTemplate) { return; } // Check whether it as an alias or a path if (!template.Contains("/")) { contentRequest.TrySetTemplate(template); } else { contentRequest.SetTemplate(new Template(template, template, Guid.NewGuid().ToString().Replace("-", string.Empty))); } var requestUrl = contentRequest.Uri.OriginalString; // Add the template to the cache in order to retrieve it from the Render MVC controller var cacheId = string.Format(Constants.Cache.TemplateCacheIdPattern, requestUrl.ToLower().Trim()); string cacheDependencyId = GetNodeCacheDependency(contentRequest.PublishedContent.Id); Helpers.CacheHelper.GetExistingOrAddToCacheSlidingExpiration(cacheId, 300, CacheItemPriority.NotRemovable, () => { return(template); }, new[] { Constants.Config.ConfigFilePhysicalPath }, new[] { cacheDependencyId }); } } }
public bool TryFindContent(PublishedContentRequest contentRequest) { try { if (contentRequest != null) { //Get the current url. var url = contentRequest.Uri.AbsoluteUri; //Get the news nodes that are already cached. var cachedNewsNodes = (Dictionary <string, ContentFinderItem>)HttpContext.Current.Cache[CacheKeys.BlogPostNodes]; if (cachedNewsNodes != null) { //Check if the current url already has a news item. if (cachedNewsNodes.ContainsKey(url)) { //If the current url already has a node use that so the rest of the code doesn't need to run again. var contentFinderItem = cachedNewsNodes[url]; contentRequest.PublishedContent = contentFinderItem.Content; contentRequest.TrySetTemplate(contentFinderItem.Template); return(true); } } //Split the url segments. var path = contentRequest.Uri.GetAbsolutePathDecoded(); var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); //The news items should contain 3 segments. if (parts.Length == 3) { //Get all the root nodes. var rootNodes = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot(); //Find the news item that matches the last segment in the url. var newsItem = rootNodes.DescendantsOrSelf(DocumentTypes.BlogPostAlias).FirstOrDefault(x => x.UrlName == parts.Last()); if (newsItem != null) { //Get the news item template. var template = ApplicationContext.Current.Services.FileService.GetTemplate(newsItem.TemplateId); if (template != null) { //Store the fields in the ContentFinderItem-object. var contentFinderItem = new ContentFinderItem() { Template = template.Alias, Content = newsItem }; //If the correct node is found display that node. contentRequest.PublishedContent = contentFinderItem.Content; contentRequest.TrySetTemplate(contentFinderItem.Template); if (cachedNewsNodes != null) { //Add the new ContentFinderItem-object to the cache. cachedNewsNodes.Add(url, contentFinderItem); } else { //Create a new dictionary and store it in the cache. cachedNewsNodes = new Dictionary <string, ContentFinderItem>() { { url, contentFinderItem } }; HttpContext.Current.Cache.Add(CacheKeys.BlogPostNodes, cachedNewsNodes, null, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.High, null); } } } } } } catch (Exception ex) { LogHelper.Error <BlogPostsContentFinder>("Failed to find content for Blog Posts", ex); } return(contentRequest?.PublishedContent != null); }
public override bool TryFindContent(PublishedContentRequest contentRequest) { // eg / or /path/to/whatever var url = contentRequest.Uri.GetAbsolutePathDecoded(); var mdRoot = "/" + MarkdownLogic.BaseUrl; if (url.StartsWith("/projects/umbraco-pro/contour/documentation")) { mdRoot = "/projects"; } // ensure it's a md url if (url.StartsWith(mdRoot) == false) { return(false); // not for us } // find the root content var node = FindContent(contentRequest, mdRoot); if (node == null) { return(false); } // kill those old urls foreach (var s in new [] { "master", "v480" }) { if (url.StartsWith(mdRoot + "/" + s)) { url = url.Replace(mdRoot + "/" + s, mdRoot); contentRequest.SetRedirectPermanent(url); return(true); } } // find the md file var mdFilepath = FindMarkdownFile(url); //return the broken link doc page var is404 = false; if (mdFilepath == null) { mdFilepath = FindMarkdownFile("/documentation/broken-link"); is404 = true; } if (mdFilepath == null) { // clear the published content (that was set by FindContent) to cause a 404, and in // both case return 'true' because there's no point other finders try to handle the request contentRequest.PublishedContent = null; return(true); } if (is404) { contentRequest.SetIs404(); } // set the context vars var httpContext = contentRequest.RoutingContext.UmbracoContext.HttpContext; httpContext.Items[MarkdownLogic.MarkdownPathKey] = mdFilepath; httpContext.Items["topicTitle"] = string.Join(" - ", httpContext.Request.RawUrl .Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries) .Skip(1) .Reverse()); // override the template const string altTemplate = "DocumentationSubpage"; var templateIsSet = contentRequest.TrySetTemplate(altTemplate); //httpContext.Trace.Write("Markdown Files Handler", // string.Format("Template changed to: '{0}' is {1}", altTemplate, templateIsSet)); // be happy return(true); }
public bool TryFindContent(PublishedContentRequest contentRequest) { if (contentRequest == null) { return(false); } var url = contentRequest.Uri.AbsolutePath; var appCache = ApplicationContext.Current.ApplicationCache.RuntimeCache; var cacheKey = $"ablog_{url}"; var postInfo = appCache.GetCacheItem <AubBlogContentFinderItem>(cacheKey); if (postInfo != null) { var postContent = contentRequest.RoutingContext.UmbracoContext .ContentCache.GetById(postInfo.ContentId); contentRequest.PublishedContent = postContent; contentRequest.TrySetTemplate(postInfo.TemplateAlias); return(true); } var rootNodes = contentRequest.RoutingContext.UmbracoContext .ContentCache.GetAtRoot(); var path = contentRequest.Uri.GetAbsolutePathDecoded(); var parts = path.ToDelimitedList("/"); // get the content by the post-name or the id. var content = rootNodes.DescendantsOrSelf(Blog.Presets.DocTypes.BlogPost) .Where(x => x.UrlName.InvariantEquals(parts.Last()) || x.Id.ToString() == parts.Last()) .FirstOrDefault(); if (content != null) { var finderItem = new AubBlogContentFinderItem { ContentId = content.Id, TemplateAlias = content.GetTemplateAlias() }; appCache.InsertCacheItem <AubBlogContentFinderItem>( cacheKey, () => finderItem, priority: CacheItemPriority.Default); contentRequest.PublishedContent = content; contentRequest.TrySetTemplate(finderItem.TemplateAlias); } else { // the slower way - we need to work out by blog root what the post // is (using the post settings) var blogRoot = rootNodes.DescendantsOrSelf(Blog.Presets.DocTypes.BlogPosts) .Where(x => parts.InvariantContains(x.UrlName)) .FirstOrDefault(); if (blogRoot != null) { var blogPlace = parts.IndexOf(blogRoot.UrlName); var blogUrl = $"/{string.Join("/", parts.Skip(blogPlace + 1))}/"; // goes and gets the special (category or tag) route. var item = GetSpecialRoute(blogRoot, blogUrl); if (item != null) { appCache.InsertCacheItem <AubBlogContentFinderItem>( cacheKey, () => item, priority: CacheItemPriority.Default); contentRequest.PublishedContent = blogRoot; contentRequest.TrySetTemplate(item.TemplateAlias); } } } return(contentRequest.PublishedContent != null); }
private void Process(PublishedContentRequest request) { //Are we rendering a published content (sanity check)? if (request?.PublishedContent == null) { return; } //Are there any experiments running var experiments = new GetApplicableCachedExperiments { ContentId = request.PublishedContent.Id }.ExecuteAsync().Result; //variations of the same content will be applied in the order the experiments were created, //if they override the same property variation of the newest experiment wins var variationsToApply = new List <IPublishedContentVariation>(); foreach (var experiment in experiments) { var eventArgs = new BeforeExperimentExecutedArgs(experiment, request.RoutingContext?.UmbracoContext?.HttpContext); OnBeforeExperimentExecuted(eventArgs); if (eventArgs.SkipExperiment) //allow the developer to opt out { continue; } var experimentId = experiment.GoogleExperiment.Id; //Has the user been previously exposed to this experiment? var assignedVariationId = GetAssignedVariation(request, experiment.Id); if (assignedVariationId != null) { if (ShouldApplyVariation(experiment, assignedVariationId.Value)) { var variationContent = GetVariationContent(experiment, assignedVariationId.Value); variationsToApply.Add(new PublishedContentVariation(variationContent, experimentId, assignedVariationId.Value)); } } //Should the user be included in the experiment? else if (ShouldVisitorParticipate(experiment)) { //Choose a variation for the user var variationId = SelectVariation(experiment); AssignVariationToUser(request, experiment.Id, variationId); if (ShouldApplyVariation(experiment, variationId)) { var variationContent = GetVariationContent(experiment, variationId); variationsToApply.Add(new PublishedContentVariation(variationContent, experimentId, variationId)); } } else { AssignVariationToUser(request, experiment.Id, -1); } } //the visitor is excluded or we didn't find the content needed for variations, just show original if (variationsToApply.Count <= 0) { return; } var variedContent = new VariedContent(request.PublishedContent, variationsToApply.ToArray()); request.PublishedContent = variedContent; request.SetIsInitialPublishedContent(); //Reset the published content now we have set the initial content request.PublishedContent = PublishedContentModelFactoryResolver.Current.Factory.CreateModel(variedContent); request.TrySetTemplate(variedContent.GetTemplateAlias()); }
public bool TryFindContent(PublishedContentRequest contentRequest) { var stores = StoreHelper.GetAllStores(); if (!stores.Any()) { return(false); } var uwebshopRequest = UwebshopRequest.Current; var content = uwebshopRequest.Product ?? uwebshopRequest.Category ?? uwebshopRequest.PaymentProvider ?? // in case ResolveUwebshopEntityUrl was already called from the module IO.Container.Resolve <IUrlRewritingService>().ResolveUwebshopEntityUrl().Entity; if (content is PaymentProvider) { var paymentProvider = content as PaymentProvider; Log.Instance.LogDebug("UmbracoDefaultAfterRequestInit paymentProvider: " + paymentProvider.Name); new PaymentRequestHandler().HandleuWebshopPaymentRequest(paymentProvider); var publishedContent = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(paymentProvider.Id); if (publishedContent == null) { return(false); } contentRequest.PublishedContent = publishedContent; SetRequestCulture(contentRequest); return(true); } if (content is Category) { var categoryFromUrl = content as Category; if (categoryFromUrl.Disabled) { return(false); } if (Access.HasAccess(categoryFromUrl.Id, categoryFromUrl.Path, Membership.GetUser())) { var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id); if (doc != null) { contentRequest.PublishedContent = doc; var altTemplate = HttpContext.Current.Request["altTemplate"]; contentRequest.TrySetTemplate(altTemplate); SetRequestCulture(contentRequest); return(true); } } else { if (HttpContext.Current.User.Identity.IsAuthenticated) { contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(categoryFromUrl.Path))); } contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(categoryFromUrl.Path))); return(true); } } else if (content is Product) { var productFromUrl = content as Product; if (productFromUrl.Disabled) { return(false); } if (Access.HasAccess(productFromUrl.Id, productFromUrl.Path, Membership.GetUser())) { var doc = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetById(content.Id); if (doc != null) { contentRequest.PublishedContent = doc; var altTemplate = HttpContext.Current.Request["altTemplate"]; contentRequest.TrySetTemplate(altTemplate); SetRequestCulture(contentRequest); return(true); } } else { if (HttpContext.Current.User.Identity.IsAuthenticated) { contentRequest.SetRedirect(library.NiceUrl(Access.GetErrorPage(productFromUrl.Path))); } contentRequest.SetRedirect(library.NiceUrl(Access.GetLoginPage(productFromUrl.Path))); return(true); } } return(false); }
/// <inheritdoc/> public virtual bool TryFindContent(PublishedContentRequest contentRequest) { IPublishedContent content = null; if (contentRequest.RoutingContext.UmbracoContext == null) { LogHelper.Error <DocumentTypeUrlNodeRouteHandler>( "umbraco context is null! for url: " + contentRequest.Uri, new ArgumentNullException(nameof(contentRequest.RoutingContext.UmbracoContext))); return(false); } try { if (contentRequest.RoutingContext.UmbracoContext.HttpContext.Request.Url != null) { var path = contentRequest.RoutingContext.UmbracoContext.HttpContext.Request.Url .GetAbsolutePathDecoded(); var parts = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries); var tmpUrl = "/"; // Lets try to get the content by using parts of the url until we find it. for (var index = 0; index < parts.Length; index++) { tmpUrl += parts[index] + "/"; try { // Try to resolve it as a route. content = UmbracoContext.Current.ContentCache.GetByRoute(tmpUrl); if (content != null) { break; } } catch (Exception ex) { // ignored } } if (content == null) { var rootNodes = contentRequest.RoutingContext.UmbracoContext.ContentCache.GetAtRoot(); content = rootNodes.DescendantsOrSelf(DocumentTypeAlias) .FirstOrDefault(x => x.UrlName == parts.First()); } } } catch (Exception ex) { // ignored } if (content != null && content.DocumentTypeAlias.Equals(DocumentTypeAlias)) { var template = ApplicationContext.Current.Services.FileService.GetTemplate(content.TemplateId); if (template != null) { contentRequest.PublishedContent = content; contentRequest.TrySetTemplate(template.Alias); return(true); } } return(false); }