Saturday, 16 November 2013

SharePoint 2010 update current Logged in user Name in Modified By field of Custom List code running "SHAREPOINT\system"


Recently i worked on requirement in which user has only READ access on SharePoint site but he can submit input to SharePoint list through custom form

To manage the access permission for the user who has only read access on site, we have two approaches

1. Use runwithelevatedprivileges
2. Use user token

i used user token approach

Before updating the Author field in the list  used below code

protected void Button1_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                SPUser systemUser = SPContext.Current.Web.AllUsers[@"SHAREPOINT\system"];
                SPUser currentUser = SPContext.Current.Web.CurrentUser;
                using(SPSite site=new SPSite(SPContext.Current.Web.Url,systemUser.UserToken))
                {
                    site.AllowUnsafeUpdates = true;
                    using (SPWeb web = site.OpenWeb())
                    {
                        web.AllowUnsafeUpdates = true;
                        try
                        {
                            SPList list = web.Lists["List Name"];
                            SPListItem listItem = list.Items.Add();
                         
   string userName = currentUser.ID + ";#" + currentUser.Name;
                            listItem["Author"] = userName; //Modified By field.
                            listItem.Update();
                            list.Update();          
                        }
                        catch (Exception ex)
                        {
           // Exception handling logic
                        }
                    }
                }
            }        
        }

cheers!!