/// <summary>
 /// Gets the Typed Results of the query with caching
 /// </summary>
 /// <returns>The Typed Results.</returns>
 public InfoDataSet <BaseInfo> GetTypedResult()
 {
     if (CacheMinutes == -1)
     {
         // Check cache settings
         CacheMinutes = CacheHelper.CacheMinutes(SiteContext.CurrentSiteName);
     }
     if (string.IsNullOrWhiteSpace(CacheItemName))
     {
         CacheItemName = string.Join("|", CacheItemNameParts);
     }
     if (!EnvironmentHelper.PreviewEnabled && CacheMinutes > 0 && !string.IsNullOrWhiteSpace(CacheItemName))
     {
         return(CacheHelper.Cache <InfoDataSet <BaseInfo> >(cs =>
         {
             if (cs.Cached)
             {
                 cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies);
             }
             return TypedResult;
         }, new CacheSettings(CacheMinutes, CacheItemName, "ObjectQuery_TypedResult", CacheItemNameParts)));
     }
     else
     {
         return(TypedResult);
     }
 }
 /// <summary>
 /// Gets the Typed Results of the query with caching
 /// </summary>
 /// <returns>The Typed Results.</returns>
 public InfoDataSet <TreeNode> GetTypedResult()
 {
     if (CacheMinutes == -1)
     {
         // Check cache settings
         CacheMinutes = CacheHelper.CacheMinutes(SiteContext.CurrentSiteName);
     }
     if (string.IsNullOrWhiteSpace(CacheItemName))
     {
         CacheItemName = string.Join("|", CacheItemNameParts);
     }
     if (!EnvironmentHelper.PreviewEnabled && CacheMinutes > 0 && !string.IsNullOrWhiteSpace(CacheItemName))
     {
         return(CacheHelper.Cache <InfoDataSet <TreeNode> >(cs =>
         {
             if (cs.Cached)
             {
                 if (CacheDependencies != null)
                 {
                     CacheDependencyParts.AddRange(CacheDependencies);
                 }
                 cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencyParts.Distinct().ToArray());
             }
             return TypedResult;
         }, new CacheSettings(CacheMinutes, CacheItemName, "TreeNode_TypedResult", CacheItemNameParts)));
     }
     else
     {
         return(TypedResult);
     }
 }
 /// <summary>
 /// Gets the Results (DataSet) of the results, caching if applicable
 /// </summary>
 /// <returns>The DataSet of the results</returns>
 public DataSet GetCachedResult()
 {
     if (CacheMinutes == -1)
     {
         // Check cache settings
         CacheMinutes = CacheHelper.CacheMinutes(SiteContext.CurrentSiteName);
     }
     if (string.IsNullOrWhiteSpace(CacheItemName))
     {
         CacheItemName = string.Join("|", CacheItemNameParts);
     }
     if (CacheMinutes > 0 && !string.IsNullOrWhiteSpace(CacheItemName))
     {
         return(CacheHelper.Cache <DataSet>(cs =>
         {
             if (cs.Cached)
             {
                 cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies);
             }
             return Result;
         }, new CacheSettings(CacheMinutes, CacheItemName, "ObjectQuery_Result", CacheItemNameParts)));
     }
     else
     {
         return(Result);
     }
 }
