SharePoint 2013 Timer Job - Remove user from SharePoint group not working

Kumar32490 1 Reputation point
2021-02-16T04:51:12.193+00:00

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();



            }

        }

    }

}

}

SharePoint Server
SharePoint Server
A family of Microsoft on-premises document management and storage systems.
2,236 questions
SharePoint Development
SharePoint Development
SharePoint: A group of Microsoft Products and technologies used for sharing and managing content, knowledge, and applications.Development: The process of researching, productizing, and refining new or existing technologies.
2,686 questions
SharePoint Server Development
SharePoint Server Development
SharePoint Server: A family of Microsoft on-premises document management and storage systems.Development: The process of researching, productizing, and refining new or existing technologies.
1,576 questions
{count} votes

3 answers

Sort by: Most helpful
  1. Baker Kong-MSFT 3,791 Reputation points
    2021-02-16T08:16:05.17+00:00

    Hi @Kumar32490 ,

    It shows that the user you specified could not be found. Generally, the user login name is like to:

    68569-image.png

    It's different from email address.

    Best Regards,
    Baker Kong


    If an Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

  2. Kumar32490 1 Reputation point
    2021-02-16T08:44:21.087+00:00

    Hi @Baker Kong-MSFT ,

    May I know what changes should I make in source code so that it works ?


  3. Kumar32490 1 Reputation point
    2021-02-17T11:10:04.84+00:00

    Hi @Baker Kong-MSFT

    I have updated the code successfully to include domain\username. It removes user from the group successfully. However, I notice that the below code runs only for first item in the list. It should run for all items in the list. May I know where I am going wrong ?

    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)  
    
                {  
    
                                     
                    string[] loginNameParts = item["UserName"].ToString().Split('\\');  
    
                    string loginNameWithoutDomain = "i:0#.w|ustdev\\" + loginNameParts[1];  
    
                    RemoveUser(loginNameWithoutDomain, item["GroupName"].ToString(), "http://dw032/");  
    
                    item["Status"] = "Expired";  
    
                    item.Update();                
    
     
    
                }  
    
                else  
    
                {  
    
                    item["Status"] = "Active";  
    
                    item.Update();  
    
     
    
                }  
    
            }  
    
        }  
    
    0 comments No comments