Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people, just like you, are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
Solved

event receiver errors to set list item permissions

Posted on 2010-11-26
11
1,709 Views
Last Modified: 2012-05-10
I am trying to compile this code and I'm getting 2 errors/warnings:

1 - the variable 'ex' is declared but never used

2-access to member 'microsoft.sharepoint.spitemeventreceiver.itemadding(microsoft.spitemeventproperties)' through a 'base' keyword from an anonymous method or iterator results in unverifiable code. consider moving the access to a helper method on the containing type.


using System;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace DemoAttendanceEventReceiver.EventReceiver1
{
    ///<summary>
    ///list item events
    ///</summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            try
            {
                //stop other events from firing while this method executes
                this.DisableEventFiring();
                //add code here
                //{
                base.ItemUpdating(properties);
                //}
                ///<summary>
                ///an item being addded
                ///</summary>
                //      public override void ItemAdded(SPItemEventProperties properties)
                //     {

                using (SPWeb contextWeb = properties.OpenWeb())
                {
                    SPUser me = contextWeb.CurrentUser;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(properties.SiteId))
                        {
                            SPWeb elevatedWeb = elevatedSite.OpenWeb(properties.RelativeWebUrl);

                            base.ItemAdding(properties);

                            properties.ListItem.BreakRoleInheritance(false);

                            SPRoleDefinition def = elevatedWeb.RoleDefinitions["FULL CONTROL"];

                            SPRoleAssignment role = new SPRoleAssignment(me.LoginName, me.Email, me.Name, me.Notes);
                            role.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role);

                            SPUser requestedUser = elevatedWeb.SiteUsers[properties.ListItem["Requested By"].ToString()];
                            SPRoleAssignment role2 = new SPRoleAssignment(requestedUser);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role2.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role2);

                            SPUser authorizedBy = elevatedWeb.SiteUsers[properties.ListItem["Authorized By"].ToString()];
                            SPRoleAssignment role3 = new SPRoleAssignment(authorizedBy);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role3.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role3);

                        }
                    });
                }
            }
            catch (Exception ex)
            { }
            finally
            {//re-enable event firing
                this.EnableEventFiring();
            }
        }
    }
}

Open in new window

0
Comment
Question by:sullisnyc44
  • 7
  • 4
11 Comments
 
LVL 3

Expert Comment

by:Nomoho
ID: 34225056
Remove your line: base.ItemAdding(properties);
this has nothing to do with your code, you already wrote base.ItemUpdating(properties); at the beginning which is at the right place.

If you where customizing the ItemAdding (and all other -ing events) event receiver, you should not call the base.Method in the SPSecurity.RunWithElevatedPrivileges() method (base.ItemAdding();). Just put it at the beginning of your method overrided for the native validation fields.)
0
 
LVL 3

Expert Comment

by:Nomoho
ID: 34225097
Hello again, for your 2nd warning (or first) you should use your ex variable:

here is an exemple, I write the error in the sharepoint logs files (because it is a sharepoint event and not a webpart):

catch (Exception ex)
 {
      Microsoft.Office.Server.Diagnostics.PortalLog.LogString("Une erreur est survenue. Source : {0}, message : {1}", "DemoAttendanceEventReceiver.EventReceiver1.EventReceiver1", ex.ToString();

 }

Open in new window


The logs can be found in the folder:
HardDisk:\Program files\Common files\microsoft shared\web server extensions\12\logs

In french, the folder Common files is called "fichiers communs", maybe you will find another name if you don't work with the english version of sharepoint
0
 

Author Comment

by:sullisnyc44
ID: 34242457
thanks so much.

now I'm getting this error:
Error      1      The type or namespace name 'Office' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)      C:\temp\DemoAttendanceEventReceiver\DemoAttendanceEventReceiver\Class1.cs      64      30      DemoAttendanceEventReceiver

I think my VS environment is lacking the proper sharepoint setup.

I cannot install the sharepont sdk - I keep getting an error because I'm running an x64 environment/server
0
PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

 
LVL 3

Expert Comment

by:Nomoho
ID: 34242833
Hello,