Esempio n. 4
0
        public List <SocialIcon> GetAllSocialIcons(string siteName = null)
        {
            var socialLinks = new List <SocialIcon>();

            if (siteName == null)
            {
                siteName = SiteContext.CurrentSiteName;
            }

            using (var cs = new CachedSection <List <SocialIcon> >(ref socialLinks, CacheHelper.CacheMinutes(siteName), true, _projectCacheKey))
            {
                if (cs.LoadData)
                {
                    socialLinks = SocialIconProvider.GetSocialIcons().OnSite(siteName).ToList();

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{siteName}|{SocialIcon.CLASS_NAME}|all"
                    };

                    cs.Data            = socialLinks;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(socialLinks);
        }
        public static string GetContent(string manifestKey, string prefix = "")
        {
            var distServerPath = HttpContext.Current.Server.MapPath(DistPath);

            if (string.IsNullOrEmpty(distServerPath) || !Directory.Exists(distServerPath))
            {
                return(null);
            }
            var result = string.Empty;

            using (var cs = new CachedSection <string>(ref result, CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), true,
                                                       $"AssetsCache_{manifestKey}_{ManifestHash}"))
            {
                if (cs.LoadData)
                {
                    var fullPath = GetFullPathFromManifest(manifestKey);
                    if (!string.IsNullOrEmpty(fullPath))
                    {
                        var processedValue = fullPath.Replace($"{DistPath}/", string.Empty);
                        var fullFilePath   = distServerPath + "\\" + prefix + processedValue;
                        if (File.Exists(fullFilePath))
                        {
                            result = File.ReadAllText(fullFilePath);
                        }

                        cs.Data = result;
                    }
                }
            }

            return(result);
        }
Esempio n. 6
0
    /// <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)
    {
        return(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[]
                    {
                        "cms.document|byid|" + 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)));
    }
Esempio n. 7
0
        public List <Project> GetAllProjects(string siteName = null)
        {
            var result = new List <Project>();

            if (siteName == null)
            {
                siteName = SiteContext.CurrentSiteName;
            }
            using (var cs = new CachedSection <List <Project> >(ref result, CacheHelper.CacheMinutes(siteName), true, _projectCacheKey))
            {
                if (cs.LoadData)
                {
                    result = ProjectProvider.GetProjects().OnSite(siteName).ToList();

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{siteName}|{Project.CLASS_NAME}|all"
                    };

                    cs.Data            = result;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(result);
        }
        private static string[] GetPageTypesWithSeoUrlClassNames()
        {
            const string cacheKey = "deleteboilerplate|pagetypeswithseourlclassnames|all";

            var result   = new string[0];
            var siteName = SiteContext.CurrentSiteName;

            using (var cs = new CachedSection <string[]>(ref result, CacheHelper.CacheMinutes(siteName), true, cacheKey))
            {
                if (cs.LoadData)
                {
                    // All page types with SeoUrl column
                    result = DataClassInfoProvider.GetClasses()
                             .Where(dataClass =>
                                    dataClass.ClassIsDocumentType &&
                                    dataClass.ClassSearchSettingsInfos.Any(x => x.Name.Equals(Constants.DynamicRouting.SeoUrlFieldName)))
                             .Select(x => x.ClassName)
                             .ToArray();

                    var cacheDependencies = new List <string>
                    {
                        "cms.class|all",
                        "cms.documenttype|all"
                    };

                    cs.Data            = result;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(result);
        }
Esempio n. 9
0
 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");
             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 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)));
             }
         }
     }
     catch (Exception ex)
     {
         EventLogProvider.LogException("RelationshipMacros", "GetNewPageLinkError", ex);
     }
     return("#");
 }
Esempio n. 10
0
 /// <summary>
 /// Gets the TreeNode for the corresponding path, can be either the NodeAliasPath or a URL Alias
 /// </summary>
 /// <param name="Path"></param>
 /// <returns></returns>
 public static TreeNode GetNodeByAliasPath(string Path, string ClassName = null, string CultureCode = null)
 {
     return(CacheHelper.Cache <TreeNode>(cs =>
     {
         List <string> CacheDependencies = new List <string>();
         TreeNode FoundNode = DocumentQueryHelper.RepeaterQuery(Path: Path, ClassNames: ClassName, CultureCode: CultureCode).GetTypedResult().Items.FirstOrDefault();
         if (FoundNode == null)
         {
             // Check Url Aliases
             var FoundNodeByAlias = DocumentAliasInfoProvider.GetDocumentAliasesWithNodesDataQuery().WhereEquals("AliasUrlPath", Path).Or().Where(string.Format("'{0}' like AliasWildCardRule", SqlHelper.EscapeQuotes(Path))).FirstOrDefault();
             if (FoundNodeByAlias != null && FoundNodeByAlias.AliasNodeID > 0)
             {
                 CacheDependencies.Add("cms.documentalias|all");
                 CacheDependencies.Add(string.Format("node|{0}|{1}", SiteContext.CurrentSiteName, Path));
                 FoundNode = DocumentQueryHelper.RepeaterQuery(NodeID: FoundNodeByAlias.AliasNodeID, ClassNames: ClassName, CultureCode: (!string.IsNullOrWhiteSpace(FoundNodeByAlias.AliasCulture) ? FoundNodeByAlias.AliasCulture : CultureCode)).GetTypedResult().Items.FirstOrDefault();
             }
         }
         if (FoundNode != null)
         {
             CacheDependencies.Add("documentid|" + FoundNode.DocumentID);
         }
         if (cs.Cached)
         {
             cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies.ToArray());
         }
         return FoundNode;
     }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), Path, ClassName, CultureCode)));
 }
