Delete First n records from sharepoint online list
Here i have a custom list with few views.
In perticular view display am getting list threshhold problem.
So my requirements is that when the items in list is crossing 4990 then immediatly i need to delete first 100 records from the list.
first here am getting the total records in the list, then if the cound is greter then 4990 then am getting first 100 records.
then am looping each record for deletion.
so i will not get list thresh hold prolem for my view.
here am using sharepoint cleint object model to perform this operations for sharepoint online.
I think this same code will work for onpremises also.
so for logging into sharepoint online it will not accept direct password.
we need to convert our password as securestring.
so here am using GetPasswordFromConsoleInput() funtion for converting my login password to convert as secure string and then am passing this secure string to
SharePointOnlineCredentials() method.
here am used console application todo this task.
so here is my code.
static void Main(string[] args)
{
string webUrl = "https://sharepoint.com/usa/";
string userName ="******";
string pwd = "*******";
SecureString password = GetPasswordFromConsoleInput(pwd);
using (var context = new ClientContext(webUrl))
{
context.Credentials = new SharePointOnlineCredentials(userName, password);
context.Load(context.Web, w => w.Title);
context.ExecuteQuery();
List listName = context.Web.Lists.GetByTitle("MyList");
context.Load(listName);
context.ExecuteQuery();
if (listName.ItemCount > 4990)
{
CamlQuery query1 = new CamlQuery();
query1.ViewXml = "<View><RowLimit>100</RowLimit></View>";
ListItemCollection items = listName.GetItems(query1);
context.Load(items);
context.ExecuteQuery();
if (items.Count>0)
{
for (int i = items.Count-1; i>=0; i--)
{
items[i].DeleteObject();
}
context.ExecuteQuery();
}
}
}
}
private static SecureString GetPasswordFromConsoleInput(string password)
{
//ConsoleKeyInfo info;
//Get the user's password as a SecureString
SecureString securePassword = new SecureString();
foreach (char c in password)
{
securePassword.AppendChar(c);
}
return securePassword;
}
Comments