Visual Studio does not add sharepoint's references in projects by default, you must manually add this one:
right click on reference, and choose Microsoft.Office.Server (or find it in the computer where sharepoint is installed:
"C:\program files\common files\microsoft shared\web server extensions\12\isapi\microsoft.office.server.dll"
0
 

Author Comment

by:sullisnyc44
ID: 34248492
ok. but shouldn't I be able to create a custom workflow using visual studio?

I do not have any of the sharepoint content specific project types listed when I open visual studio.
0
 

Author Comment

by:sullisnyc44
ID: 34248502
oops - that was an answer to a different question
0
 

Author Comment

by:sullisnyc44
ID: 34248630
Thanks so much - that seems to have rebuilt ok.

is applying [Full Control] to this item what I should be doing? Should it be a lesser permission level? Just to edit or something?  Just curious

Also I need to apply item permissions to a group I created on the site called "Attendance Managers" they need to be able to see everything.

Once I have this built, I will need to deploy it (GAC the dll, correct?) I would appreciate some guidance as well.

I will repost my code:

using System;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace DemoAttendanceEventReceiver.EventReceiver1
{
    ///<summary>
    ///list item events
    ///</summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            try
            {
                //stop other events from firing while this method executes
                this.DisableEventFiring();
                //add code here
                //{
                base.ItemUpdating(properties);
                //}
                ///<summary>
                ///an item being addded
                ///</summary>
                //      public override void ItemAdded(SPItemEventProperties properties)
                //     {

                using (SPWeb contextWeb = properties.OpenWeb())
                {
                    SPUser me = contextWeb.CurrentUser;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(properties.SiteId))
                        {
                            SPWeb elevatedWeb = elevatedSite.OpenWeb(properties.RelativeWebUrl);

                        
                            properties.ListItem.BreakRoleInheritance(false);

                            SPRoleDefinition def = elevatedWeb.RoleDefinitions["FULL CONTROL"];

                            SPRoleAssignment role = new SPRoleAssignment(me.LoginName, me.Email, me.Name, me.Notes);
                            role.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role);

                            SPUser requestedUser = elevatedWeb.SiteUsers[properties.ListItem["Requested By"].ToString()];
                            SPRoleAssignment role2 = new SPRoleAssignment(requestedUser);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role2.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role2);

                            SPUser authorizedBy = elevatedWeb.SiteUsers[properties.ListItem["Authorized By"].ToString()];
                            SPRoleAssignment role3 = new SPRoleAssignment(authorizedBy);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role3.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role3);

                        }
                    });
                }
            }
            catch (Exception ex)
                {
                  Microsoft.Office.Server.Diagnostics.PortalLog.LogString("An error has occurred. Source : {0}, message : {1}", "DemoAttendanceEventReceiver.EventReceiver1.EventReceiver1", ex.ToString());
                }

            finally
            {//re-enable event firing
                this.EnableEventFiring();
            }
        }
    }
}

Open in new window

0
 
LVL 3

Accepted Solution

by:
Nomoho earned 500 total points
ID: 34249342
Hello, it depends on what you need to do.
All you can do manually in sharepoint can be done by code.

You can follow this guide to deploy your event handler:
http://www.mscommunity.ba/blogs/quarks_bar/archive/2009/03/12/develop-and-deploy-a-sharepoint-event-receiver-from-the-scratch.aspx

- before breaking the role inheritance, add the following test:
if(!properties.ListItem.HasUniqueRoleAssignments) otherwise you will get an exception.
(you can resetroleinheritance for example)

- you must reopen the SPListItem and not reuse the properties.ListItem when using RunWithElevatedProvileges method
You can follow the example of the guide:
SPSite elevatedSite = new SPSite(sharepointItem.ParentList.parentWeb.Site.ID);                     
SPWeb elevatedWeb = elevatedSite.OpenWeb(sharepointItem.ParentList.ParentWeb.ID);  
SPList elevatedList = elevatedWeb.Lists[parentList.ID];  
//get the file with the privileged permissions  
SPListItem elevatedItem = elevatedList.Items.GetItemById(properties.ListItem.ID);
/* and then do your elevated action */

Open in new window

0
 

Author Comment