Esempio n. 11
0
        /// <summary>
        /// Mimics the Repeater with Custom Query, including caching
        /// </summary>
        /// <param name="QueryName">The Query Name</param>
        /// <param name="OrderBy">Order By</param>
        /// <param name="SelectTopN">TopN</param>
        /// <param name="WhereCondition">Where Condition</param>
        /// <param name="Columns">Columns</param>
        /// <param name="QueryParameters">Query Parameters to pass to query.</param>
        /// <param name="CacheItemName">Unique identifier for the cache, REQUIRED for caching.</param>
        /// <param name="CacheMinutes">Optional Cache Minutes, will use site's default cache minutes if not provided.</param>
        /// <param name="CacheDependencies">Cache Dependencies</param>
        /// <returns></returns>
        public static DataSet ExecuteQuery(
            string QueryName,
            string OrderBy        = null,
            int SelectTopN        = -1,
            string WhereCondition = null,
            string Columns        = null,
            QueryDataParameters QueryParameters = null,
            string CacheItemName       = null,
            int CacheMinutes           = -1,
            string[] CacheDependencies = null)
        {
            List <object> CacheItemNameParts = new List <object>();

            if (CacheMinutes == -1)
            {
                // Check cache settings
                CacheMinutes = CacheHelper.CacheMinutes(SiteContext.CurrentSiteName);
            }

            if (CacheMinutes > 0 && !string.IsNullOrWhiteSpace(CacheItemName))
            {
                // Fill up the CacheItemNameParts
                if (QueryParameters != null)
                {
                    foreach (DataParameter QueryParam in QueryParameters)
                    {
                        CacheItemNameParts.Add(string.Format("{0}|{1}", QueryParam.Name, QueryParam.Value));
                    }
                }
                if (!string.IsNullOrWhiteSpace(WhereCondition))
                {
                    CacheItemNameParts.Add(WhereCondition);
                }
                if (!string.IsNullOrWhiteSpace(OrderBy))
                {
                    CacheItemNameParts.Add(OrderBy);
                }
                if (!string.IsNullOrWhiteSpace(Columns))
                {
                    CacheItemNameParts.Add(Columns);
                }
                if (SelectTopN > -1)
                {
                    CacheItemNameParts.Add(SelectTopN);
                }
                return(CacheHelper.Cache <DataSet>(cs =>
                {
                    if (cs.Cached)
                    {
                        cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies);
                    }
                    return ConnectionHelper.ExecuteQuery(QueryName, QueryParameters, WhereCondition, OrderBy, SelectTopN, Columns);
                }, new CacheSettings(CacheMinutes, CacheItemName, "Result", QueryName, CacheItemNameParts)));
            }
            else
            {
                return(ConnectionHelper.ExecuteQuery(QueryName, QueryParameters, WhereCondition, OrderBy, SelectTopN, Columns));
            }
        }
        /// <summary>
        /// Uses the given IPrincipleUser to get the current user.
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        public static UserInfo AuthenticatedUser(IPrincipal User)
        {
            string Username = (User != null && User.Identity != null ? User.Identity.Name : "public");

            return(CacheHelper.Cache <UserInfo>(cs =>
            {
                return UserInfoProvider.GetUserInfo(Username);
            }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "AuthenticatedUser", Username)));
        }
 /// <summary>
 /// Gets the Typed Results, populating the "Children" of the Nodes with their children.
 /// </summary>
 /// <returns>The TreeNodes (top level) with Children populated with their child elements.</returns>
 public InfoDataSet <TreeNode> GetHierarchicalTypedResult()
 {
     if (CacheMinutes == -1)
     {
         // Check cache settings
         CacheMinutes = CacheHelper.CacheMinutes(SiteContext.CurrentSiteName);
     }
     if (string.IsNullOrWhiteSpace(CacheItemName))
     {
         CacheItemName = string.Join("|", CacheItemNameParts);
     }
     if (!EnvironmentHelper.PreviewEnabled && CacheMinutes > 0 && !string.IsNullOrWhiteSpace(CacheItemName))
     {
         return(CacheHelper.Cache <InfoDataSet <TreeNode> >(cs =>
         {
             Dictionary <int, TreeNode> ParentNodeIDToTreeNode = new Dictionary <int, TreeNode>();
             List <TreeNode> CompiledNodes = new List <TreeNode>();
             if (cs.Cached)
             {
                 if (CacheDependencies != null)
                 {
                     CacheDependencyParts.AddRange(CacheDependencies);
                 }
                 cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencyParts.Distinct().ToArray());
             }
             // Populate the Children of the TypedResults
             foreach (TreeNode Node in TypedResult)
             {
                 // Make sure Children only contain the children found in the typed results.
                 Node.Children.MakeEmpty();
                 ParentNodeIDToTreeNode.Add(Node.NodeID, Node);
                 // If no parent exists, add to top level
                 if (!ParentNodeIDToTreeNode.ContainsKey(Node.NodeParentID))
                 {
                     CompiledNodes.Add(Node);
                 }
                 else
                 {
                     // Otherwise, add to the parent element.
                     ParentNodeIDToTreeNode[Node.NodeParentID].Children.Add(Node);
                 }
             }
             return new InfoDataSet <TreeNode>(CompiledNodes.ToArray());
         }, new CacheSettings(CacheMinutes, CacheItemName, "TreeNode_TypedResult", CacheItemNameParts)));
     }
     else
     {
         return(TypedResult);
     }
 }
