Esempio n. 1
0
        /// <summary>
        /// Returns relative URL for the specified tree node, using the Url Slug if the class is not in the excluded list.
        /// </summary>
        /// <param name="node">Tree node</param>
        /// <returns>The Relative Url</returns>
        protected override string GetUrlInternal(TreeNode node)
        {
            try
            {
                if (node == null)
                {
                    return(base.GetUrlInternal(node));
                }
                if (!DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(node.ClassName.ToLower()))
                {
                    var FoundSlug = CacheHelper.Cache(cs =>
                    {
                        if (cs.Cached)
                        {
                            cs.CacheDependency = CacheHelper.GetCacheDependency("DynamicRouting.UrlSlug|all");
                        }
                        return(UrlSlugInfoProvider.GetUrlSlugs()
                               .WhereEquals("UrlSlugNodeID", node.NodeID)
                               .WhereEquals("UrlSlugCultureCode", node.DocumentCulture)
                               .FirstOrDefault());
                    }, new CacheSettings(1440, "GetUrlSlugByNode", node.NodeID, node.DocumentCulture));

                    if (FoundSlug != null)
                    {
                        return(FoundSlug.UrlSlug);
                    }
                }
            } catch (Exception ex) {
                EventLogProvider.LogException("DynamicRouting", "DocumentUrlProvider_GetUrlInternal_Error", ex, additionalMessage: "for node " + (node == null || node.NodeGUID == null ? "null" : node.NodeGUID.ToString()));
            }
            return(base.GetUrlInternal(node));
        }
        private void Document_Move_After(object sender, DocumentEventArgs e)
        {
            // Update on the Node itself, this will rebuild itself and it's children
            DynamicRouteInternalHelper.CommitTransaction(true);
            try
            {
                DynamicRouteEventHelper.DocumentInsertUpdated(e.Node.NodeID);

                var PreviousParentNodeID = Thread.GetData(Thread.GetNamedDataSlot("PreviousParentIDForNode_" + e.Node.NodeID));
                if (PreviousParentNodeID != null && (int)PreviousParentNodeID != e.TargetParentNodeID)
                {
                    // If differnet node IDs, it moved to another parent, so also run Document Moved check on both new and old parent
                    DynamicRouteEventHelper.DocumentMoved((int)PreviousParentNodeID, e.TargetParentNodeID);
                }
            }
            catch (UrlSlugCollisionException ex)
            {
                LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Document After Before for Node {e.Node.NodeAliasPath}");
                e.Cancel();
            }
            catch (Exception ex)
            {
                LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Document Move After for Node {e.Node.NodeAliasPath}");
            }
        }
 private void Document_Update_After(object sender, DocumentEventArgs e)
 {
     // Update the document itself, only if there is no workflow
     try
     {
         if (e.Node.WorkflowStep == null)
         {
             DynamicRouteEventHelper.DocumentInsertUpdated(e.Node.NodeID);
         }
         else
         {
             if (e.Node.WorkflowStep.StepIsPublished && DynamicRouteInternalHelper.ErrorOnConflict())
             {
                 DynamicRouteEventHelper.DocumentInsertUpdated_CheckOnly(e.Node.NodeID);
             }
         }
     }
     catch (UrlSlugCollisionException ex)
     {
         LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Document Update After for ${e.Node.NodeAlias}.");
         e.Cancel();
     }
     catch (Exception ex)
     {
         LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Document Update After for ${e.Node.NodeAlias}.");
         e.Cancel();
     }
 }
Esempio n. 4
0
        /// <summary>
        /// Renders the View with either an ITreeNode model or the given Model Type
        /// </summary>
        /// <returns></returns>
        public ActionResult RenderViewWithModel(bool?IncludeDocumentInOutputCache = null)
        {
            if (!IncludeDocumentInOutputCache.HasValue)
            {
                IncludeDocumentInOutputCache = DynamicRouteInternalHelper.GetDefaultAddPageToCacheDependency();
            }
            var node        = mDynamicRouteHelper.GetPage(AddPageToCacheDependency: IncludeDocumentInOutputCache.Value);
            var routeConfig = mDynamicRouteHelper.GetRouteConfiguration(node);

            HttpContext.Kentico().PageBuilder().Initialize(node.DocumentID);

            // Convert type
            if (routeConfig.ModelType != null)
            {
                try {
                    return(View(routeConfig.ViewName, Convert.ChangeType(node, routeConfig.ModelType)));
                } catch (InvalidCastException ex)
                {
                    throw new InvalidCastException(ex.Message + ", this may be caused by the generated PageType class not being found in the project, or if it's located in an assembly that does not have [assembly: AssemblyDiscoverable] in it's AssemblyInfo.cs.  The found page is of type " + (node == null ? "Null" : node.GetType().FullName), ex);
                }
            }
            else
            {
                return(View(routeConfig.ViewName, node));
            }
        }
