1

I am trying to create an EventReceiver for a blog site (for the Posts list) and am having some trouble getting it working. I want to change the Created By column to Anonymous. Basically I have this whole thing working in a console application, however, that will only change the Created By column names when the console application is executed.

I need it to change the Created By whenever a new item is added to the list. My code is below....how do I modify this to use in an EventReceiver project??? Since I already tell the EventReceiver project the URL I want the EventReceiver attached to, I'm not sure what I can remove from this code, right now it just doesn't do anything, no error and no changing of the Created By column when I debug.

   using (SPSite site = new SPSite("http://test-sharepoint/subsite/")) 
   { 
       using (SPWeb web = site.OpenWeb()) 
       { 
           SPList list = web.Lists["Posts"]; 
           SPListItemCollection listItemCollection = list.Items; 

           foreach (SPListItem listItem in listItemCollection) 
           { 
               SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");
                listItem["Author"] = userName; 
               listItem["Editor"] = userName; 

               listItem.Update(); 
           } 
           web.Update(); 
       } 
    } 

EDIT: Code is in ItemAdded method

EDIT #2: This is trying the same code except without the loop and using properties.ListItem, this was my attempt in a Event Recevier project but no luck. It just doesn't change the Created By field, or any field for that matter (I tried the Title as well)

       SPSite site = new SPSite("http://test-sharepoint/subsite/");
       SPWeb web = site.OpenWeb();
       SPFieldUserValue userName = new SPFieldUserValue(web, 22, "Anonymous");

       properties.ListItem["Author"] = userName;
       properties.ListItem["Editor"] = userName;
       properties.ListItem.Update();

*Also from my understanding the SPFieldUserValue will grab either a User or a SharePoint User Group (Permissions) so in my code, the 22 grabs the SharePoint User Group that I want and "Anonymous" is the user from that group...


EDIT #3: More progress, this code works without issues for a list, however, not for the Posts or Comments lists, for those it does not change the Created By field. Could it be because of the approve/reject for all items??? Whether approved orpending it still does not show annonymous, BUT like I mentioned, it works fine in a different list.

   public override void ItemAdded(SPItemEventProperties properties)
   {
       base.ItemAdded(properties);

       SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
       SPWeb web = site.OpenWeb();
       SPFieldUserValue userName = new SPFieldUserValue(web,22,"Anonymous");

       SPListItem currentItem = properties.ListItem;
       //currentItem["Title"] = userName;  //DateTime.Now.ToString();
       currentItem["Author"] = userName;
       currentItem["Editor"] = userName;
       currentItem.SystemUpdate();
   }

**EDIT #4: Alright I found my issue, when creating the project I chose Custom List as my list to attach to but I needed to choose Posts or Comments and now the above code works!!!

But now I have another problem, all posts on the blog are first submitted for approval...and due to this the event receiver doesn't seem to work for users other than the admin. It works fine for the admin account where I can just directly publish a post or comment but for a user with Contribute permissions whose posts are submitted for approval still shows their name on the Manage Posts page...what could I do about this? Any ideas?**

The code that works:

   public override void ItemAdded(SPItemEventProperties properties)
   {
       base.ItemAdded(properties);

       SPSite site = new SPSite("http://test-sharepoint/hr/blog/"); //SPContext.Current.Site;
       SPWeb web = site.OpenWeb();
       SPFieldUserValue userName = new SPFieldUserValue(web, 23, "Anonymous");

       SPListItem currentItem = properties.ListItem;
       currentItem["Author"] = userName;
       currentItem["Editor"] = userName;
       currentItem.SystemUpdate();
   }
danronmoon
  • 3,814
  • 5
  • 34
  • 56
