I have written a SP2013 timer job, which should remove user from SharePoint group when triggered. Written below piece of code in CustomTimerJob.cs. It updates the list item status to Active/Expired successfully on running the timer, but doesn't remove user from SharePoint group. Can let me know where I am wrong ?
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TimerJobApplication
{
public class CustomTimerJob : SPJobDefinition
{
public CustomTimerJob() : base() { }
public CustomTimerJob(string jobName, SPService service)
: base(jobName, service, null, SPJobLockType.None)
{
this.Title = "Access Rights Timer";
}
public CustomTimerJob(string jobName, SPWebApplication webapp)
: base(jobName, webapp, null, SPJobLockType.ContentDatabase)
{
this.Title = "Access Rights Timer";
}
public void RemoveUser(String userLoginName, string groupName, string SiteURL)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SiteURL))
{
using (SPWeb web = site.OpenWeb())
{
SPGroup group = web.SiteGroups[groupName];
SPUser userToRemove = web.EnsureUser(userLoginName);
group.RemoveUser(userToRemove);
group.Update();
}
}
});
}
public override void Execute(Guid targetInstanceId)
{
var currentdate=DateTime.Now.Date;
SPWebApplication webApp = this.Parent as SPWebApplication;
SPList taskList = webApp.Sites[0].AllWebs["dev"].Lists["Limited_Access_To_Security_Groups"];
SPView view = taskList.Views["All Items"]; //custom view name
SPListItemCollection olistitems = taskList.GetItems(view);
foreach (SPListItem item in olistitems)
{
if (Convert.ToDateTime(item["ExpiryDate"]) <= DateTime.Now.Date)
{
RemoveUser(item["UserName"].ToString(), "Dev Visitors", "http://devsite/");
item["Status"] = "Expired";
item.Update();
}
else
{
item["Status"] = "Active";
item.Update();
}
}
}
}
}