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);
            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;
            }

            // 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;
        }
Exemplo n.º 2
0
        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);
        }
		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;
		}
        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["CachedNewsNodes"];
                    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[] { '/' }, System.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("Newsitem").Where(x => x.UrlName == parts.Last()).FirstOrDefault();
                        if(newsItem != null)
                        {
                            //Get the news item template.
                            var template = 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("CachedNewsNodes",
                                          cachedNewsNodes,
                                          null,
                                          DateTime.Now.AddDays(1),
                                          System.Web.Caching.Cache.NoSlidingExpiration,
                                          System.Web.Caching.CacheItemPriority.High,
                                          null);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Umbraco.LogException<NewsContentFinder>(ex);
            }

            return contentRequest.PublishedContent != null;
        }