How-To: Overcome missing Exists() function on SharePoint objects like SiteGroups, RoleDefinitions, Lists etc.

Especially when I'm wiriting Feature Receivers, I need to know if a certain SharePoint objects is present or not. A .Exists() method would be great on all the nice collections we are given back from SPRoleDefinition, SPGroup, SPList and so on. This posts will show you how to overcome this in a convenient way. No rocket sience here, only collection information from various posts and putting them together.

The shortest way to implement an .Exists() function is by using LINQ Extensions:

SPGroup.Exists() –>  if (!mySPWeb.SiteGroups.Cast<SPGroup>().Any(group => string.Equals(group.Name, myGroupName)))
SPRoleDefinition.Exists() –> if (!mySPWeb.RoleDefinitions.Cast<SPRoleDefinition>().Any(role => string.Equals(role.Name, myRoleDefinitionName)))
SPList.Exists() –> if (!mySPWeb.Lists.Cast<SPList>().Any(list => string.Equals(list.Title, myListTitle)))
… and so on

This is taking up the ideas from the post of Jeremy Thake that you can find here.

If for any reason you can't or don't want to use extensions, there is also a "old-fashioned" way of doing this which I've used in the past, however, it works only for SharePoint object collections that have an .XML property:

         /// <summary>
        /// This function checks the passed in SPWeb instance for the existance of a role (definition).
        /// </summary>
        /// <param name="web">The SPWeb object for the site to contain the role.</param>
        /// <param name="roleName">The name of the role (definition) looked for.</param>
        /// <returns></returns>
        public static bool SPRoleDefinitionExists(SPWeb web, string roleName)
        {
            XPathDocument doc = new XPathDocument(new StringReader(web.RoleDefinitions.Xml));
            if (null == doc.CreateNavigator().SelectSingleNode("//Role[@Name='" + roleName + "']"))
                return false;
            return true;
        }

         /// <summary>
        /// This function checks the passed in SPWeb instance for the existance of a site group.
        /// </summary>
        /// <param name="web">The SPWeb object for the site to contain the role.</param>
        /// <param name="siteGroupName">The name of the site group looked for.</param>
        /// <returns></returns>
        public static bool SPSiteGroupExists(SPWeb web, string siteGroupName)
        {
            XPathDocument doc = new XPathDocument(new StringReader(web.RoleDefinitions.Xml));
            if (null == doc.CreateNavigator().SelectSingleNode("//Group[@Name='" + siteGroupName + "']"))
                return false;
            return true;
        }

 

Leave a Reply