Tudor Hofnar
  • 267
  • 2
  • 9
  • 20
  • Try to follow this guide to see if you have performed all the steps mentioned there: http://www.dotnetcurry.com/ShowArticle.aspx?ID=649. Another thing is that you could modify your code to use `ListItem` (or `ListItemId`) from `properties` parameter you should have available in `ItemAdded` event receiver. This way you could avoid updating all items each time. – Lukasz M Sep 20 '12 at 18:46
  • Thanks for the reply, I did actually try using properties.ListItem instead of iterating through all items but it still doesn't work. I will paste my code for that in the original post... – Tudor Hofnar Sep 20 '12 at 19:54
  • Is the code actually running, but not changing the fields' values and you can debug it? If so, verify with debugger if no exception is thrown and all the lines are run. I also suppose that `SPFieldUserValue` constructor with 3 parameters should take both id and value of the same lookup user to target. Try to change it into `SPFieldUserValue userName = new SPFieldUserValue(web, "Anonymous");`. Anonymous user should be added to SharePoint users directly (it probably won't work if you add only AD group he's in, but not the user himself). – Lukasz M Sep 20 '12 at 20:16
  • I've actually tried with the user as either added to SHarePoint users directly as well as within a SharePoint group but nothing. Funny thing is that if I just simply do this --properties.ListItem["Title"] = "Test Title"; properties.ListItem.Update();-- it works and changes the title, the problem is that it does not work for the Created By column of the list. The debugger goes through all lines I believe and no exceptions, however, I can't place breakpoints as they say no symbols loaded, and I've tried a lot of posts to fix that but nothing has worked. Any other ideas? – Tudor Hofnar Sep 20 '12 at 20:37
  • There are some other things I noticed in your code. that can cause the issue. First, use `properties.ListItem.SystemUpdate();` instead of `properties.ListItem.Update();` to update the item without affecting the columns updated by sharepoint automatically on item update. You can also try to update created by field this way: `properties.ListItem[SPBuiltInFieldId.Created_x0020_By] = userName`. Secondly, you can try to restart Sharepoint Timer Service (in windows services) and try to attach the debugger again to be able to put breakpoints. – Lukasz M Sep 20 '12 at 20:54
  • You can also open new site and web and get the item based on its ID from `properties`. If this won't work, try to invoke the code with elevated priviledges and More info here: http://msdn.microsoft.com/en-us/library./microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx – Lukasz M Sep 20 '12 at 21:05
  • Thanks again Lukasz but still nothing. Is it ok that I am using the EventReceiver project and using F5 to debug? I'm a beginner to EventReceiver so this is kind of a weird issue. When you say open a new site and web do you mean like what I am doing in my initial code above? Where I am using the 'using' statements? I have tried restarting the Timer Service before and no luck, just did it again and same thing. I'm starting to give up on EventReceivers, this is my second attempt at getting them to work and they only seem to want to if I change the titles of list items but not any other columns – Tudor Hofnar Sep 20 '12 at 22:37
  • Ok I have it working, somewhat...check my EDIT #3 above. It all works fine on a list, just not on the Blog Posts or Comments lists, any idea why those would be different? – Tudor Hofnar Sep 20 '12 at 23:37
  • I'm not sure why it's not working for other lists types, but you might want to try `this.EventFiringEnabled` as mentioned here: http://www.3guysonsharepoint.com/?p=568. In order to debug an event receiver deployed on a running SharePoint, you should attach to *w3wp.exe* process (in *Debug* menu, *Attach to process...* option). – Lukasz M Sep 21 '12 at 18:52
  • 1
    Thanks Lukasz! I have it working on the list now, but only if I am in the admin role. Since regular users need to submit a post for approval before its published, it will show their name when they post However, since I am an admin, I can automatically publish my post and the name does not show up, it says Anonymous. Is there something else I need to account for so that regular users will appear as Anonymous too? Any ideas for this? – Tudor Hofnar Sep 21 '12 at 20:36
  • Yes, attach an event receiver to `ItemUpdated` event and use the same code to set *Author* and *Editor* fields there (because probably item gets updated when it's published in order to change its status). In fact, setting *Editor* field in here may be enough as author should be already set by `ItemAdded` event handling method. – Lukasz M Sep 21 '12 at 20:46
  • Alright, getting closer...now having the code in ItemUpdated kind of works. So when a user submits a blog post it is not visible since it needs approval, BUT the approver can see who wrote the post which is not good, however, after he approves it it turns to a nnonymous. Is there an event that I should attach to so that the post is seen as Annonymous to the approver prior to him granting the approval? – Tudor Hofnar Sep 21 '12 at 22:03
  • I was thinking about the ItemAdding method but from what I've read online the properties.ListItem is blank...would ItemAdding be the solution? – Tudor Hofnar Sep 21 '12 at 22:43
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/17006/discussion-between-lukasz-m-and-tudor-hofnar) – Lukasz M Sep 22 '12 at 20:14

1 Answers1

0

In response to edit #4, when working with SharePoint, if code works when executed by the administrator account, but does not work when executed by a "normal" account, permissions are likely to blame.

See the answer to the question SharePoint/WSS: Modify “created by” field? for an example of an SPItemEventReceiver that modifies the Author field.

Note: Many SharePoint developers recommend against the use of RunWithElevatedPrivileges and suggest using impersonation instead. See my answer to the question In which situation use SPSecurity.RunWithElevatedPrivileges with superusertoken? for more details.

Community
  • 1
  • 1
Ryan Prechel
  • 6,592
  • 5
  • 23
  • 21