Thursday, March 26, 2009

Delete List Items or Document Library Items Forever (Without sending to recycle bin)

Some weeks back I got a post from my co-worker to delete all the items from a list without being overloading items in recycle bin.

There is a good post in http://code.msdn.microsoft.com/SharePointListDelete which I'm keeping it for my own reference. This post is not my original content, and I'm only keeping this post for my own reference in development.

Firstly this method of deleting the items is more efficient with the performance on the execution for deleting let's say 10,000 of records. Also it sends only one request to delete all the records instead of individual request per items. Also I noted one more useful method spSite.RootWeb.ProcessBatchData(sbDelete.ToString());


public static void DeleteAllItems(string site, string list)
{
using (SPSite spSite = new SPSite(site)){
using (SPWeb spWeb = spSite.OpenWeb()){
StringBuilder sbDelete =BuildBatchDeleteCommand(spWeb.Lists[list]); spSite.RootWeb.ProcessBatchData(sbDelete.ToString()); spWeb.RecycleBin.DeleteAll();
//
Note: For me it didn't work for rootweb, i used spWeb.
ProcessBatchData(sbDelete.ToString());}}}
Now the method to call the XML request. This will build a list of all the items to get deleted.
private static StringBuilder BuildBatchDeleteCommand(SPList spList)
{

StringBuilder sbDelete = new
StringBuilder();

sbDelete.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><Batch>");

string command = "<Method><SetList Scope=\"Request\">" + spList.ID +

"</SetList><SetVar Name=\"ID\">{0}</SetVar><SetVar Name=\"Cmd\">Delete</SetVar></Method>";
// Remember to delete the document library you have to add this <SetVar> too //<SetVar Name="owsfileref">{server-relative-url}</SetVar> The relative URl to the document to delete, where SPFile instance's ServerRelativeUrl property.
foreach (SPListItem item in spList.Items)
{
sbDelete.Append(string.Format(command, item.ID.ToString()));
}
sbDelete.Append("</Batch>");

return sbDelete;
}
Also I got variant of this method to delete purge the items similar way. This can be executed in the list object without calling the Rootweb.You have to call only the CAML query with each fields ids defined. This will also run as a single request batch command.

<Batch OnError="Continue">
<Method ID="1" Cmd="Delete">
<Field Name="ID">1</Field>
</Method>
<Method ID="2" Cmd="Delete">
<Field Name="ID">2</Field>
</Method>
……… so on
</Batch>

Similary for deleting the documents from the list , add the following line inside the Method tag.
<Field Name="FileRef">http://spdev/Library Name/Msg-4218faa2-727e.xml</Field>

The commands can also be executed from the Sharepoint Webservices UpdateListItems() method.

No comments: