Tuesday, January 11, 2011

Deleting ListItems for large list size Failed?

The following code only works for List. Refer my other post for Document Library.
For novice to use this code, specify the strings variables siteURL, listName.

The maximum items that your program can delete is 5000 which can be changed.


The way web.Lists[listName] works is that it loads the meta-data information of the all lists for that specific SPWeb object and then it does SPList.Title comparison with metadata of all the lists returned and returns the first matching list from the SPWeb.Lists collection. This has got two implications:
1. The loading of list is slow as the meta-data information of all the list is loaded and then comparison happens on list name specified.
2. If there are large numbers of lists in a specific SPWeb, the process of getting the meta-data information of all the available lists may introduce transaction lock in backend database when multiple such calls happen in quick succession.

The suggested way to access a list is by using SPWeb.GetList(string url). In this case, first the GUID of list is figured out and then meta-data for the list is loaded. Obviously, this is a faster way also.
If your head is already spinning, the summary is that
"And you must use  web.GetList(listName) instead of web.Lists[listName]. Otherwise it may take for ever."

Hey friends, If you have saved lot of time using my code, please pay me by smiling at all the people you see today. They will smile back at you. We will all be in a pool of happy smiles. If you have a big wallet, find & feed a hungry stomach today(not mine).  And God will bless you.

using (SPSite site = new SPSite(siteURL))
{

 using (SPWeb web = site.OpenWeb())
                {
                    web.AllowUnsafeUpdates = true;
                    StringBuilder sbDelete = new StringBuilder();

                   SPList spList = web.GetList("/Lists/" + listName);

                    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>";
                    int limit = 0;
                    foreach (SPListItem item in spList.Items)
                    {
                        limit++;
                        if (limit > 5000)
                            break;
                        sbDelete.Append(string.Format(command, item.ID.ToString()));
                    }
                    sbDelete.Append("</Batch>");

                    web.ProcessBatchData(sbDelete.ToString());
                    web.Update();
                    web.AllowUnsafeUpdates = false;
                }
}

No comments: