I have a custom webpart. Inside this webpart there is some logic to update the webpart settings. See below the code.
I edit the page where the webpart is located. I click on a button which will update the webpart and run the code below.
It gives me an exception like:
WebPartPageUserException: The file is not checked out. You must first check out this document before making changes.
Why do I got this exception? I checked this page out.
private bool SetWebPartProperties(string pageUrl, string webPartId)
{
Microsoft.SharePoint.Utilities.SPUtility.ValidateFormDigest();
SPWeb currentWeb = SPContext.Current.Web;
PublishingWeb publishingWeb = null;
PublishingPage page = null;
SPSecurity.RunWithElevatedPrivileges(
delegate()
{
using (SPSite site = new SPSite(currentWeb.Url))
{
using (SPWeb web = site.OpenWeb())
{
if (PublishingWeb.IsPublishingWeb(web))
{
publishingWeb = PublishingWeb.GetPublishingWeb(web);
PublishingPageCollection pages = publishingWeb.GetPublishingPages();
if (pages[pageUrl] != null)
{
page = pages[pageUrl];
if (page.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
{
page.CheckOut();
}
}
}
SPLimitedWebPartManager wpm = null;
// Here you will use the url of the page to get an instance of its
// WebPartManager - with this object, you will be able to find and
// update your web part....
wpm = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);
// ... using its id to find it in the WebParts collection of the
// WebPartManager.
System.Web.UI.WebControls.WebParts.WebPart wp = wpm.WebParts[webPartId];
// ... and this setting is important, otherwise it won't accept
// changes by code. Notice that I'm setting it back to false after
// the update...
wpm.Web.AllowUnsafeUpdates = true;
// DO SOME LOGIC
// ... and then you save it...
wpm.SaveChanges(wp); // HERE THE ERROR OCCURED
wpm.Web.AllowUnsafeUpdates = false;
wpm.Dispose();
string checkinComment = string.Format("Hoofditems: {0} Aantal nieuwsitems: {1}", "", maxDays);
page.CheckIn(checkinComment);
SPFile pageFile = page.ListItem.File;
pageFile.Publish(checkinComment);
}
}
});
return true;
}