In the earlier article, we saw, how to Create a List View. In the same manner, we may come across a scenario to delete/update the existing views. The below snippet will be handy for the developers.
using Microsoft.SharePoint.Client;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace Office365.Console
{
class Program
{
static void Main(string[] args)
{
DeleteUpdateView();
}
public static void DeleteUpdateView()
{
OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
string siteUrl = "https://************.sharepoint.com/sites/DeveloperSite/";
//string siteUrl = item.TargetSiteUrl;
string userName = "sathish@****.onmicrosoft.com";
string password = "********";
using (var clientContext = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
{
try
{
Web web = clientContext.Web;
clientContext.Load(web);
clientContext.Load(web.Lists);
clientContext.ExecuteQuery();
List list = web.Lists.GetByTitle("Test List");
clientContext.Load(list);
clientContext.Load(list.Views);
clientContext.ExecuteQuery();
//To Delete the View
var lstViewToBeDeleted = list.Views.GetByTitle("Created By Me");
lstViewToBeDeleted.DeleteObject();
clientContext.ExecuteQuery();
//To Update the View
var lstViewToBeUpdated = list.Views.GetByTitle("All Items Test");
lstViewToBeUpdated.ViewQuery = "<OrderBy><FieldRef Name="Modified" Ascending="FALSE" /></OrderBy>";
lstViewToBeUpdated.Update();
clientContext.ExecuteQuery();
}
catch (Exception ex)
{
System.Console.ForegroundColor = ConsoleColor.Red;
System.Console.WriteLine("Exception Occured : " + ex.Message);
System.IO.File.AppendAllText("C:\Temp\UpdatePropertyBagIndexed.txt", ex.Message + " - " + siteUrl + Environment.NewLine);
}
}
System.Console.WriteLine("Completed....");
System.Console.WriteLine("Press Any Key to Exit ....");
System.Console.ReadLine();
}
}
}
In the above snippet, I have deleted a view and updated a view. The Update, I have done only the ViewQuery property. Like that, we can update many properties of a view and the ViewQuery itself, can have many CAML Queries.
The Output of the Update will be something like,
Happy Coding,
Sathish Nadarajan.
Leave a comment