by:sullisnyc44
ID: 34249672
how do I set permissions for the group 'Attendance Managers'? And I think I want to set requester to read once it's submitted, authorized by to edit and the group to full control.

here is my updated code:
 
using System;
using System.Security.Permissions;
using Microsoft.SharePoint;

namespace DemoAttendanceEventReceiver.EventReceiver1
{
    ///<summary>
    ///list item events
    ///</summary>
    public class EventReceiver1 : SPItemEventReceiver
    {
        public override void ItemUpdating(SPItemEventProperties properties)
        {
            try
            {
                //stop other events from firing while this method executes
                this.DisableEventFiring();
                //add code here
                //{
                base.ItemUpdating(properties);
                //}
                ///<summary>
                ///an item being addded
                ///</summary>
                //      public override void ItemAdded(SPItemEventProperties properties)
                //     {

                using (SPWeb contextWeb = properties.OpenWeb())
                {
                    SPUser me = contextWeb.CurrentUser;
                    SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite elevatedSite = new SPSite(properties.SiteId))
                        {
                            SPWeb elevatedWeb = elevatedSite.OpenWeb(properties.RelativeWebUrl);

                            if(!properties.ListItem.HasUniqueRoleAssignments) 
                                //otherwise you will get an exception. (you can resetroleinheritance for example)
                        
                            properties.ListItem.BreakRoleInheritance(false);

                        SPSite elevatedSite = new SPSite(sharepointItem.ParentList.parentWeb.Site.ID);
                        SPWeb elevatedWeb = elevatedSite.OpenWeb(sharepointItem.ParentList.ParentWeb.ID);
                        SPList elevatedList = elevatedWeb.Lists[parentList.ID];
                        //get the file with the privileged permissions  
                        SPListItem elevatedItem = elevatedList.Items.GetItemById(properties.ListItem.ID);
                        /* and then do your elevated action */

                            SPRoleDefinition def = elevatedWeb.RoleDefinitions["FULL CONTROL"];

                            SPRoleAssignment role = new SPRoleAssignment(me.LoginName, me.Email, me.Name, me.Notes);
                            role.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role);

                            SPUser requestedUser = elevatedWeb.SiteUsers[properties.ListItem["Requested By"].ToString()];
                            SPRoleAssignment role2 = new SPRoleAssignment(requestedUser);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role2.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role2);

                            SPUser authorizedBy = elevatedWeb.SiteUsers[properties.ListItem["Authorized By"].ToString()];
                            SPRoleAssignment role3 = new SPRoleAssignment(authorizedBy);
                            def = elevatedWeb.RoleDefinitions["FULL CONTROL"];
                            role3.RoleDefinitionBindings.Add(def);
                            properties.ListItem.RoleAssignments.Add(role3);

                        }
                    });
                }
            }
            catch (Exception ex)
                {
                  Microsoft.Office.Server.Diagnostics.PortalLog.LogString("An error has occurred. Source : {0}, message : {1}", "DemoAttendanceEventReceiver.EventReceiver1.EventReceiver1", ex.ToString());
                }

            finally
            {//re-enable event firing
                this.EnableEventFiring();
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:sullisnyc44
ID: 34249808
ALSO - my other issue is how do I create a unique GUID when I can't install the sharepoint project sdk extensions on a x64 machine?
0
 

Author Comment

by:sullisnyc44
ID: 34260598
FYI You can use this http://sptemplateland.codeplex.com/
 
VS2005 didn’t come bundled with SP templates
0

Featured Post

Ransomware: The New Cyber Threat & How to Stop It

This infographic explains ransomware, type of malware that blocks access to your files or your systems and holds them hostage until a ransom is paid. It also examines the different types of ransomware and explains what you can do to thwart this sinister online threat.  

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I recently came across an issue with a MOSS 2007 deployment where access into some sub-sites were denied, even for the MOSS farm administrators. A bit of background to the setup of this MOSS farm; this was a three server setup, consisting of a fr…
There is one common problem that all we SharePoint developers share: custom solution deployment. This topic can't be covered fully in this short article, so all I want to do in this one is to review it from a development-to-operations perspectiv…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

856 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question