Esempio n. 14
0
        /// <summary>
        /// Determines if the current relationship is an AdHoc relationship based on the UI Property RelationshipName
        /// </summary>
        /// <returns>True if the current relationship is an ad hoc relationship</returns>
        private static bool IsAdHocRelationship()
        {
            string RelationshipName = ValidationHelper.GetString(UIContext.Current.Data.GetValue("RelationshipName"), "");

            return(CacheHelper.Cache <bool>(cs =>
            {
                RelationshipNameInfo relationshipObj = RelationshipNameInfoProvider.GetRelationshipNameInfo(RelationshipName);

                if (relationshipObj != null && cs.Cached)
                {
                    cs.CacheDependency = CacheHelper.GetCacheDependency("cms.relationshipname|byid|" + relationshipObj.RelationshipNameId);
                }
                return relationshipObj != null ? relationshipObj.RelationshipNameIsAdHoc : false;
            }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "RelationshipMacro", "IsAdHocRelationship", RelationshipName)));
        }
Esempio n. 15
0
        public IEnumerable <TaxonomyType> GetAllTaxonomyTypes()
        {
            var cacheKey = $"{_baseCacheKey}|types|all";

            var result   = new List <TaxonomyType>();
            var siteName = SiteContext.CurrentSiteName;

            using (var cs = new CachedSection <List <TaxonomyType> >(ref result, CacheHelper.CacheMinutes(siteName), true, cacheKey))
            {
                if (cs.LoadData)
                {
                    result = TaxonomyTypeProvider.GetTaxonomyTypes().AllCultures()
                             .Published()
                             .OnSite(siteName)
                             .OrderBy("NodeOrder")
                             .ToList();

                    var taxonomyItems = TaxonomyItemProvider.GetTaxonomyItems().AllCultures()
                                        .Published()
                                        .OnSite(siteName)
                                        .OrderBy("NodeOrder")
                                        .ToList();

                    foreach (var taxonomyType in result)
                    {
                        taxonomyType.TaxonomyItems =
                            taxonomyItems.Where(x => x.NodeParentID == taxonomyType.NodeID).ToList();

                        foreach (var taxonomyItem in taxonomyType.TaxonomyItems)
                        {
                            taxonomyItem.TaxonomyType = taxonomyType;
                        }
                    }

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{siteName}|{TaxonomyType.CLASS_NAME}|all",
                        $"nodes|{siteName}|{TaxonomyItem.CLASS_NAME}|all"
                    };

                    cs.Data            = result;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(result);
        }
 /// <summary>
 /// Gets the TreeNode for the corresponding path, can be either the NodeAliasPath or a URL Alias
 /// </summary>
 /// <param name="Path"></param>
 /// <returns></returns>
 public static TreeNode GetNodeByAliasPath(string Path, string ClassName = null, string CultureCode = null)
 {
     return(CacheHelper.Cache <TreeNode>(cs =>
     {
         List <string> CacheDependencies = new List <string>();
         TreeNode FoundNode = DocumentQueryHelper.RepeaterQuery(Path: Path, ClassNames: ClassName, CultureCode: CultureCode).GetTypedResult().Items.FirstOrDefault();
         if (FoundNode != null)
         {
             CacheDependencies.Add("documentid|" + FoundNode.DocumentID);
         }
         if (cs.Cached)
         {
             cs.CacheDependency = CacheHelper.GetCacheDependency(CacheDependencies.ToArray());
         }
         return FoundNode;
     }, new CacheSettings((EnvironmentHelper.PreviewEnabled ? 0 : CacheHelper.CacheMinutes(SiteContext.CurrentSiteName)), Path, ClassName, CultureCode, SiteContext.CurrentSiteName)));
 }
    /// <summary>
    /// Selects line randomly.
    /// </summary>
    /// <param name="random">Random generator</param>
    /// <param name="questions">Questions</param>
    /// <returns>Lines</returns>
    private string[] SelectLine(Random random, string questions)
    {
        ArrayList lines = null;

        // Get current culture
        string culture  = ValidationHelper.GetString(ViewState["CultureCode"], LocalizationContext.PreferredCultureCode);
        string sitename = SiteContext.CurrentSiteName;

        // Get or generate cache item name
        string useCacheItemName = CacheHelper.BaseCacheKey + "|" + RequestContext.CurrentURL + "|" + ClientID + "|" + culture + "|" + UseTextOrImageCaptcha;

        // Try to get data from cache
        if (CacheHelper.CacheMinutes(sitename) == 0)
        {
            // No caching
            CacheHelper.Remove(useCacheItemName);
            lines = GetLines(random, culture, questions);
        }
        else
        {
            object value = null;

            // Try to retrieve data from the cache
            if (!CacheHelper.TryGetItem(useCacheItemName, out value))
            {
                lines = GetLines(random, culture, questions);
                if ((lines != null) && (lines.Count > 0))
                {
                    CacheHelper.Add(useCacheItemName, lines, null, DateTime.Now.AddMinutes(CacheHelper.CacheMinutes(sitename)), Cache.NoSlidingExpiration);
                }
            }
            else
            {
                lines = (ArrayList)CacheHelper.GetItem(useCacheItemName);
            }
        }

        if ((lines != null) && (lines.Count > 0))
        {
            // Split selected line a return result.
            int selectedLine = random.Next(lines.Count);
            return(lines[selectedLine].ToString().Split(';'));
        }

        return(null);
    }
        /// <summary>
        /// Can override this to implement your own custom logic to get the UserInfo of the current user.  Use httpContext.User
        /// </summary>
        /// <param name="httpContext">The HttpContext of the request</param>
        /// <returns>The UserInfo, should return the Public user if they are not logged in.</returns>
        public virtual UserInfo GetCurrentUser(HttpContextBase httpContext)
        {
            // return EnvironmentHelper.AuthenticatedUser(httpContext.User);
            // This logic is the same as my EnvironmentHelper.AuthenticatedUser(httpContext.User), added so does not depend on my classes.
            string Username = DataHelper.GetNotEmpty((httpContext.User != null && httpContext.User.Identity != null ? httpContext.User.Identity.Name : "public"), "public");

            return(CacheHelper.Cache <UserInfo>(cs =>
            {
                UserInfo UserObj = UserInfoProvider.GetUserInfo(Username);
                if (UserObj == null)
                {
                    UserObj = UserInfoProvider.GetUserInfo("public");
                }
                if (cs.Cached)
                {
                    cs.CacheDependency = CacheHelper.GetCacheDependency("cms.user|byid|" + UserObj.UserID);
                }
                return UserObj;
            }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), "AuthenticatedUser", Username)));
        }
