コード例 #1
0
        /// <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);
        }
コード例 #2
0
        /// <summary>
        /// Gets the Current Culture, needed for User Culture Permissions
        /// </summary>
        /// <returns></returns>
        private string GetCulture()
        {
            string SiteName       = SiteContextSafe().SiteName;
            string DefaultCulture = SiteContextSafe().DefaultVisitorCulture;
            string Culture        = "";

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

            using (var AuthorizeGetCultureTaskHandler = AuthorizeEvents.GetCulture.StartEvent(CultureArgs))
            {
                // If Preview is enabled, use the Kentico Preview CultureName
                if (PreviewEnabled)
                {
                    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.CultureName;
                    }
                    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) { }
                }

                AuthorizeGetCultureTaskHandler.FinishEvent();
                // set the culture
                Culture = CultureArgs.Culture;
            }
            return(Culture);
        }
 public Task <string> GetCustomCultureAsync(GetCultureEventArgs cultureArgs, AuthorizationEventType eventType)
 {
     return(Task.FromResult <string>(null));
 }
コード例 #4
0
        /// <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>
        /// <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 Url = "", string Culture = "", string SiteName = "", IEnumerable <string> Columns = null)
        {
            // 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 = PortalContext.ViewMode != ViewModeEnum.LiveSite;
            }
            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 culture not set, use the LocalizationContext.CurrentCulture
                if (string.IsNullOrWhiteSpace(CultureArgs.Culture))
                {
                    try
                    {
                        CultureArgs.Culture = LocalizationContext.CurrentCulture.CultureName;
                    }
                    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 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
                    {
                        // Get Page based on Url
                        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 },
                                { "@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.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;
            }
            return(FoundPage);
        }
コード例 #5
0
        /// <summary>
        /// Gets the Current Culture, needed for User Culture Permissions
        /// </summary>
        /// <returns></returns>
        private async Task <string> GetCultureAsync()
        {
            string siteName       = SiteContextSafe().SiteName;
            string defaultCulture = SiteContextSafe().DefaultVisitorCulture;
            string culture        = "";

            // 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 = _httpContextAccessor.HttpContext.Kentico().Preview().Enabled;
            }
            catch (InvalidOperationException) { }

            GetCultureEventArgs cultureArgs = new GetCultureEventArgs()
            {
                DefaultCulture = defaultCulture,
                SiteName       = siteName,
                Request        = _httpContextAccessor.HttpContext.Request,
                PreviewEnabled = previewEnabled
            };

            string customCulture = await _authorizationContextCustomizer.GetCustomCultureAsync(cultureArgs, AuthorizationEventType.Before);

            if (!string.IsNullOrWhiteSpace(customCulture))
            {
                return(customCulture);
            }

            // If Preview is enabled, use the Kentico Preview CultureName
            if (previewEnabled)
            {
                try
                {
                    culture = _httpContextAccessor.HttpContext.Kentico().Preview().CultureName;
                }
                catch (Exception) { }
            }

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

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

            cultureArgs.Culture = culture;

            string customCultureAfter = await _authorizationContextCustomizer.GetCustomCultureAsync(cultureArgs, AuthorizationEventType.After);

            if (!string.IsNullOrWhiteSpace(customCultureAfter))
            {
                culture = customCultureAfter;
            }

            return(culture);
        }