by Håvard Hebnes
18. July 2009 11:37
If you want to change the associated contenttype for a pagelayout, you can do it like this:
// first you need a reference to a PublihingSite or PublishingWeb
var pubSite = new PublishingSite(site);
// then we need to get all available pagelayouts
var pageLayouts = pubSite.GetPageLayouts(false);
// try to find the pagelayout you want to update
var pageLayout = GetPageLayout(pageLayouts, "pagelayout.aspx");
// if pagelayout exists, update it (here you need to have a ref to the contenttype)
if (pageLayout != null)
UpdateAssiciationContentType(contentType, pageLayout);
/// <summary>
/// Helper method to update associated contenttype for a pagelayout
/// </summary>
/// <param name="newsContentType"></param>
/// <param name="pageLayout"></param>
private static void UpdateAssiciationContentType(SPContentType contentType, PageLayout pageLayout)
{
// Check out the pagelayout
pageLayout.ListItem.File.CheckOut();
// set AssociatedContentType
pageLayout.AssociatedContentType = contentType;
pageLayout.Update();
// CheckIn, Publish and approve changes
pageLayout.ListItem.File.CheckIn("Changed associated contenttype");
pageLayout.ListItem.File.Publish("");
pageLayout.ListItem.File.Approve("Change approved");
}
/// <summary>
/// Get pagelayout by name
/// </summary>
/// <param name="pageLayouts"></param>
/// <param name="name"></param>
/// <returns></returns>
private static PageLayout GetPageLayout(IEnumerable<PageLayout> pageLayouts, string name)
{
var layouts = from PageLayout layout in pageLayouts
where layout.Name == name
select layout;
return layouts.Count() == 1 ? layouts.ElementAt(0) : null;
}
by Håvard Hebnes
20. June 2009 16:46
If you're looking for a specific item in a list, there are many ways you can get it.
You could go through the whole list using a loop (not recommended):
foreach (SPListItem item in list.Items)
{
if(item.Title == "Title1892")
return item;
}
You could use a SPQuery:
var tmpQuery = new SPQuery
{
Query =
@"<Where>
<Eq>
<FieldRef Name='Title' />
<Value Type='Text'>Title1892</Value>
</Eq>
</Where>"
};
list.GetItems(tmpQuery);
or you could use LINQ:
Method 1:
List<SPListItem> q = (from SPListItem item in list.Items
orderby item.Title
ascending
where item.Title == "Title1892"
select item).ToList();
Console.WriteLine(q[0].Title);
Method 2:
var query = from SPListItem item in list.Items
orderby item.Title
ascending
where item.Title == "Title1892"
select item;
Console.WriteLine(query.ElementAt(0).Title);