Esempio n. 5
0
        /// <summary>
        /// Build Node (and upward), and build the children and update recursively only if changes detected.
        /// </summary>
        /// <param name="UrlSlugID"></param>
        public static void UrlSlugModified(int UrlSlugID)
        {
            // Convert UrlSlugID to NodeID
            int NodeID = UrlSlugInfoProvider.GetUrlSlugInfo(UrlSlugID).UrlSlugNodeID;

            DynamicRouteInternalHelper.RebuildRoutesByNode(NodeID);
        }
Esempio n. 6
0
        protected void btnRebuildSubTree_Click(object sender, EventArgs e)
        {
            TreeNode Page = DocumentHelper.GetDocuments().Path("/" + tbxPath.Value.ToString().Trim('%').Trim('/')).FirstOrDefault();

            if (Page != null)
            {
                DynamicRouteInternalHelper.RebuildSubtreeRoutesByNode(Page.NodeID);
            }
        }
        /// <summary>
        /// Removes Application Path from Url if present and ensures starts with /
        /// </summary>
        /// <param name="Url">The Url (Relative)</param>
        /// <param name="ApplicationPath"></param>
        /// <param name="SiteName">SiteName, if provided will also remove the site's forbidden and replacement characters</param>
        /// <returns></returns>
        public static string GetUrl(string RelativeUrl, string ApplicationPath, string SiteName = "")
        {
            // Remove Application Path from Relative Url if it exists at the beginning
            if (!string.IsNullOrWhiteSpace(ApplicationPath) && ApplicationPath != "/" && RelativeUrl.ToLower().IndexOf(ApplicationPath.ToLower()) == 0)
            {
                RelativeUrl = RelativeUrl.Substring(ApplicationPath.Length);
            }

            return(DynamicRouteInternalHelper.GetCleanUrl(RelativeUrl, SiteName));
        }
Esempio n. 8
0
 public static void ExcludedClassesChanged(string SiteName = null)
 {
     if (!string.IsNullOrWhiteSpace(SiteName))
     {
         DynamicRouteInternalHelper.RebuildRoutesBySite(SiteName);
     }
     else
     {
         DynamicRouteInternalHelper.RebuildRoutes();
     }
 }
Esempio n. 9
0
 protected void btnCleanWipe_Click(object sender, EventArgs e)
 {
     // clear out
     ConnectionHelper.ExecuteNonQuery("truncate table DynamicRouting_SlugGenerationQueue", null, QueryTypeEnum.SQLQuery, true);
     ConnectionHelper.ExecuteNonQuery("truncate table DynamicRouting_UrlSlug", null, QueryTypeEnum.SQLQuery, true);
     ConnectionHelper.ExecuteNonQuery("truncate table DynamicRouting_UrlSlugStagingTaskIgnore", null, QueryTypeEnum.SQLQuery, true);
     foreach (SiteInfo Site in SiteInfoProvider.GetSites())
     {
         DynamicRouteInternalHelper.RebuildRoutesBySite(Site.SiteName);
     }
 }
Esempio n. 10
0
        public string Execute(TaskInfo task)
        {
            string Result = "";

            switch (task.TaskName.ToLower())
            {
            case "checkurlslugqueue":
                DynamicRouteInternalHelper.CheckUrlSlugGenerationQueue();
                break;
            }
            return(Result);
        }
Esempio n. 11
0
 private void Control_OnAction(string actionName, object actionArgument)
 {
     switch (actionName.ToLower())
     {
     case "run":
         int SlugQueueID = ValidationHelper.GetInteger(actionArgument, 0);
         if (SlugQueueID > 0)
         {
             DynamicRouteInternalHelper.RunSlugGenerationQueueItem(SlugQueueID);
         }
         break;
     }
 }
