"File is not checked out" error using the methods of the SPLimitedWebPartManager class

10 Nov 2014 By Giuseppe Marchi (SharePoint MVP)

In one of our lastest projects, we needed to insert some web parts within a SharePoint 2013 page, at the activation of a feature. One of the web parts in question was the XsltViewWebPart, which we talked about in one of the previous posts.
The page instead was the home page of a Publishing site, so with obligatory checkout and publication mechanisms before doing any modification to the content or relative layout. This is our code for adding the web part within the page:

 

SPFile homePageFile = web.GetFile("Pages/Home.aspx");
SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(homePageFile.ServerRelativeUrl, PersonalizationScope.Shared);

if (homePageFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
    homePageFile.CheckOut();

SPList list = web.Lists["MY LIST NAME"];
XsltListViewWebPart webpart = CreateXsltViewWebPart(list);
wpManager.AddWebPart(webpart, "TopWebPartZone", 0);

homePageFile.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
homePageFile.Publish(string.Empty);

 

By carrying out the above code, we got the following error during the execution of the call to the AddWebPart method:

 

"File is not checked out."

 

And yet the call to the CheckOut method was there ...

 

Where was the problem?
The problem was at the point in which the instance of the class SPLimitedWebPartManager was recovered. In fact, by trying to recover this instance before the call to the CheckOut method, the class had in memory a version of the page that wasn't checked-out yet, so it wasn't modifiable. For its functions to work correctly, this instance has to be recovered AFTER having done checkout on the page.
Here is the working code.

 

SPFile homePageFile = web.GetFile("Pages/Home.aspx");
if (homePageFile.CheckOutStatus == SPFile.SPCheckOutStatus.None)
    homePageFile.CheckOut();

SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(homePageFile.ServerRelativeUrl, PersonalizationScope.Shared);

SPList list = web.Lists["MY LIST NAME"];
XsltListViewWebPart webpart = CreateXsltViewWebPart(list);
wpManager.AddWebPart(webpart, "TopWebPartZone", 0);

homePageFile.CheckIn(string.Empty, SPCheckinType.MajorCheckIn);
homePageFile.Publish(string.Empty);

 

I hope this will be helpful to you.

0 Comments :

Comment

Comments closed