Introduction
The audit feature of Microsoft SharePoint Server or SharePoint Online lets you track user actions on a site's content types, lists, libraries, list items, and library files within your site collections. Knowing who has done what with which information is critical for many requirements, such as regulatory compliance and records management. In this article, you will learn how to configure SharePoint Site Collection Audit settings programmatically, using C# Client-Side Object Model (CSOM). This will be applicable to all SharePoint On-Premise platforms.
Prerequisite
- Create a site collection in SharePoint central admin.
- Should have site collection administrator permission.
Enable Audit Settings using CSOM
The following section explains the flow for enabling the SharePoint site collection audit settings.
- Add the references to your C# project. The necessary references are Microsoft.SharePoint.Client.dll and Microsoft.SharePoint.Client.Runtime.dll.
- Initialize the client context object with the site URL.
- ClientContext ctx = new ClientContext("https://SiteURL.com");
- If you are trying to access the SharePoint site, then you need to setup the site credentials with credentials parameter and get it set to the client context.
- ctx.AuthenticationMode = ClientAuthenticationMode.FormsAuthentication; ctx.FormsAuthenticationLoginInfo = new FormsAuthenticationLoginInfo("ID67891", "Password");
- Initialize audit object with the site object.
- Load and execute the query.
- Enable the Audit by setting the AuditFlags to AuditMaskType.All
- Set the number of days to hold the audit log by AuditLogTrimmingRetention property.
- Trim the audit log by setting true to TrimAuditLog.
- Load and execute the query.
- Site= ctx.Site;
- Audit audit = site.Audit;
- ctx.Load(site);
- ctx.Load(audit);
- ctx.ExecuteQuery();
- // Enable all auditing is site collection level
- audit.AuditFlags = Microsoft.SharePoint.Client.AuditMaskType.All;
- audit.Update();
- // Adjust retention time to be 30 days
- site.AuditLogTrimmingRetention = 30;
- site.TrimAuditLog = true;
- ctx.ExecuteQuery();



Guru GunalPosted Sep 15, 2016, 10:23 AM
Good one
Tarun DPosted Aug 7, 2016, 9:55 AM
Thanks for the nice share