Esempio n. 12
0
        /// <summary>
        /// Renders the Dynamic Route View (no model)
        /// </summary>
        /// <returns></returns>
        public ActionResult RenderView(bool?IncludeDocumentInOutputCache = null)
        {
            if (!IncludeDocumentInOutputCache.HasValue)
            {
                IncludeDocumentInOutputCache = DynamicRouteInternalHelper.GetDefaultAddPageToCacheDependency();
            }
            // Get default Add Page to Output Dependency
            var node        = mDynamicRouteHelper.GetPage(AddPageToCacheDependency: IncludeDocumentInOutputCache.Value);
            var routeConfig = mDynamicRouteHelper.GetRouteConfiguration(node);

            HttpContext.Kentico().PageBuilder().Initialize(node.DocumentID);

            return(View(routeConfig.ViewName));
        }
Esempio n. 13
0
        /// <summary>
        /// Returns true if a Page is found using the Dynamic Routing
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="route"></param>
        /// <param name="parameterName"></param>
        /// <param name="values"></param>
        /// <param name="routeDirection"></param>
        /// <returns></returns>
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            string controllerName = values.ContainsKey("controller")
                    ? ValidationHelper.GetString(values["controller"], "")
                    : "";

            if (controllerName.Equals("KenticoFormWidget", StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            var page = DynamicRouteHelper.GetPage();

            return(page != null && !DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(page.ClassName.ToLower()));
        }
 private void Document_Sort_After(object sender, DocumentSortEventArgs e)
 {
     // Check parent which will see if Children need update
     try
     {
         DynamicRouteInternalHelper.RebuildRoutesByNode(e.ParentNodeId);
     }
     catch (UrlSlugCollisionException ex)
     {
         LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Document Sort Update After for Parent Node ${e.ParentNodeId}.");
         e.Cancel();
     }
     catch (Exception ex)
     {
         LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Document Sort Update After for Parent Node ${e.ParentNodeId}.");
     }
 }
Esempio n. 15
0
        /// <summary>
        /// Returns presentation URL for the specified node, using UrlSlug if the class is not in the excluded list. This is the absolute URL where live presentation of given node can be found.
        /// </summary>
        /// <param name="node">Tree node to return presentation URL for.</param>
        /// <param name="preferredDomainName">A preferred domain name that should be used as the host part of the URL. Preferred domain must be assigned to the site as a domain alias otherwise site main domain is used.</param>
        /// <returns></returns>
        protected override string GetPresentationUrlInternal(TreeNode node, string preferredDomainName = null)
        {
            try
            {
                if (node == null)
                {
                    return(base.GetPresentationUrlInternal(node, preferredDomainName));
                }

                if (!DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(node.ClassName.ToLower()))
                {
                    var FoundSlug = CacheHelper.Cache(cs =>
                    {
                        if (cs.Cached)
                        {
                            cs.CacheDependency = CacheHelper.GetCacheDependency("DynamicRouting.UrlSlug|all");
                        }
                        return(UrlSlugInfoProvider.GetUrlSlugs()
                               .WhereEquals("UrlSlugNodeID", node.NodeID)
                               .WhereEquals("UrlSlugCultureCode", node.DocumentCulture)
                               .FirstOrDefault());
                    }, new CacheSettings(1440, "GetUrlSlugByNode", node.NodeID, node.DocumentCulture));

                    if (FoundSlug != null)
                    {
                        SiteInfo site = node.Site;
                        string   url  = FoundSlug.UrlSlug;
                        if (!string.IsNullOrEmpty(site.SitePresentationURL))
                        {
                            return(URLHelper.CombinePath(url, '/', site.SitePresentationURL, null));
                        }
                        if (!string.IsNullOrEmpty(preferredDomainName))
                        {
                            return(URLHelper.GetAbsoluteUrl(url, preferredDomainName));
                        }
                        return(URLHelper.GetAbsoluteUrl(url, site.DomainName));
                    }
                }
            } catch (Exception ex)
            {
                EventLogProvider.LogException("DynamicRouting", "DocumentUrlProvider_GetPresentationUrlInternal_Error", ex, additionalMessage: "for node " + (node == null || node.NodeGUID == null ? "null" : node.NodeGUID.ToString()));
            }

            return(base.GetPresentationUrlInternal(node, preferredDomainName));
        }
        private void CultureSite_InsertDelete_After(object sender, ObjectEventArgs e)
        {
            CultureSiteInfo CultureSite = (CultureSiteInfo)e.Object;
            string          SiteName    = DynamicRouteInternalHelper.GetSite(CultureSite.SiteID).SiteName;

            try
            {
                DynamicRouteEventHelper.SiteLanguageChanged(SiteName);
            }
            catch (UrlSlugCollisionException ex)
            {
                LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Culture Site Insert/Delete for Site {SiteName}");
                e.Cancel();
            }
            catch (Exception ex)
            {
                LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Culture Site Insert/Delete for Site {SiteName}");
            }
        }
Esempio n. 17
0
        /// <summary>
        /// Returns true if a Page is found using the Dynamic Routing
        /// </summary>
        /// <param name="httpContext"></param>
        /// <param name="route"></param>
        /// <param name="parameterName"></param>
        /// <param name="values"></param>
        /// <param name="routeDirection"></param>
        /// <returns></returns>
        public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection)
        {
            // Never match on URL generation, this is called with the Url.Action and HtmlLink and shouldn't ever be used.
            if (routeDirection == RouteDirection.UrlGeneration)
            {
                return(false);
            }

            string controllerName = values.ContainsKey("controller")
                    ? ValidationHelper.GetString(values["controller"], "")
                    : "";

            if (controllerName.Equals("KenticoFormWidget", StringComparison.InvariantCultureIgnoreCase))
            {
                return(false);
            }

            var page = mDynamicRouteHelper.GetPage(AddPageToCacheDependency: false);

            return(page != null && !DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(page.ClassName.ToLower()));
        }
        public static object ParentUrl(EvaluationContext context, params object[] parameters)
        {
            // Based on the Macro Resolver which has the TreeNode Data, return the ParentUrl
            int    NodeID         = ValidationHelper.GetInteger(context.Resolver.ResolveMacros("{% NodeID %}"), 0);
            int    NodeParentID   = ValidationHelper.GetInteger(context.Resolver.ResolveMacros("{% NodeParentID %}"), 0);
            string Culture        = ValidationHelper.GetString(context.Resolver.ResolveMacros("{% DocumentCulture %}"), "en-US");
            string DefaultCulture = DynamicRouteInternalHelper.SiteContextSafe().DefaultVisitorCulture;

            return(CacheHelper.Cache(cs =>
            {
                UrlSlugInfo Slug = UrlSlugInfoProvider.GetUrlSlugs()
                                   .WhereEquals("UrlSlugNodeID", NodeParentID)
                                   .OrderBy($"case when UrlSlugCultureCode = '{Culture}' then 0 else 1 end, case when UrlSlugCultureCode = '{DefaultCulture}' then 0 else 1 end")
                                   .Columns("UrlSlug")
                                   .FirstOrDefault();
                if (cs.Cached)
                {
                    cs.CacheDependency = CacheHelper.GetCacheDependency("dynamicrouting.urlslug|all");
                }
                return Slug != null ? Slug.UrlSlug : "";
            }, new CacheSettings(1440, "GetUrlSlug", NodeParentID, Culture, DefaultCulture)));
        }
        /// <summary>
        /// Returns presentation URL for the specified node, using UrlSlug if the class is not in the excluded list. This is the absolute URL where live presentation of given node can be found.
        /// </summary>
        /// <param name="node">Tree node to return presentation URL for.</param>
        /// <param name="preferredDomainName">A preferred domain name that should be used as the host part of the URL. Preferred domain must be assigned to the site as a domain alias otherwise site main domain is used.</param>
        /// <returns></returns>
        protected override string GetPresentationUrlInternal(TreeNode node, string preferredDomainName = null)
        {
            if (!DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(node.ClassName.ToLower()))
            {
                if (node == null)
                {
                    return(null);
                }
                var FoundSlug = CacheHelper.Cache(cs =>
                {
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency("DynamicRouting.UrlSlug|all");
                    }
                    return(UrlSlugInfoProvider.GetUrlSlugs()
                           .WhereEquals("UrlSlugNodeID", node.NodeID)
                           .WhereEquals("UrlSlugCultureCode", node.DocumentCulture)
                           .FirstOrDefault());
                }, new CacheSettings(1440, "GetUrlSlugByNode", node.NodeID, node.DocumentCulture));

                if (FoundSlug != null)
                {
                    SiteInfo site = node.Site;
                    string   url  = FoundSlug.UrlSlug;
                    if (!string.IsNullOrEmpty(site.SitePresentationURL))
                    {
                        return(URLHelper.CombinePath(url, '/', site.SitePresentationURL, null));
                    }
                    if (!string.IsNullOrEmpty(preferredDomainName))
                    {
                        return(URLHelper.GetAbsoluteUrl(url, preferredDomainName));
                    }
                    return(URLHelper.GetAbsoluteUrl(url, site.DomainName));
                }
            }

            return(base.GetPresentationUrlInternal(node, preferredDomainName));
        }
        /// <summary>
        /// Returns relative URL for the specified tree node, using the Url Slug if the class is not in the excluded list.
        /// </summary>
        /// <param name="node">Tree node</param>
        /// <returns>The Relative Url</returns>
        protected override string GetUrlInternal(TreeNode node)
        {
            if (!DynamicRouteInternalHelper.UrlSlugExcludedClassNames().Contains(node.ClassName.ToLower()))
            {
                var FoundSlug = CacheHelper.Cache(cs =>
                {
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency("DynamicRouting.UrlSlug|all");
                    }
                    return(UrlSlugInfoProvider.GetUrlSlugs()
                           .WhereEquals("UrlSlugNodeID", node.NodeID)
                           .WhereEquals("UrlSlugCultureCode", node.DocumentCulture)
                           .FirstOrDefault());
                }, new CacheSettings(1440, "GetUrlSlugByNode", node.NodeID, node.DocumentCulture));

                if (FoundSlug != null)
                {
                    return(FoundSlug.UrlSlug);
                }
            }
            return(base.GetUrlInternal(node));
        }
        private void UrlSlug_Update_After_IsCustomRebuild(object sender, ObjectEventArgs e)
        {
            UrlSlugInfo      UrlSlug = (UrlSlugInfo)e.Object;
            RecursionControl Trigger = new RecursionControl("UrlSlugNoLongerCustom_" + UrlSlug.UrlSlugGuid);

            if (!Trigger.Continue)
            {
                try
                {
                    // If Continue is false, then the Before update shows this needs to be rebuilt.
                    DynamicRouteInternalHelper.RebuildRoutesByNode(UrlSlug.UrlSlugNodeID);
                }
                catch (UrlSlugCollisionException ex)
                {
                    LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Url Slug {UrlSlug.UrlSlugID}");
                    e.Cancel();
                }
                catch (Exception ex)
                {
                    LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Url Slug {UrlSlug.UrlSlugID}");
                }
            }
        }
        /// <summary>
        /// Gets the node based on the current request url and then renders the template result.
        /// </summary>
        public ActionResult Index(string TemplateControllerName = null, bool?IncludeDocumentInOutputCache = null)
        {
            if (!IncludeDocumentInOutputCache.HasValue)
            {
                IncludeDocumentInOutputCache = DynamicRouteInternalHelper.GetDefaultAddPageToCacheDependency();
            }
            ITreeNode FoundNode = mDynamicRouteHelper.GetPage(Columns: new string[] { "DocumentID" }, AddPageToCacheDependency: IncludeDocumentInOutputCache.Value);

            if (FoundNode != null)
            {
                HttpContext.Kentico().PageBuilder().Initialize(FoundNode.DocumentID);
                if (!string.IsNullOrWhiteSpace(TemplateControllerName))
                {
                    // Adjust the route data to point to the template's controller if it has one.
                    HttpContext.Request.RequestContext.RouteData.Values["Controller"] = TemplateControllerName;
                }
                return(new TemplateResult(FoundNode.DocumentID));
            }
            else
            {
                return(new HttpNotFoundResult());
            }
        }
        /// <summary>
        /// Gets the CMS Page using Dynamic Routing, returning the culture variation that either matches the given culture or the Slug's culture, or the default site culture if not found.
        /// </summary>
        /// <param name="Url">The Url (part after the domain), if empty will use the Current Request</param>
        /// <param name="Culture">The Culture, not needed if the Url contains the culture that the UrlSlug has as part of it's generation.</param>
        /// <param name="SiteName">The Site Name, defaults to current site.</param>
        /// <param name="Columns">List of columns you wish to include in the data returned.</param>
        /// <param name="AddPageToCacheDependency">If true, the found page will have it's DocumentID added to the request's Output Cache Dependency</param>
        /// <returns>The Page that matches the Url Slug, for the given or matching culture (or default culture if one isn't found).</returns>
        public ITreeNode GetPage(string Url = "", string Culture = "", string SiteName = "", IEnumerable <string> Columns = null, bool AddPageToCacheDependency = true)
        {
            // Load defaults
            SiteName = (!string.IsNullOrWhiteSpace(SiteName) ? SiteName : DynamicRouteInternalHelper.SiteContextSafe().SiteName);
            string DefaultCulture = DynamicRouteInternalHelper.SiteContextSafe().DefaultVisitorCulture;

            if (string.IsNullOrWhiteSpace(Url))
            {
                Url = EnvironmentHelper.GetUrl(HttpContext.Current.Request.Url.AbsolutePath, HttpContext.Current.Request.ApplicationPath, SiteName);
            }

            // Handle Preview, during Route Config the Preview isn't available and isn't really needed, so ignore the thrown exception
            bool PreviewEnabled = false;

            try
            {
                PreviewEnabled = HttpContext.Current.Kentico().Preview().Enabled;
            }
            catch (InvalidOperationException) { }

            GetCultureEventArgs CultureArgs = new GetCultureEventArgs()
            {
                DefaultCulture = DefaultCulture,
                SiteName       = SiteName,
                Request        = HttpContext.Current.Request,
                PreviewEnabled = PreviewEnabled,
                Culture        = Culture
            };

            using (var DynamicRoutingGetCultureTaskHandler = DynamicRoutingEvents.GetCulture.StartEvent(CultureArgs))
            {
                // If Preview is enabled, use the Kentico Preview CultureName
                if (PreviewEnabled && string.IsNullOrWhiteSpace(CultureArgs.Culture))
                {
                    try
                    {
                        CultureArgs.Culture = HttpContext.Current.Kentico().Preview().CultureName;
                    }
                    catch (Exception) { }
                }

                // If culture still not set, use the LocalizationContext.CurrentCulture
                if (string.IsNullOrWhiteSpace(CultureArgs.Culture))
                {
                    try
                    {
                        CultureArgs.Culture = LocalizationContext.CurrentCulture.CultureCode;
                    }
                    catch (Exception) { }
                }

                // If that fails then use the System.Globalization.CultureInfo
                if (string.IsNullOrWhiteSpace(CultureArgs.Culture))
                {
                    try
                    {
                        CultureArgs.Culture = System.Globalization.CultureInfo.CurrentCulture.Name;
                    }
                    catch (Exception) { }
                }

                DynamicRoutingGetCultureTaskHandler.FinishEvent();
            }

            // set the culture
            Culture = CultureArgs.Culture;

            // Convert Columns to string, must include DocumentID though at all times
            if (Columns != null && !Columns.Contains("*") && !Columns.Contains("documentid", StringComparer.InvariantCultureIgnoreCase))
            {
                var Appended = Columns.ToList();
                Appended.Add("documentid");
                Columns = Appended;
            }
            string ColumnsVal = Columns != null?string.Join(",", Columns.Distinct()) : "*";

            // Create GetPageEventArgs Event ARgs
            GetPageEventArgs Args = new GetPageEventArgs()
            {
                RelativeUrl    = Url,
                Culture        = Culture,
                DefaultCulture = DefaultCulture,
                SiteName       = SiteName,
                PreviewEnabled = PreviewEnabled,
                ColumnsVal     = ColumnsVal,
                Request        = HttpContext.Current.Request
            };

            // Run any GetPage Event hooks which allow the users to set the Found Page
            ITreeNode FoundPage = null;

            using (var DynamicRoutingGetPageTaskHandler = DynamicRoutingEvents.GetPage.StartEvent(Args))
            {
                if (Args.FoundPage == null)
                {
                    try
                    {
                        Args.FoundPage = CacheHelper.Cache <TreeNode>(cs =>
                        {
                            // Using custom query as Kentico's API was not properly handling a Join and where.
                            DataTable NodeTable = ConnectionHelper.ExecuteQuery("DynamicRouting.UrlSlug.GetDocumentsByUrlSlug", new QueryDataParameters()
                            {
                                { "@Url", Url },
                                { "@Culture", Culture },
                                { "@DefaultCulture", DefaultCulture },
                                { "@SiteName", SiteName }
                            }, topN: 1, columns: "DocumentID, ClassName").Tables[0];
                            if (NodeTable.Rows.Count > 0)
                            {
                                int DocumentID   = ValidationHelper.GetInteger(NodeTable.Rows[0]["DocumentID"], 0);
                                string ClassName = ValidationHelper.GetString(NodeTable.Rows[0]["ClassName"], "");

                                DocumentQuery Query = DocumentHelper.GetDocuments(ClassName)
                                                      .WhereEquals("DocumentID", DocumentID)
                                                      .CombineWithAnyCulture();

                                // Handle Columns
                                if (!string.IsNullOrWhiteSpace(ColumnsVal))
                                {
                                    Query.Columns(ColumnsVal);
                                }

                                // Handle Preview
                                if (PreviewEnabled)
                                {
                                    Query.LatestVersion(true)
                                    .Published(false);
                                }
                                else
                                {
                                    Query.Published();
                                }

                                TreeNode Page = Query.FirstOrDefault();

                                // Cache dependencies on the Url Slugs and also the DocumentID if available.
                                if (cs.Cached)
                                {
                                    cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] {
                                        "dynamicrouting.urlslug|all",
                                        "documentid|" + DocumentID
                                    });
                                }

                                // Return Page Data
                                return(Query.FirstOrDefault());
                            }
                            else
                            {
                                return(null);
                            }
                        }, new CacheSettings((PreviewEnabled ? 0 : 1440), "DynamicRoutine.GetPage", Url, Culture, DefaultCulture, SiteName, PreviewEnabled, ColumnsVal));
                    }
                    catch (Exception ex)
                    {
                        // Add exception so they can handle
                        DynamicRoutingGetPageTaskHandler.EventArguments.ExceptionOnLookup = ex;
                    }
                }

                // Finish event, this will trigger the After
                DynamicRoutingGetPageTaskHandler.FinishEvent();

                // Return whatever Found Page
                FoundPage = DynamicRoutingGetPageTaskHandler.EventArguments.FoundPage;
            }

            // Add documentID to the output cache dependencies, we ensured that DocumentID would be returned in the result always.
            if (FoundPage != null && AddPageToCacheDependency && HttpContext.Current != null && HttpContext.Current.Response != null)
            {
                string Key = $"documentid|{FoundPage.DocumentID}";
                CacheHelper.EnsureDummyKey(Key);
                HttpContext.Current.Response.AddCacheItemDependency(Key);
            }

            return(FoundPage);
        }
 /// <summary>
 /// Gets the Page's Url Slug based on the given NodeGuid and Culture.  If Culture not found, then will prioritize the Site's Default Culture, then Cultures by alphabetical order.
 /// </summary>
 /// <param name="NodeGuid">The Node to find the Url Slug</param>
 /// <param name="DocumentCulture">The Document Culture, if not provided will use default Site's Culture.</param>
 /// <returns>The UrlSlug (with ~ prepended) or Null if page not found.</returns>
 public string GetPageUrl(Guid NodeGuid, string DocumentCulture = null)
 {
     return(DynamicRouteInternalHelper.GetPageUrl(NodeGuid, DocumentCulture));
 }
 /// <summary>
 /// Gets the Page's Url Slug based on the given NodeID and Culture.  If Culture not found, then will prioritize the Site's Default Culture, then Cultures by alphabetical order.
 /// </summary>
 /// <param name="NodeID">The NodeID</param>
 /// <param name="DocumentCulture">The Document Culture, if not provided will use default Site's Culture.</param>
 /// <param name="SiteName">The Site Name, if not provided then will query the NodeID to find it's site.</param>
 /// <returns>The UrlSlug (with ~ prepended) or Null if page not found.</returns>
 public string GetPageUrl(int NodeID, string DocumentCulture = null, string SiteName = null)
 {
     return(DynamicRouteInternalHelper.GetPageUrl(NodeID, DocumentCulture, SiteName));
 }
 /// <summary>
 /// Gets the Page's Url Slug based on the given NodeAliasPath, Culture and SiteName.  If Culture not found, then will prioritize the Site's Default Culture, then Cultures by alphabetical order.
 /// </summary>
 /// <param name="NodeAliasPath">The Node alias path you wish to select</param>
 /// <param name="DocumentCulture">The Document Culture, if not provided will use default Site's Culture.</param>
 /// <param name="SiteName">The Site Name, if not provided then the Current Site's name is used.</param>
 /// <returns>The UrlSlug (with ~ prepended) or Null if page not found.</returns>
 public string GetPageUrl(string NodeAliasPath, string DocumentCulture = null, string SiteName = null)
 {
     return(DynamicRouteInternalHelper.GetPageUrl(NodeAliasPath, DocumentCulture, SiteName));
 }
 /// <summary>
 /// Gets the Page's Url Slug based on the given DocumentGuid and it's Culture.
 /// </summary>
 /// <param name="DocumentGuid">The Document Guid</param>
 /// <returns>The UrlSlug (with ~ prepended) or Null if page not found.</returns>
 public string GetPageUrl(Guid DocumentGuid)
 {
     return(DynamicRouteInternalHelper.GetPageUrl(DocumentGuid));
 }
 /// <summary>
 /// Gets the Page's Url Slug based on the given DocumentID and it's Culture.
 /// </summary>
 /// <param name="DocumentID">The Document ID</param>
 /// <returns></returns>
 public string GetPageUrl(int DocumentID)
 {
     return(DynamicRouteInternalHelper.GetPageUrl(DocumentID));
 }
