SharePoint 2010のPageで重複するWebPartをFeatureで削除

18358 ワード

SharePoint 2010のPageで繰り返されるWebPartをFeatureで削除します.
コードは次のとおりです.
public class SupportCenterDuplicatedWebpartRemovalFeatureReceiver : FnxFeatureReceiver
    {
        /// <summary>
        /// Event receiver for feature activation
        /// </summary>
        /// <param name="properties">Feature properties passed from SharePoint</param>
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            base.FeatureActivated(properties);
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            SPFeatureScope scope = properties.Feature.Definition.Scope;
            SPSite parentSite = null;
            SPWeb thisWeb = null;
            SPWeb rootWeb = null;

            // Note: Scope should be "Web" for Support Center Pages feature but handler is here in case of future deployment scope change
            if (scope == SPFeatureScope.Site)
            {
                parentSite = properties.Feature.Parent as SPSite;
                if (parentSite != null)
                {
                    rootWeb = parentSite.RootWeb;
                    thisWeb = rootWeb;
                }
            }
            else if (scope == SPFeatureScope.Web)
            {
                thisWeb = properties.Feature.Parent as SPWeb;

                if (thisWeb != null)
                {
                    parentSite = thisWeb.Site;

                    if (parentSite != null)
                    {
                        rootWeb = parentSite.RootWeb;
                    }
                }
            }

            try
            {
                if (rootWeb != null)
                {
                    if (thisWeb != null)
                    {
                        // we only add the navaigation to support subsite; otherwise the 2nd level menu will mess up
                        if (!thisWeb.Url.ToLower().Contains(KSConstants.SUPPORTER_SITE_URL.ToLower())) return;
                        DeleteDuplicatedWebparts(thisWeb);
                        DeleteWebpartEntries(rootWeb);
                        ResetFeatures(parentSite);
                    }
                }
            }
            catch (SPException ex)
            {
                Trace.WriteLine(ex.Message);
                LoggingService.LogError("Features", ex.ToFormattedExceptionString());
            }
        }

        /// <summary>
        /// reset web feature(create webpartentries) and site feautre(add webpart into pages)
        /// </summary>
        /// <param name="thisWeb"></param>
        /// <param name="parentSite"></param>
        private void ResetFeatures(SPSite parentSite)
        {
            Guid siteFeatureId = new Guid("668ce347-97bb-4048-ae96-95f2c3a4cc42");
            var siteFeature = parentSite.Features.SingleOrDefault(sf => sf.DefinitionId == siteFeatureId);
            if (siteFeature == null)
            {
                ActivateOrReactiveSiteFeature(parentSite, siteFeatureId, true, true);
            }
            else
            {
                ActivateOrReactiveSiteFeature(parentSite, siteFeatureId, false, true);
                ActivateOrReactiveSiteFeature(parentSite, siteFeatureId, true, true);
            }
        }

        /// <summary>
        /// activate or deactivate site feature
        /// </summary>
        /// <param name="site"></param>
        /// <param name="featureGuid"></param>
        /// <param name="activate"></param>
        /// <param name="force"></param>
        private void ActivateOrReactiveSiteFeature(SPSite site, Guid featureGuid, bool activate, bool force)
        {
            if (activate)//if feature is not activated
            {
                site.Features.Add(featureGuid, force);
                //activate feature
            }
            else site.Features.Remove(featureGuid, force);
        }

        /// <summary>
        /// Delete duplicated all webparts
        /// </summary>
        /// <param name="thisWeb"></param>
        private void DeleteDuplicatedWebparts(SPWeb thisWeb)
        {
            //delete all webpart.
            Collection<string> existWebpartTitles = new Collection<string>();
            SPList pageList = thisWeb.Lists["Pages"];
            foreach (SPListItem item in pageList.Items)
            {
                SPFile file = thisWeb.GetFile(thisWeb.Url + "/" + item.Url);
                if (file.CheckOutType != Microsoft.SharePoint.SPFile.SPCheckOutType.None)
                {
                    file.UndoCheckOut();
                }
                file.CheckOut();
                if (file != null)
                {
                    existWebpartTitles.Clear();
                    using (SPLimitedWebPartManager webpartsMng = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
                    {
                        for (int i = webpartsMng.WebParts.Count - 1; i >= 0; i--)
                        {
                            //delete condition: 
                            //1. if it is "Content Top 5 WebPart", webpart with same catalog will be deleted.
                            //2. if it is not "Content Top 5 WebPart", webpart with same title will be deleted.
                            if (webpartsMng.WebParts[i].Title.Equals("Content Top 5 WebPart", StringComparison.Ordinal))
                            {
                                string catagory = (webpartsMng.WebParts[i].WebBrowsableObject as FundsNetwork.KnowledgeAndSupport.WebParts.Top5WebPart.Top5WebPart).Category;
                                if (!existWebpartTitles.Contains(catagory))
                                {
                                    existWebpartTitles.Add(catagory);
                                    continue;
                                }
                            }
                            else
                            {
                                if (!existWebpartTitles.Contains(webpartsMng.WebParts[i].Title))
                                {
                                    existWebpartTitles.Add(webpartsMng.WebParts[i].Title);
                                    continue;
                                }
                            }
                            webpartsMng.DeleteWebPart(webpartsMng.WebParts[i]);
                        }
                    }
                }
                file.CheckIn("Delete personal Webparts.");
            }
            thisWeb.Update();
        }

        /// <summary>
        /// Delete all webpartentries in KS project
        /// </summary>
        /// <param name="rootWeb"></param>
        private void DeleteWebpartEntries(SPWeb rootWeb)
        {
            // delete Web Part template files
            List<SPFile> FilesToDelete = new List<SPFile>();
            // figure out which Web Part template files need to be deleted
            SPList WebPartGallery = rootWeb.Lists["Web Part Gallery"];
            if (WebPartGallery != null)
            {
                foreach (SPListItem WebPartTemplateFile in WebPartGallery.Items)
                {
                    if (WebPartTemplateFile.File.Name.Contains("KnowledgeAndSupport"))
                    {
                        FilesToDelete.Add(WebPartTemplateFile.File);
                    }
                }
                // delete Web Part template files 
                foreach (SPFile file in FilesToDelete)
                {
                    if (file.CheckOutType != Microsoft.SharePoint.SPFile.SPCheckOutType.None)
                    {
                        file.UndoCheckOut();
                    }
                    file.CheckOut();
                    file.Delete();
                    file.Update();
                    rootWeb.Update();
                }
            }
        }
    }

 
......