3

I have a form with some fields like name, lastname, address, phonenumber etc. This page is accessible to anonymous users. The code behind is adding a new listitem under administrator privileges. When I go to the list I see an empty created by field. I would like to add programmatically for each new item a value with some existing user account.

The reason why I would like to do that is because on this list I have a workflow. And it is triggered on each new item. When I fill in the form anonymously the workflow is also running under an anonymous user. But it stuck in the progress status. When I log in with some user everything is working fine. So I would like to manipulate the system like the item which is created will run the workflow on some account.

the workflow is just a simple email with the items inside of it. It is created in SharePoint designer.

2 Answers 2

2

In the code behind you can set the Author field, which is Internal Name for Created By field.. You can do something like:

SPUser user = web.EnsureUser("<User Login Name>");
listItem["Author"] = user.ID;
listItem.Update();
0

SPSecurity.RunWithElevatedPrivilieges() will execute your code as the system account, i.e. the account under which the application pool runs, which might not be what you want to do. For example, if you have a workflow attached to the list which is supposed to trigger when new items are added to the list, it will not fire if you insert a new list item under the credentials of the system account (this was a security fix introduced in SharePoint 2007 SP 1). In that case, you will have to perform the insert operation under a different account that has the correct permissions on the list.

You can get the UserToken for any user using the following code:

        SPUserToken userToken = null;
        SPSecurity.RunWithElevatedPrivileges(() =>
        {
            using (SPSite site = new SPSite(SPContext.Current.Site.ID))
            {
                using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
                {
                    userToken = web.AllUsers["domain\\username"].UserToken;
                }
            }
        });

Replace the "domain\username" with the correct windows account name. Then you can pass this user token to one of the overloads of the SPSite object constructor to execute the code under this user's credentials like so:

        using (SPSite site = new SPSite(SPContext.Current.Site.ID, userToken))
        {
            using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
            {
                // This code will execute under the credentials of the userToken user
            }
        }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.