Esempio n. 29
0
 protected void btnRebuildSite_Click(object sender, EventArgs e)
 {
     DynamicRouteInternalHelper.RebuildRoutesBySite(DynamicRouteInternalHelper.SiteContextSafe().SiteName);
 }
Esempio n. 30
0
        /// <summary>
        /// Gets the CMS Page using the given Url Slug.
        /// </summary>
        /// <param name="UrlSlug">The UrlSlug to look up (part after the domain)</param>
        /// <param name="Culture">The Culture, not needed if the Url contains the culture that the UrlSlug has as part of it's generation.</param>
        /// <param name="SiteName">The Site Name, defaults to current site.</param>
        /// <param name="Columns">List of columns you wish to include in the data returned.</param>
        /// <returns>The Page that matches the Url Slug, for the given or matching culture (or default culture if one isn't found).</returns>
        public static ITreeNode GetPage(string UrlSlug = "", string Culture = "", string SiteName = "", IEnumerable <string> Columns = null)
        {
            // Load defaults
            SiteName = (!string.IsNullOrWhiteSpace(SiteName) ? SiteName : DynamicRouteInternalHelper.SiteContextSafe().SiteName);
            string DefaultCulture = DynamicRouteInternalHelper.SiteContextSafe().DefaultVisitorCulture;

            // Handle Preview, during Route Config the Preview isn't available and isn't really needed, so ignore the thrown exception
            bool PreviewEnabled = false;

            try
            {
                PreviewEnabled = PortalContext.ViewMode != ViewModeEnum.LiveSite;
            }
            catch (InvalidOperationException) { }

            // set the culture
            if (string.IsNullOrWhiteSpace(Culture))
            {
                Culture = LocalizationContext.CurrentCulture.CultureName;
            }

            // Convert Columns to
            string ColumnsVal = Columns != null?string.Join(",", Columns.Distinct()) : "*";

            // Run any GetPage Event hooks which allow the users to set the Found Page
            ITreeNode FoundPage = null;

            try
            {
                // Get Page based on Url
                FoundPage = CacheHelper.Cache <TreeNode>(cs =>
                {
                    // Using custom query as Kentico's API was not properly handling a Join and where.
                    DataTable NodeTable = ConnectionHelper.ExecuteQuery("DynamicRouting.UrlSlug.GetDocumentsByUrlSlug", new QueryDataParameters()
                    {
                        { "@Url", UrlSlug },
                        { "@Culture", Culture },
                        { "@DefaultCulture", DefaultCulture },
                        { "@SiteName", SiteName },
                        { "@PreviewEnabled", PreviewEnabled }
                    }, topN: 1, columns: "DocumentID, ClassName").Tables[0];
                    if (NodeTable.Rows.Count > 0)
                    {
                        int DocumentID   = ValidationHelper.GetInteger(NodeTable.Rows[0]["DocumentID"], 0);
                        string ClassName = ValidationHelper.GetString(NodeTable.Rows[0]["ClassName"], "");

                        DocumentQuery Query = DocumentHelper.GetDocuments(ClassName)
                                              .WhereEquals("DocumentID", DocumentID);

                        // Handle Columns
                        if (!string.IsNullOrWhiteSpace(ColumnsVal))
                        {
                            Query.Columns(ColumnsVal);
                        }

                        // Handle Preview
                        if (PreviewEnabled)
                        {
                            Query.LatestVersion(true)
                            .Published(false);
                        }
                        else
                        {
                            Query.PublishedVersion(true);
                        }

                        TreeNode Page = Query.FirstOrDefault();

                        // Cache dependencies on the Url Slugs and also the DocumentID if available.
                        if (cs.Cached)
                        {
                            if (Page != null)
                            {
                                cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] {
                                    "dynamicrouting.urlslug|all",
                                    "dynamicrouting.versionhistoryurlslug|all",
                                    "dynamicrouting.versionhistoryurlslug|bydocumentid|" + Page.DocumentID,
                                    "documentid|" + Page.DocumentID,
                                });
                            }
                            else
                            {
                                cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "dynamicrouting.urlslug|all", "dynamicrouting.versionhistoryurlslug|all" });
                            }
                        }

                        // Return Page Data
                        return(Query.FirstOrDefault());
                    }
                    else
                    {
                        return(null);
                    }
                }, new CacheSettings(1440, "DynamicRoutine.GetPageMother", UrlSlug, Culture, DefaultCulture, SiteName, PreviewEnabled, ColumnsVal));
            }
            catch (Exception ex)
            {
            }
            return(FoundPage);
        }