The best overloaded method match for ‘Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(…) has some invalid arguments

I came across a issue today why attempting to use SPSecurity.RunWithElevatedPrivileges in code. The two exceptions I got when I tried building the solution was:

The best overloaded method match for ‘Microsoft.SharePoint.RunWithElevatedPrivileges(Microsoft.SharePoint.SPSecurity.CodeToRunElevated)’ has some invalid arugments

Argument ‘1’: cannot convert from ‘anonymous method’ to ‘Microsoft.SharePoint.SPSecurity.CodeToRunElevated’

And the code was

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(Web.ParentWeb.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        if (web != null)
                        {
                            String groupName = DateTime.Now() + ” Contributors”;
                           return  Groups.Get(web, groupName);

                        }                       
                    }
                }
            });
            return null;

All the two errors were trying to tell me in ‘another language was that I cannot have ‘return’ calls in the code that is being elevated.  So I moved the ‘return’ calls outside of the code that was being run under elevated privileges.

  Group group = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(Web.ParentWeb.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {

                        if (web != null)
                        {
                            String groupName = DateTime.Now() + ” Contributors”;
                            group = Groups.Get(web, groupName);

                        }                       
                    }
                }
            });
            return group;               

 After doing this, the code compiled.

Done.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: