private void AddContentTypeToLibraries(string siteUrl)The first method is what we are looping through all webs and go to each list and try to add a content type. And the second method is before adding a content type to a list, we are checking whether the content type is already there or not for that list. So, we are checking for that condition and if find the content type is not already attached to the list then only we are adding to the list.
{
List<SPContentType> contentTypes = new List<SPContentType>();
using (SPSite site = new SPSite(siteUrl))
{
using (SPWeb web = site.OpenWeb())
{
contentTypes.Add(web.ContentTypes["ContentType1"]);
contentTypes.Add(web.ContentTypes["ContentType2"]);
contentTypes.Add(web.ContentTypes["ContentType3"]);
}
foreach (SPWeb web in site.AllWebs)
{
try
{
web.AllowUnsafeUpdates = true;
foreach (SPList list in web.Lists)
{
if (!list.Title.Equals("MyList", StringComparison.InvariantCultureIgnoreCase))
continue;
for (int i = 0; i < contentTypes.Count; i++)
{
AddContentTypeToList(contentTypes[i], list);
}
}
}
catch { }
finally
{
web.AllowUnsafeUpdates = false;
web.Dispose();
}
}
}
}
void AddContentTypeToList(SPContentType ct, SPList list)
{
if (list.ContentTypes[ct.Name] == null)
{
list.ContentTypes.Add(ct);
list.Update();
}
}
Hope you understand the logic and how we need to implement it.
0 komentar:
Post a Comment