正如问题所说 - 有没有办法确定哪些页面包含我的网页部分?
答案 0 :(得分:15)
如果您正在寻找代码,我会为您提供一些帮助。如果您想查找所有内容查询Web部件,那么您可以调用我的代码:
FindWebPart("http://server.com/", "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart");
以下是代码:
public static void FindWebPart(string siteCollectionUrl, string webPartName)
{
using (SPSite siteCollection = new SPSite(siteCollectionUrl))
{
using (SPWeb rootSite = siteCollection.OpenWeb())
{
FindWebPartHelper(rootSite, webPartName);
}
}
}
public static void FindWebPartHelper(SPWeb site, string webPartName)
{
// Search for web part in Pages document library
SPList pagesList = null;
try
{
pagesList = site.Lists["Pages"];
}
catch (ArgumentException)
{
// List not found
}
if (null != pagesList)
{
SPListItemCollection pages = pagesList.Items;
foreach (SPListItem page in pages)
{
SPFile file = page.File;
using (SPLimitedWebPartManager mgr = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
try
{
SPLimitedWebPartCollection webparts = mgr.WebParts;
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in webparts)
{
// Here perform the webpart check
// For instance you could identify the web part by
// its class name
if (webPartName == wp.GetType().ToString())
{
// Found a match! Now do something...
Console.WriteLine("Found web part!");
}
}
}
finally
{
// Needs to be disposed
mgr.Web.Dispose();
}
}
}
}
// Check sub sites
SPWebCollection subSites = site.Webs;
foreach (SPWeb subSite in subSites)
{
try
{
FindWebPartHelper(subSite, webPartName);
}
finally
{
// Don't forget to dispose!
subSite.Dispose();
}
}
}
当然,您可以对此代码进行少量更改。目前它进行字符串比较,但很容易以更类型的方式进行。玩得开心!
答案 1 :(得分:3)
作为替代方案,如果要测试Web部件页面(包括协作网站上的默认页面),可以使用以下代码片段,该代码片段使用SPWeb对象的Files属性:
private static void FindWebPart(string siteUrl, string webPartName)
{
using (var site = new SPSite(siteUrl))
{
foreach (SPWeb web in site.AllWebs)
{
foreach (var file in web.Files.Cast<SPFile>().Where(file => file.Name.EndsWith("aspx")))
{
FindWebPartOnPage(webPartName, file);
}
var pagesTemplateType = (SPListTemplateType)Enum.Parse(typeof(SPListTemplateType), "850");
foreach (var documentLibrary in web.Lists.Cast<SPList>().Where(list => list.BaseTemplate == pagesTemplateType || (list.BaseTemplate == SPListTemplateType.DocumentLibrary && list.Title.Contains("Pages"))))
{
foreach (var file in documentLibrary.Items.Cast<SPListItem>().Where(item => item.File.Name.EndsWith("aspx")).Select(item => item.File))
{
FindWebPartOnPage(webPartName, file);
}
}
web.Dispose();
}
}
}
private static void FindWebPartOnPage(string webPartName, SPFile file)
{
using (var webPartManager = file.GetLimitedWebPartManager(PersonalizationScope.Shared))
{
if (webPartManager.WebParts.Cast<WebPart>().Any(webPart => webPart.GetType().Name == webPartName))
{
Console.WriteLine(file.ServerRelativeUrl);
}
webPartManager.Web.Dispose();
}
}
注意:发布功能创建的页面库的BaseTemplate值不是SPListTemplateType.DocumentLibrary;相反,它由“隐藏”值850表示。
这与LeonZandman的回答类似,但只有类名用于提供匹配:
FindWebPart("http://yoursite.com/", "MyWebPart");