/// <summary> /// Gets the NodeID from NodeGuid /// </summary> /// <param name="nodeGuid"></param> /// <returns>The NodeID</returns> private static int?GetNodeID(Guid nodeGuid) { return(CacheHelper.Cache(cs => { TreeNode node = DocumentHelper.GetDocuments() .WhereEquals("NodeGuid", nodeGuid) .CombineWithAnyCulture() .CombineWithDefaultCulture() .Columns("NodeID") .FirstOrDefault(); if (node != null) { if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency($"nodeid|{node.NodeID}"); } } return node?.NodeID; }, new CacheSettings(1440, "RelExtendedGetNodeID", nodeGuid))); }
/// <summary> /// Gets the current Tree Node based on the NodeID parameter passed to UI elements /// </summary> /// <returns>The Tree Node that the current page belongs to</returns> private static TreeNode CurrentNode() { int NodeID = QueryHelper.GetInteger("NodeID", -1); string Culture = QueryHelper.GetString("culture", "en-US"); if (NodeID > 0) { return(CacheHelper.Cache <TreeNode>(cs => { TreeNode currentNode = new DocumentQuery().WhereEquals("NodeID", NodeID).Culture(Culture).CombineWithDefaultCulture(true).FirstOrDefault(); if (currentNode != null && cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("nodeid|" + NodeID); } return currentNode; }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "RelationshipMacro", "CurrentNode", NodeID, Culture))); } else { return(null); } }
public static object GetRenewalStatus(EvaluationContext context, params object[] parameters) { // make sure current user is logged in if (!AuthenticationHelper.IsAuthenticated()) { return("join"); } // by default use current logged in user UserInfo user = MembershipContext.AuthenticatedUser; // if username is supplied, try to look up user with username if (parameters.Length == 1) { user = UserInfoProvider.GetUserInfo(parameters[0].ToString()); } // If user is null, then exit if (user == null) { return("join"); } // some users had a | at the end of their customer ID, remove that and everything after string customerID = user.GetStringValue("PersonifyIdentifier", ""); if (String.IsNullOrEmpty(customerID)) { return("join"); } else if (customerID.Contains("|")) { customerID = customerID.Substring(0, (customerID.IndexOf('|'))); } String status = CacheHelper.Cache(cs => LookupRenewalStatus(cs, customerID), new CacheSettings(10, "renewalstatus|" + customerID)); return(status); }
/// <summary> /// Check if any pages of children of this node's parent have a class with Url Pattern contains NodeOrder, if so then the siblings of a changed node need to have its siblings built (start with parent) /// </summary> /// <returns>If Siblings need to be checked for URL slug changes</returns> public static bool CheckSiblings(string NodeAliasPath = "", string SiteName = "") { // Get any classes that have {% NodeOrder %} List <int> ClassIDs = CacheHelper.Cache <List <int> >(cs => { if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.class|all"); } return(DataClassInfoProvider.GetClasses() .WhereLike("ClassURLPattern", "%NodeOrder%") .Select(x => x.ClassID).ToList()); }, new CacheSettings(1440, "ClassesForSiblingCheck")); // If no NodeAliasPath given, then return if there are any Classes that have NodeOrder if (string.IsNullOrWhiteSpace(NodeAliasPath)) { return(ClassIDs.Count > 0); } else { SiteName = GetSiteName(SiteName); var Document = DocumentHelper.GetDocument(new NodeSelectionParameters() { SelectSingleNode = true, AliasPath = NodeAliasPath, SiteName = SiteName }, new TreeProvider()); // return if any siblings have a class NodeOrder exist return(DocumentHelper.GetDocuments() .WhereEquals("NodeParentID", Document.NodeParentID) .WhereNotEquals("NodeID", Document.NodeID) .WhereIn("NodeClassID", ClassIDs) .Columns("NodeID") .Count > 0); } }
/// <summary> /// Loads total number of pages waiting for the approval. /// </summary> /// <param name="liveTileContext">Context of the live tile. Contains information about the user and the site the model is requested for</param> /// <exception cref="ArgumentNullException"><paramref name="liveTileContext"/> is null</exception> /// <returns>Live tile model</returns> public LiveTileModel GetModel(LiveTileContext liveTileContext) { if (liveTileContext == null) { throw new ArgumentNullException("liveTileContext"); } return(CacheHelper.Cache(() => { int waitingPagesCount = GetNumberOfPendingPages(liveTileContext.SiteInfo, (UserInfo)liveTileContext.UserInfo); if (waitingPagesCount == 0) { return null; } return new LiveTileModel { Value = waitingPagesCount, Description = ResHelper.GetString("pendingpages.livetiledescription") }; }, new CacheSettings(2, "PendingPagesLiveModelProvider", liveTileContext.SiteInfo.SiteID, liveTileContext.UserInfo.UserID))); }
/// <summary> /// Loads total number of submissions waiting for import. /// </summary> /// <param name="liveTileContext">Context of the live tile. Contains information about the user and the site the model is requested for</param> /// <exception cref="ArgumentNullException"><paramref name="liveTileContext"/> is null</exception> /// <returns>Live tile model</returns> public LiveTileModel GetModel(LiveTileContext liveTileContext) { if (liveTileContext == null) { throw new ArgumentNullException("liveTileContext"); } return(CacheHelper.Cache(() => { int waitingSubmissionsCount = GetNumberOfWaitingSubmissions(liveTileContext.SiteInfo.SiteID); if (waitingSubmissionsCount == 0) { return null; } return new LiveTileModel { Value = waitingSubmissionsCount, Description = ResHelper.GetString("translations.livetiledescription") }; }, new CacheSettings(2, "TranslationsLiveModelProvider", liveTileContext.SiteInfo.SiteID))); }
/// <summary> /// Check if any child Url Pattern contains NodeLevel, NodeParentID, NodeAliasPath, DocumentNamePath if so then must check all children as there could be one of these page types down the tree that is modified. /// </summary> /// <returns>If Descendents need to be checked for URL slug changes</returns> public static bool CheckDescendents(string NodeAliasPath = "", string SiteName = "") { // Get any classes that have {% NodeOrder %} List <int> ClassIDs = CacheHelper.Cache <List <int> >(cs => { if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.class|all"); } return(DataClassInfoProvider.GetClasses() .WhereLike("ClassURLPattern", "%NodeLevel%") .Or() .WhereLike("ClassURLPattern", "%NodeParentID%") .Or() .WhereLike("ClassURLPattern", "%NodeAliasPath%") .Or() .WhereLike("ClassURLPattern", "%DocumentNamePath%") .Select(x => x.ClassID).ToList()); }, new CacheSettings(1440, "ClassesForDescendentCheck")); // If no NodeAliasPath given, then return if there are any Classes that have NodeOrder if (string.IsNullOrWhiteSpace(NodeAliasPath)) { return(ClassIDs.Count > 0); } else { SiteName = GetSiteName(SiteName); // return if any siblings have a class NodeOrder exist return(DocumentHelper.GetDocuments() .Path(NodeAliasPath, PathTypeEnum.Children) .OnSite(new SiteInfoIdentifier(SiteName)) .CombineWithAnyCulture() .WhereIn("NodeClassID", ClassIDs) .Columns("NodeID") .Count > 0); } }
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)); }
/// <summary> /// Loads number of visits in the last week. /// </summary> /// <param name="liveTileContext">Context of the live tile. Contains information about the user and the site the model is requested for</param> /// <exception cref="ArgumentNullException"><paramref name="liveTileContext"/> is null</exception> /// <returns>Live tile model</returns> public LiveTileModel GetModel(LiveTileContext liveTileContext) { if (liveTileContext == null) { throw new ArgumentNullException("liveTileContext"); } return(CacheHelper.Cache(() => { if (!AnalyticsHelper.AnalyticsEnabled(liveTileContext.SiteInfo.SiteName)) { return null; } var weekVisitsCount = GetWeekVisitsCount(liveTileContext.SiteInfo.SiteID); return new LiveTileModel { Value = weekVisitsCount, Description = ResHelper.GetString("webanalytics.livetiledescription") }; }, new CacheSettings(2, "WebAnalyticsLiveTileModelProvider", liveTileContext.SiteInfo.SiteID))); }
/// <summary> /// Returns an enumerable collection of articles ordered by the date of publication. The most recent articles come first. /// </summary> /// <param name="count">The number of articles to return. Use 0 as value to return all records.</param> /// <returns>An enumerable collection that contains the specified number of articles ordered by the date of publication.</returns> //public IEnumerable<Article> GetArticles(int count = 0) //{ // return ArticleProvider.GetArticles() // .LatestVersion(mLatestVersionEnabled) // .Published(!mLatestVersionEnabled) // .OnSite(SiteContext.CurrentSiteName) // .Culture(mCultureName) // .CombineWithDefaultCulture() // .TopN(count) // .OrderByDescending("DocumentPublishFrom") // .ToList(); //} //public IEnumerable<Article> GetArticles(int count = 0) //{ // string culture = "en-us"; // //string siteName = SiteContext.CurrentSiteName; // Func<IEnumerable<Article>> dataLoadMethod = () => ArticleProvider.GetArticles() // .OnSite("DancingGoatMvc") // .Culture(culture) // .TopN(count) // .OrderByDescending("DocumentPublishFrom") // .TypedResult; // Ensures that the result of the query is saved, not the query itself // var cacheSettings = new CacheSettings(10, "myapp|data|articles", "DancingGoatMvc", culture, count) // { // GetCacheDependency = () => // { // // Creates caches dependencies. This example makes the cache clear data when any article is modified, deleted, or created in Kentico. // string dependencyCacheKey = String.Format("nodes|{0}|{1}|all", "DancingGoatMvc", Article.CLASS_NAME.ToLowerInvariant()); // return CacheHelper.GetCacheDependency(dependencyCacheKey); // } // }; // return CacheHelper.Cache(dataLoadMethod, cacheSettings); //} public IEnumerable <Article> GetArticles(int count = 0) { return(CacheHelper.Cache( cs => { IEnumerable <Article> articles = ArticleProvider.GetArticles() .OnSite("DancingGoatMvc") .Culture("en-us") .TopN(count) .OrderByDescending("DocumentPublishFrom") .TypedResult; // Ensures that the result of the query is saved, not the query itself; // Setup the cache dependencies only when caching is active. if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency(String.Format("nodes|{0}|{1}|all", "DancingGoatMvc", Article.CLASS_NAME.ToLowerInvariant())); } return articles; }, new CacheSettings(5, "myapp|data|articles", "DancingGoatMvc", "en-us", count) )); }
private MacroResolver GetNodeMacroResolver(int NodeID, string ClassName) { string Culture = URLHelper.GetQueryValue(Request.RawUrl, "culture"); return(CacheHelper.Cache <MacroResolver>(cs => { MacroResolver resolver = MacroResolver.GetInstance(); List <string> Columns = new List <string>(); if (!string.IsNullOrWhiteSpace(ToolTipFormat)) { Columns.AddRange(DataHelper.GetNotEmpty(MacroProcessor.GetMacros(ToolTipFormat, true), "NodeName").Split(';')); } if (!string.IsNullOrWhiteSpace(DisplayNameFormat)) { Columns.AddRange(DataHelper.GetNotEmpty(MacroProcessor.GetMacros(DisplayNameFormat, true), "NodeName").Split(';')); } // Get data for this node and render it out DataSet FullData = new DocumentQuery(ClassName) .WhereEquals("NodeID", NodeID) .Columns(Columns) .Culture(Culture) .CombineWithDefaultCulture(true).Result; foreach (DataColumn item in FullData.Tables[0].Columns) { resolver.SetNamedSourceData(item.ColumnName, FullData.Tables[0].Rows[0][item.ColumnName]); } if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("nodeid|" + NodeID); } return resolver; }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "RelationshipTree_GetNodeMacroResolver", NodeID, Culture, ToolTipFormat, DisplayNameFormat))); }
/// <summary> /// Gets the RelativeURL from the Node Alias Path /// </summary> /// <param name="NodeAliasPath">The Node Alias Path</param> /// <returns></returns> public static string NodeAliasPathToUrl(string NodeAliasPath) { string Url = CacheHelper.Cache <string>(cs => { // get proper Url path for the given document var DocQuery = DocumentHelper.GetDocuments() .Path(NodeAliasPath) .CombineWithDefaultCulture(true) .OnCurrentSite() .TopN(1); if (LocalizationContext.CurrentCulture != null) { DocQuery.Culture(LocalizationContext.CurrentCulture.CultureCode); } var TreeNode = DocQuery.FirstOrDefault(); if (TreeNode != null) { if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { "documentid|" + TreeNode.DocumentID, "cms.class|byname|" + TreeNode.ClassName }); } return(TreeNode.RelativeURL); } else { return(null); } }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "PartialWidgetGetUrlFromPath", NodeAliasPath, SiteContext.CurrentSiteName, LocalizationContext.CurrentCulture?.CultureCode)); return(AppRelativeToRelativeUrl("~" + Url)); }
public static object GetNewPageLink(EvaluationContext context, params object[] parameters) { try { if (parameters.Length >= 2) { string ClassName = ValidationHelper.GetString(parameters[0], ""); string ParentNodeAlias = ValidationHelper.GetString(parameters[1], ""); string Culture = ValidationHelper.GetString(parameters.Length > 2 ? parameters[2] : "en-US", "en-US"); string SiteName = ValidationHelper.GetString(parameters.Length > 3 ? parameters[3] : SiteContext.CurrentSiteName, SiteContext.CurrentSiteName); string SiteDomain = ""; if (SiteName.Equals("#currentsite", StringComparison.InvariantCultureIgnoreCase)) { SiteName = SiteContext.CurrentSiteName; } if (!string.IsNullOrWhiteSpace(SiteName) && !SiteName.Equals(SiteContext.CurrentSiteName, StringComparison.InvariantCultureIgnoreCase)) { SiteDomain = (System.Web.HttpContext.Current.Request.IsSecureConnection ? "https://" : "http://") + SiteInfo.Provider.Get(SiteName).DomainName.Trim('/'); } if (!string.IsNullOrWhiteSpace(ClassName) && !string.IsNullOrWhiteSpace(ParentNodeAlias)) { return(CacheHelper.Cache <string>(cs => { int ClassID = DataClassInfoProvider.GetDataClassInfo(ClassName).ClassID; int NodeID = new DocumentQuery().Path(ParentNodeAlias, PathTypeEnum.Single).FirstOrDefault().NodeID; return SiteDomain + URLHelper.ResolveUrl(string.Format("~/CMSModules/Content/CMSDesk/Edit/Edit.aspx?action=new&classid={0}&parentnodeid={1}&parentculture={2}", ClassID, NodeID, Culture)); }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), ClassName, ParentNodeAlias, Culture, SiteName))); } } } catch (Exception ex) { Service.Resolve <IEventLogService>().LogException("RelationshipMacros", "GetNewPageLinkError", ex); } return("#"); }
/// <summary> /// Loads device profile menu. /// </summary> private void LoadDevicesMenu() { if (UseSmallButton) { plcSmallButton.Visible = true; } else { plcBigButton.Visible = true; } string defaultString = HTMLHelper.HTMLEncode(GetString("deviceselector.default", ResourceCulture)); MenuItem devMenuItem = null; if (!UseSmallButton) { devMenuItem = new MenuItem { Text = defaultString, Tooltip = defaultString, }; // Display icon in On-site editing if ((Page is PortalPage) || (Page is TemplatePage)) { devMenuItem.IconClass = "icon-monitor-smartphone"; } SetStyles(devMenuItem); buttons.Buttons.Add(devMenuItem); } var enabledProfiles = CacheHelper.Cache(cs => { // Load enabled profiles var result = DeviceProfileInfoProvider.GetDeviceProfiles() .WhereTrue("ProfileEnabled") .OrderBy("ProfileOrder") .TypedResult; cs.CacheDependency = CacheHelper.GetCacheDependency(DeviceProfileInfo.OBJECT_TYPE + "|all"); return(result); }, new CacheSettings(10, "DeviceProfileSelector", "EnabledProfiles")); if (!DataHelper.DataSourceIsEmpty(enabledProfiles)) { // Create default item SubMenuItem defaultMenuItem = new SubMenuItem { Text = defaultString, Tooltip = defaultString, OnClientClick = "ChangeDevice('');", }; if (UseSmallButton) { // Insert the current device profile to the button btnProfilesSelector.Actions.Add(new CMSButtonAction() { OnClientClick = String.Format("ChangeDevice({0}); return false;", ScriptHelper.GetString(defaultString)), Text = defaultString }); } else { // Insert the current device profile to the context menu devMenuItem.SubItems.Add(defaultMenuItem); } // Load the profiles list foreach (DeviceProfileInfo profileInfo in enabledProfiles.Items) { string profileName = GetString(profileInfo.ProfileDisplayName, ResourceCulture); CMSButtonAction deviceButton = null; if (UseSmallButton) { deviceButton = new CMSButtonAction() { OnClientClick = String.Format("ChangeDevice({0}); return false;", ScriptHelper.GetString(profileInfo.ProfileName)), Text = profileName, Name = profileName }; btnProfilesSelector.Actions.Add(deviceButton); } else { SubMenuItem menuItem = new SubMenuItem { Text = HTMLHelper.HTMLEncode(profileName), Tooltip = HTMLHelper.HTMLEncode(profileName), OnClientClick = String.Format("ChangeDevice({0});", ScriptHelper.GetString(profileInfo.ProfileName)) }; devMenuItem.SubItems.Add(menuItem); } // Update main button if current device profile is equal currently processed profile if ((currentDevice != null) && (currentDevice.ProfileName.CompareToCSafe(profileInfo.ProfileName, true) == 0)) { if (UseSmallButton) { btnProfilesSelector.SelectedActionName = profileName; } else { devMenuItem.Text = HTMLHelper.HTMLEncode(profileName); devMenuItem.Tooltip = HTMLHelper.HTMLEncode(profileName); } } } } }
/// <summary> /// Sets in the Viewbag the CurrentDocument (TreeNode), CurrentSite (SiteInfo), and CurrentCulture (CultureInfo) /// </summary> /// <param name="DocumentID">The Document ID</param> /// <param name="CultureCode">The culture if you wish it to not be based on the found Document's</param> /// <param name="SiteName">The SiteName if you wish it to not be based on the Document's</param> public void SetContext(int DocumentID, string CultureCode = null, string SiteName = null) { TreeNode DocumentNodeForClass = new DocumentQuery().WhereEquals("DocumentID", DocumentID).FirstOrDefault(); TreeNode DocumentContext = null; if (DocumentNodeForClass != null) { // Set Page Builder Context HttpContext.Kentico().PageBuilder().Initialize(DocumentID); CacheableDocumentQuery RepeaterQuery = new CacheableDocumentQuery(DocumentNodeForClass.ClassName); RepeaterQuery.WhereEquals("DocumentID", DocumentID); RepeaterQuery.CacheItemNameParts.Add("documentid|" + DocumentID); if (EnvironmentHelper.PreviewEnabled) { RepeaterQuery.LatestVersion(true); RepeaterQuery.Published(false); } else { RepeaterQuery.PublishedVersion(true); } DocumentContext = RepeaterQuery.GetTypedResult().Items.FirstOrDefault(); } if (DocumentContext != null) { ViewBag.CurrentDocument = DocumentContext; if (string.IsNullOrWhiteSpace(SiteName)) { SiteName = DocumentContext.NodeSiteName; } if (string.IsNullOrWhiteSpace(CultureCode)) { CultureCode = DocumentContext.DocumentCulture; } } if (!string.IsNullOrWhiteSpace(SiteName)) { ViewBag.CurrentSite = CacheHelper.Cache <SiteInfo>(cs => { SiteInfo SiteObj = SiteInfoProvider.GetSiteInfo(SiteName); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency("cms.site|byid|" + SiteObj.SiteID); } return(SiteObj); }, new CacheSettings(CacheHelper.CacheMinutes(SiteName), "GetSiteInfo", SiteName)); } if (!string.IsNullOrWhiteSpace(CultureCode)) { ViewBag.CurrentCulture = CacheHelper.Cache <CultureInfo>(cs => { CultureInfo CultureObj = CultureInfoProvider.GetCultureInfo(CultureCode); if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency(CultureInfo.TYPEINFO.ObjectClassName + "|byid|" + CultureObj.CultureID); } return(CultureObj); }, new CacheSettings(CacheHelper.CacheMinutes(SiteName), "GetCultureInfo", CultureCode));; } }
private int GetNumberOfTotalProductsAvailable() { return(CacheHelper.Cache(cs => GetNumberOfTotalProductsAvailableInternal(), new CacheSettings(20, "Kadena.DashboardMetrics.TotalProductsAvailable_" + SiteContext.CurrentSiteName + "_" + LocalizationContext.PreferredCultureCode))); }
private OrderStatisticsData GetOrderStatistics() { return(CacheHelper.Cache(cs => GetOrderStatisticsInternal(), new CacheSettings(20, "Kadena.DashboardMetrics.OrderStatistics_" + SiteContext.CurrentSiteName))); }
private int GetNumberOfUsers() { return(CacheHelper.Cache(cs => GetNumberOfUsersInternal(), new CacheSettings(20, "Kadena.DashboardMetrics.NumberOfUsers_" + SiteContext.CurrentSiteName))); }
/// <summary> /// Displays buttons depending on web part settings. /// </summary> protected void DisplayButtons() { // If user is already authenticated if (AuthenticationHelper.IsAuthenticated()) { var openId = CacheHelper.Cache(cs => { var id = OpenIDUserInfoProvider.GetOpenIDByUserID(MembershipContext.AuthenticatedUser.UserID); if (cs.Cached) { var dependencyKey = UserSettingsInfo.OBJECT_TYPE + "|byid|" + MembershipContext.AuthenticatedUser.UserSettings.UserSettingsID; cs.CacheDependency = CacheHelper.GetCacheDependency(dependencyKey); } return(id); }, new CacheSettings(CacheMinutes, UserSettingsInfo.OBJECT_TYPE, "openid", MembershipContext.AuthenticatedUser.UserSettings.UserSettingsID) ); var isOpenIdUser = !String.IsNullOrEmpty(openId); // Signout is visible when ShowSignOut set to true and user has OpenID registered (this is ignored for design mode) if ((ShowSignOut && isOpenIdUser) || PortalContext.IsDesignMode(ViewMode)) { // If text is set use text/button link if (!string.IsNullOrEmpty(SignOutText)) { // Button link if (ShowAsButton) { pnlLogon.DefaultButton = btnSignOut.ID; btnSignOut.Text = SignOutText; btnSignOut.Visible = true; } // Text link else { pnlLogon.DefaultButton = btnSignOutLink.ID; btnSignOutLink.Text = SignOutText; btnSignOutLink.Visible = true; } } // Image link else { pnlLogon.DefaultButton = btnSignOutImage.ID; btnSignOutImage.ImageUrl = ResolveUrl(SignOutImageURL); btnSignOutImage.Visible = true; btnSignOutImage.ToolTip = GetString("webparts_membership_signoutbutton.signout"); btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout"); } } else { Visible = false; } txtInput.Visible = false; ltlScript.Visible = false; ltlProvidersVariables.Visible = false; } else { // If text is set use text/button link if (!string.IsNullOrEmpty(SignInText)) { // Button link if (ShowAsButton) { pnlLogon.DefaultButton = btnSignIn.ID; btnSignIn.Text = SignInText; btnSignIn.Visible = true; } // Text link else { pnlLogon.DefaultButton = btnSignInLink.ID; btnSignInLink.Text = SignInText; btnSignInLink.Visible = true; } } // Image link else { pnlLogon.DefaultButton = btnSignInImage.ID; btnSignInImage.ImageUrl = ResolveUrl(SignInImageURL); btnSignInImage.Visible = true; btnSignInImage.ToolTip = GetString("webparts_membership_signoutbutton.signin"); btnSignIn.Text = GetString("webparts_membership_signoutbutton.signin"); } txtInput.Visible = true; ltlScript.Visible = true; ltlProvidersVariables.Visible = true; } // Hide textbox when applicable if (!DisplayTextbox) { txtInput.Visible = false; } }
/// <summary> /// Checks Roles, Users, Resource Names, and Page ACL depending on configuration /// </summary> /// <param name="httpContext">The Route Context</param> /// <returns>If the request is authorized.</returns> protected override bool AuthorizeCore(HttpContextBase httpContext) { AuthorizingEventArgs AuthorizingArgs = new AuthorizingEventArgs() { CurrentUser = GetCurrentUser(httpContext), FoundPage = GetTreeNode(httpContext), Authorized = false }; bool IsAuthorized = false; // Start event, allow user to overwrite FoundPage using (var KenticoAuthorizeAuthorizingTaskHandler = AuthorizeEvents.Authorizing.StartEvent(AuthorizingArgs)) { if (!AuthorizingArgs.SkipDefaultValidation) { AuthorizingArgs.Authorized = CacheHelper.Cache(cs => { bool Authorized = false; List <string> CacheDependencies = new List <string>(); // Will remain true only if no other higher priority authorization items were specified bool OnlyAuthenticatedCheck = true; // Roles if (!Authorized && !string.IsNullOrWhiteSpace(Roles)) { OnlyAuthenticatedCheck = false; CacheDependencies.Add("cms.role|all"); CacheDependencies.Add("cms.userrole|all"); CacheDependencies.Add("cms.membershiprole|all"); CacheDependencies.Add("cms.membershipuser|all"); foreach (string Role in Roles.Split(";,|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { if (AuthorizingArgs.CurrentUser.IsInRole(Role, SiteContext.CurrentSiteName, true, true)) { Authorized = true; break; } } } // Users if (!Authorized && !string.IsNullOrWhiteSpace(Users)) { OnlyAuthenticatedCheck = false; foreach (string User in Users.Split(";,|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { if (User.ToLower().Trim() == AuthorizingArgs.CurrentUser.UserName.ToLower().Trim()) { Authorized = true; break; } } } // Explicit Permissions if (!Authorized && !string.IsNullOrWhiteSpace(ResourceAndPermissionNames)) { OnlyAuthenticatedCheck = false; CacheDependencies.Add("cms.role|all"); CacheDependencies.Add("cms.userrole|all"); CacheDependencies.Add("cms.membershiprole|all"); CacheDependencies.Add("cms.membershipuser|all"); CacheDependencies.Add("cms.permission|all"); CacheDependencies.Add("cms.rolepermission|all"); foreach (string ResourcePermissionName in ResourceAndPermissionNames.Split(";,|".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) { string[] StringParts = ResourcePermissionName.Split('.'); string PermissionName = StringParts.Last(); string ResourceName = string.Join(".", StringParts.Take(StringParts.Length - 1)); if (UserSecurityHelper.IsAuthorizedPerResource(ResourceName, PermissionName, SiteContext.CurrentSiteName, AuthorizingArgs.CurrentUser)) { Authorized = true; break; } } } // Check page level security if (!Authorized && CheckPageACL) { if (AuthorizingArgs.FoundPage != null) { OnlyAuthenticatedCheck = false; CacheDependencies.Add("cms.role|all"); CacheDependencies.Add("cms.userrole|all"); CacheDependencies.Add("cms.membershiprole|all"); CacheDependencies.Add("cms.membershipuser|all"); CacheDependencies.Add("nodeid|" + AuthorizingArgs.FoundPage.NodeID); CacheDependencies.Add("cms.acl|all"); CacheDependencies.Add("cms.aclitem|all"); if (TreeSecurityProvider.IsAuthorizedPerNode(AuthorizingArgs.FoundPage, NodePermissionToCheck, AuthorizingArgs.CurrentUser) != AuthorizationResultEnum.Denied) { Authorized = true; } } } // If there were no other authentication properties, check if this is purely an "just requires authentication" area if (OnlyAuthenticatedCheck && (!UserAuthenticationRequired || !AuthorizingArgs.CurrentUser.IsPublic())) { Authorized = true; } if (cs.Cached) { cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies.Distinct().ToArray()); } return(Authorized); }, new CacheSettings(CacheAuthenticationResults ? CacheHelper.CacheMinutes(SiteContext.CurrentSiteName) : 0, "AuthorizeCore", AuthorizingArgs.CurrentUser.UserID, (AuthorizingArgs.FoundPage != null ? AuthorizingArgs.FoundPage.DocumentID : -1), SiteContext.CurrentSiteName, Users, Roles, ResourceAndPermissionNames, CheckPageACL, NodePermissionToCheck, CustomUnauthorizedRedirect, UserAuthenticationRequired)); } IsAuthorized = AuthorizingArgs.Authorized; } return(IsAuthorized); }
/// <summary> /// Can override this if you need to implement custom logic, such as a custom route. httpContext.Request.RequestContext.RouteData.Values is often used to grab route data. /// </summary> /// <param name="httpContext">The HttpContext of the request</param> /// <returns>The Tree Node for this request, null acceptable.</returns> private TreeNode GetTreeNode(HttpContextBase httpContext) { TreeNode FoundNode = null; string SiteName = SiteContextSafe().SiteName; string DefaultCulture = SiteContextSafe().DefaultVisitorCulture; // Create GetPage Event Arguments GetPageEventArgs PageArgs = new GetPageEventArgs() { RelativeUrl = GetUrl(httpContext.Request.Url.AbsolutePath, httpContext.Request.ApplicationPath, SiteName), HttpContext = httpContext, SiteName = SiteName, Culture = GetCulture(), DefaultCulture = DefaultCulture }; // Start event, allow user to overwrite FoundPage using (var KenticoAuthorizeGetPageTaskHandler = AuthorizeEvents.GetPage.StartEvent(PageArgs)) { if (PageArgs.FoundPage == null) { IPageDataContextRetriever PageContextRetriever = DependencyResolver.Current.GetService <IPageDataContextRetriever>(); var PageContext = PageContextRetriever.Retrieve <TreeNode>(); // Try using Kentico's Page Builder Data Context if (PageContext != null && PageContext.Page != null) { PageArgs.FoundPage = PageContext.Page; } else { try { // Try to find the page from node alias path, default lookup type PageArgs.FoundPage = CacheHelper.Cache(cs => { TreeNode Page = DocumentHelper.GetDocuments() .Path(PageArgs.RelativeUrl, PathTypeEnum.Single) .Culture(!string.IsNullOrWhiteSpace(PageArgs.Culture) ? PageArgs.Culture : PageArgs.DefaultCulture) .CombineWithAnyCulture() .CombineWithDefaultCulture() .OnSite(PageArgs.SiteName) .Columns("NodeACLID", "NodeID", "DocumentID", "DocumentCulture") // The Fields required for authorization .FirstOrDefault(); if (cs.Cached && Page != null) { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { $"nodeid|{Page.NodeID}", $"documentid|{Page.DocumentID}" }); } return(Page); }, new CacheSettings(1440, "KenticoAuthorizeGetTreeNode", PageArgs.RelativeUrl, PageArgs.SiteName)); } catch (Exception ex) { PageArgs.ExceptionOnLookup = ex; } } } else if (PageArgs.FoundPage.NodeACLID <= 0) { PageArgs.ExceptionOnLookup = new NullReferenceException("The TreeNode does not contain the NodeACLID property, which is required for Permission lookup."); } // Finish the event KenticoAuthorizeGetPageTaskHandler.FinishEvent(); // Pass the Found Node back from the args FoundNode = PageArgs.FoundPage; } return(PageArgs.FoundPage); }
public TData Cache <TData>(Func <CacheSettings, TData> loadMethod, CacheSettings settings) => CacheHelper.Cache(loadMethod, settings);
public static void OverrideGetPageEvent(object sender, GetPageEventArgs args) { string cultureCode = args.Culture; //Occasionally the culture code may come out as full text such as English - United Kingdom, using this info we can fetch the culture code if (args.Culture.Length > 5) { cultureCode = CultureInfoProvider.GetCultures().Where(a => a.CultureName == args.Culture).First().CultureCode; } UpdateCacheItem <string>("CurrentRelUrl", args.RelativeUrl); UpdateCacheItem <string>("CultureCode", cultureCode); if (args.FoundPage == null) { try { args.FoundPage = CacheHelper.Cache <TreeNode>(cs => { //TODO: ADD Culture DataTable PossibleUrlPatterns = GetPossibleUrls(args.RelativeUrl, cultureCode); if (PossibleUrlPatterns.Rows.Count > 0) { var matchedUrl = GetUrlMatch(args.RelativeUrl, cultureCode, PossibleUrlPatterns); if (matchedUrl == null || !matchedUrl.HasMatch) { return(null); } DocumentQuery Query = DocumentHelper.GetDocuments(matchedUrl.UrlBreakdown.KenticoData.ClassName).WhereEquals("NodeId", matchedUrl.UrlBreakdown.KenticoData.NodeId).CombineWithAnyCulture(); if (args.PreviewEnabled) { Query.LatestVersion(true).Published(false); } else { Query.PublishedVersion(true); } TreeNode page = Query.FirstOrDefault(); if (cs.Cached) { if (page != null) { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { $"{WildcardUrlInfo.OBJECT_TYPE}|all", "documentid|" + page.DocumentID }); } else { cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { $"{WildcardUrlInfo.OBJECT_TYPE}dynamicrouting.wildcards|all" }); } } return(page); } else { return(null); } }, new CacheSettings(args.PreviewEnabled ? 0 : 1440, "DynamicRouting.GetPage", args.RelativeUrl, cultureCode, args.DefaultCulture, args.SiteName, args.PreviewEnabled, args.ColumnsVal)); } catch (Exception ex) { args.ExceptionOnLookup = ex; } if (args.FoundPage == null) { HttpContext.Current.Response.StatusCode = 404; } } }
/// <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); }
public static Dictionary <int, string> GetLocations() { return(CacheHelper.Cache(cs => LoadLocations(cs), new CacheSettings(30, "customdatasource|locations"))); }
/// <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); }
/// <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); }
private void LoadFooterLinks() { //if the table does not exist, let it crash var categories = CacheHelper.Cache( cs => CustomTableItemProvider.GetItems(Constants.CustomTables.FooterLinkCategory).ToList() .Select(r => new { column = r.GetValue(Constants.CustomTables.CategoryColumn).ToString(), name = r.GetValue(Constants.CustomTables.CategoryName).ToString() }), new CacheSettings(SettingsHelper.Webpart.CacheSettings, Constants.CustomTables.FooterLinkCategory)); LeftFooterTitle.Text = categories.First(r => r.column == Constants.CustomTables.ColumnLeft).name; RightFooterTitle.Text = categories.First(r => r.column == Constants.CustomTables.ColumnRight).name; CentreFooterTitle.Text = categories.First(r => r.column == Constants.CustomTables.ColumnCentre).name; //social links var socialLinks = CacheHelper.Cache( cs => CustomTableItemProvider.GetItems(Constants.CustomTables.SocialFooterLinks).ToList() .Select(r => new { title = r.GetValue(Constants.CustomTables.Title).ToString(), url = r.GetValue(Constants.CustomTables.Url).ToString() }), new CacheSettings(SettingsHelper.Webpart.CacheSettings, Constants.CustomTables.SocialFooterLinks)); var links = CacheHelper.Cache( cs => CustomTableItemProvider.GetItems(Constants.CustomTables.GlobalFooterLinks).ToList() .Select(r => new { column = r.GetValue(Constants.CustomTables.LinkColumn).ToString(), url = r.GetValue(Constants.CustomTables.LinkUrl).ToString(), name = r.GetValue(Constants.CustomTables.LinkLabel).ToString() }), new CacheSettings(SettingsHelper.Webpart.CacheSettings, Constants.CustomTables.GlobalFooterLinks)); LeftFooterRepeater.DataSource = links.Where(r => r.column == Constants.CustomTables.ColumnLeft).Select(r => new HyperLink() { Text = r.name, NavigateUrl = r.url }).ToList(); LeftFooterRepeater.DataBind(); SocialRepeater.DataSource = socialLinks.Select(r => new HyperLink() { Text = r.title, NavigateUrl = r.url }).ToList(); SocialRepeater.DataBind(); RightFooterRepeater.DataSource = links.Where(r => r.column == Constants.CustomTables.ColumnRight).Select(r => new HyperLink() { Text = r.name, NavigateUrl = r.url }).ToList(); RightFooterRepeater.DataBind(); CentreFooterRepeater.DataSource = links.Where(r => r.column == Constants.CustomTables.ColumnCentre).Select(r => new HyperLink() { Text = r.name, NavigateUrl = r.url }).ToList(); CentreFooterRepeater.DataBind(); }