Esempio n. 19
0
        /// <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);
            }
        }
Esempio n. 20
0
    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)));
    }
Esempio n. 21
0
 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("#");
 }
        public List <NavigationLink> GetAllNavigationLinks(string siteName = null)
        {
            var navigationLinks = new List <NavigationLink>();

            if (siteName == null)
            {
                siteName = SiteContext.CurrentSiteName;
            }

            using (var cs = new CachedSection <List <NavigationLink> >(ref navigationLinks, CacheHelper.CacheMinutes(siteName), true, _projectCacheKey))
            {
                if (cs.LoadData)
                {
                    navigationLinks = NavigationLinkProvider.GetNavigationLinks().OnSite(siteName).ToList();

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{siteName}|{NavigationLink.CLASS_NAME}|all"
                    };

                    cs.Data            = navigationLinks;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(navigationLinks);
        }
 private static CacheSettings CreateCacheSettings(string cacheKey)
 {
     return(new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), cacheKey));
 }
Esempio n. 24
0
        /// <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));;
            }
        }
Esempio n. 25
0
 /// <summary>
 /// Gets the default content cache minutes set for the current site.
 /// </summary>
 private static int GetCacheMinutes()
 {
     return(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName));
 }
        /// <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);
        }
Esempio n. 27
0
        protected void OnTabCreated(object sender, TabCreatedEventArgs e)
        {
            if (e.Tab == null)
            {
                return;
            }

            var tab     = e.Tab;
            var element = e.UIElement;
            PageTemplateInfo UITemplate = PageTemplateInfoProvider.GetPageTemplateInfo(e.UIElement.ElementPageTemplateID);
            var manager = DocumentManager;
            var node    = manager.Node;

            bool splitViewSupported = PortalContext.ViewMode != ViewModeEnum.EditLive;

            string elementName = element.ElementName.ToLowerCSafe();

            if (UITemplate.CodeName.ToLower().Contains("editrelationship"))
            {
                XmlDocument properties = new XmlDocument();
                properties.LoadXml(e.UIElement.ElementProperties);
                XmlNode LeftSideMacro  = properties.SelectSingleNode("/Data[1]/IsLeftSideMacro[1]");
                XmlNode RightSideMacro = properties.SelectSingleNode("/Data[1]/IsRightSideMacro[1]");
                XmlNode AutoHide       = properties.SelectSingleNode("/Data[1]/AutoHide[1]");

                if (AutoHide != null && ValidationHelper.GetBoolean(AutoHide.InnerText, false) && LeftSideMacro != null && RightSideMacro != null)
                {
                    MacroResolver pageResolver = MacroResolver.GetInstance();
                    // Get current node's class, then full document so it has related data.
                    int      NodeID          = ValidationHelper.GetInteger(URLHelper.GetQueryValue(RequestContext.RawURL, "nodeid"), 1);
                    string   Culture         = DataHelper.GetNotEmpty(URLHelper.GetQueryValue(RequestContext.RawURL, "culture"), "en-US");
                    TreeNode CurrentDocument = CacheHelper.Cache <TreeNode>(cs =>
                    {
                        TreeNode Document = new DocumentQuery().WhereEquals("NodeID", NodeID).Columns("ClassName").FirstOrDefault();
                        Document          = new DocumentQuery(Document.ClassName).WhereEquals("NodeID", NodeID).Culture(Culture).FirstOrDefault();
                        if (cs.Cached)
                        {
                            cs.CacheDependency = CacheHelper.GetCacheDependency(new string[] { string.Format("node|{0}|{1}|{2}", Document.NodeSiteName, Document.NodeAliasPath, Culture,
                                                                                                             PageTemplateInfo.OBJECT_TYPE + "|byid|" + e.UIElement.ElementPageTemplateID) });
                        }
                        return(Document);
                    }, new CacheSettings(CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), NodeID, Culture, e.UIElement.ElementPageTemplateID));
                    pageResolver.SetNamedSourceData("CurrentDocument", CurrentDocument);
                    if (!(ValidationHelper.GetBoolean(pageResolver.ResolveMacros(LeftSideMacro.InnerText), true) || ValidationHelper.GetBoolean(pageResolver.ResolveMacros(RightSideMacro.InnerText), true)))
                    {
                        e.Tab = null;
                    }
                }
            }

            if (DocumentUIHelper.IsElementHiddenForNode(element, node))
            {
                e.Tab = null;
                return;
            }

            // Ensure split view mode
            if (splitViewSupported && PortalUIHelper.DisplaySplitMode)
            {
                tab.RedirectUrl = DocumentUIHelper.GetSplitViewUrl(tab.RedirectUrl);
            }
        }
        public List <NavigationLink> GetNavigationLinksByPath(string path)
        {
            var cacheKey = $"{_projectCacheKey}|{path}";

            var navigationLinks = new List <NavigationLink>();

            using (var cs = new CachedSection <List <NavigationLink> >(ref navigationLinks, CacheHelper.CacheMinutes(SiteContext.CurrentSiteName), true, cacheKey))
            {
                if (cs.LoadData)
                {
                    var result = NavigationLinkProvider.GetNavigationLinks()
                                 .Path(path)
                                 .OnSite(SiteContext.CurrentSiteName)
                                 .ToList();

                    var associatedPagePaths = DocumentHelper.GetDocuments()
                                              .Columns("NodeGUID,NodeAliasPath")
                                              .WhereIn("NodeGUID", result.Select(x => x.AssociatedPage).ToList())
                                              .ToList();

                    foreach (var navigationLink in result)
                    {
                        navigationLink.AssociatedPagePath =
                            associatedPagePaths.FirstOrDefault(x => x.NodeGUID == navigationLink.AssociatedPage)
                            ?.NodeAliasPath;

                        navigationLink.ChildLinks = result.Where(x => x.NodeParentID == navigationLink.NodeID)
                                                    .OrderBy(x => x.NodeOrder)
                                                    .ToList();
                        foreach (var childLink in navigationLink.ChildLinks)
                        {
                            childLink.ParentLink = navigationLink;
                        }
                    }

                    navigationLinks = result.Where(x => x.ParentLink == default(NavigationLink)).ToList();

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{SiteContext.CurrentSiteName}|{NavigationLink.CLASS_NAME}|all"
                    };

                    cs.Data            = navigationLinks;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(navigationLinks);
        }
Esempio n. 29
0
        public IDictionary <Guid, TaxonomyItem> GetAllTaxonomyItems()
        {
            var cacheKey = $"{_baseCacheKey}|items|all";
            var siteName = SiteContext.CurrentSiteName;
            var result   = new Dictionary <Guid, TaxonomyItem>();

            using (var cs = new CachedSection <Dictionary <Guid, TaxonomyItem> >(ref result, CacheHelper.CacheMinutes(siteName), true, cacheKey))
            {
                if (cs.LoadData)
                {
                    result = GetAllTaxonomyTypes().SelectMany(x => x.TaxonomyItems)
                             .ToDictionary(k => k.NodeGUID, v => v);

                    var cacheDependencies = new List <string>
                    {
                        $"nodes|{siteName}|{TaxonomyType.CLASS_NAME}|all",
                        $"nodes|{siteName}|{TaxonomyItem.CLASS_NAME}|all"
                    };

                    cs.Data            = result;
                    cs.CacheDependency = CacheHelper.GetCacheDependency(cacheDependencies);
                }
            }

            return(result);
        }