2007-08-31

Recursive batch delete command

We all know the scenario: we have a list with a large number of junk testing records we need to get rid of.

We could write a console app with the following:

SPListItemCollection listItems = list.Items;
for (int id = 8; id <= listItems.Count; id++)
{
try {
listItems[id].Delete();
Console.WriteLine("Deleting " + id.ToString());
}
catch(Exception ex){ }
}
list.Update();



Now sit back and watch the numbers tick by... or you could what is widely considered the fastest way in SharePoint (WSS) to perform the operation, to use 'ProcessBatchData' as it avoids the Object Model and is considerably faster.

Here is some example code which will remove items from a SharePoint list.

StringBuilder oSBDelBat = new StringBuilder();
oSBDelBat.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?><batch>");
foreach (SPListItem item in CurrentList.Items)
{
oSBDelBat.Append("<method>");
oSBDelBat.Append("<setlist scope="\">" + CurrentList.ID + "</setlist>");
oSBDelBat.Append("<setvar name="\">" + Convert.ToString(item.ID) + "</setvar>");
oSBDelBat.Append("<setvar name="\">Delete</setvar>");
oSBDelBat.Append("</method>");
}
oSBDelBat.Append("</batch>");
try
{
SPContext.Current.Site.RootWeb.ProcessBatchData(oSBDelBat.ToString());
}
catch (Exception ex)
{
Console.WriteLine("Delete failed: " + ex.Message);
throw;
}


2007-08-28

Deploying a dll to the GAC and recycling the application pool

When developing a sharepoint dll in Visual Studio 2005 the quickest way to deploy and test your dll is to automate it with a post build event.



How do we do this?

1.- Open the properties window for your project... solution explorer> right click project name > select properties.



2.- Click "Build Events".



3.- Paste

"C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\gacutil" -i "$(TargetPath)" } C:\Recycle.vbs

in to the "Post-build event command line" field.

4.- Create a new text file with the following script:

strAppPoolName = "Sharepoint - 80"
strComputer = "."
Set objWMIService = GetObject("winmgmts:{authenticationLevel=pktPrivacy}\\"& strComputer & "\root\microsoftiisv2")
Set colItems = objWMIService.ExecQuery("Select * From IIsApplicationPool Where Name = 'W3SVC/AppPools/" & strAppPoolName & "'")
For Each objItem in colItems
objItem.Recycle
Next
Wscript.echo "Recycle Completed"

5.- Save as C:\Recycle.vbs