Thursday, 10 March 2016

Gets the Current user in the Timer Job Debbugging

Question)can we get the currentuser?while debugging i’m getting the system account.what if i need the currect logged in user?
Answer)Glad that the code helped you. For your question, timer job is an independent one. We cannot get SPContext in it.
If you check “SharePoint 2010 Timer” service under services.msc, it is the user “log on as” the value you get for the user identity.
may be this scenario will help you to understand, I have set the timer job to run everyday at 11:00pm. The code will run automatically at that time and it will be running under only one user context.
I generally use the below method to get the user with which timer job is running
private string GetContextUser()
        {
            string _timerJobUser =@"SHAREPOINT\System";
            try
            {
                string httpContextUser = ((HttpContext.Current !=null) && (HttpContext.Current.User !=null) && (HttpContext.Current.User.Identity !=null)) ?
                HttpContext.Current.User.Identity.Name :string.Empty;
                string windowsIdentity = (WindowsIdentity.GetCurrent() !=null) ? WindowsIdentity.GetCurrent().Name :string.Empty;
                if (!(string.IsNullOrEmpty(httpContextUser)))
                {
                    _timerJobUser = httpContextUser;
                }
                else if ((string.IsNullOrEmpty(httpContextUser)) && (!string.IsNullOrEmpty(windowsIdentity)))
                {
                    _timerJobUser = windowsIdentity;
                }
            }
            catch (Exception ex)
            {
                //log it before throwing
                throw (ex);
            }
            return _timerJobUser;
        }

No comments:

Post a Comment