Showing posts with label elevated privileges. Show all posts
Showing posts with label elevated privileges. Show all posts

Saturday, 16 June 2012

An Addendum to the Last Post: Only Works on Document Libraries

I should have noted this at the time, but I was not aware of it. It was only when I tried to do the same thing with an SPList object that I ran into trouble.

This is why - BeforeProperties and AfterProperties do not work on a list

So I ended up having to create a Just Updated flag for the user to click when they want to send an email. Just before ending the event handler, it sets that flag back to false. Yet another hack to make up for SharePoint 2007's "by design behaviour" (sigh)

So if using the code in the previous post - document library only, lads. Sorry.

Saturday, 19 May 2012

How to use BeforeProperties and AfterProperties in an RunWithElevatedPrivileges block

I came up against a tricky problem this week when I wrote code that would not work for a non-admin account and needed to wrap it up in a privilege block (note: I am not using RunWithElevatedPrivileges as it's dodgy, see earlier blog entries on the subject, but it's along similar lines.)

As explained before, an override method for an SPItemEventReceiver object always passes in the properties of the list item as a parameter. This allows for manipulation of the object. 

But we also know that the properties object cannot be used within the SPSecurity.RunWithElevatedPrivileges block as an entirely new site object needs to be created with separate web, list and item objects created with it. This is fine usually, but what if we need to compare the value of a column before being updated with the results after it has been changed? Usually we would be able to avail of properties.BeforeProperties["Fieldname"] and properties.AfterProperties["Fieldname"] and compare the two, but our new SPListItem object inside the privilege block does not possess either of these attributes. So, what to do?

The solution is below - important lines in bold:

SPItemEventDataCollection before = properties.BeforeProperties;
SPItemEventDataCollection after = properties.AfterProperties;
Guid siteID = properties.SiteId;
Guid webID = properties.ListItem.Web.ID;               
//this is for getting the user Token to log in as system
SPSite tempSite = new SPSite(siteID);
SPUserToken sysToken = tempSite.SystemAccount.UserToken;
//need to dump this as not declared in a using block
tempSite.Dispose();
//start the privilege block
using (SPSite site = new SPSite(siteID, sysToken))
{
    using (SPWeb web = site.OpenWeb(webID))
    {
        if (before["FieldName"].ToString() != after["FieldName"].ToString())
        { someBooleanVariable = true; }
        //do work
    }

}

Wednesday, 18 April 2012

SPUtility.RunWithElevatedPrivileges Fails with getting SPUser from groups

Using SPUtility.RunWithElevatedPrivileges fails when trying to get SPUser objects from groups. It worked when I removed the privilege block, but this was not practical for non-admin users. The code below worked perfectly for me:


            Guid groupWebID = SPContext.Current.Web.ID;
            Guid groupSiteID = SPContext.Current.Site.ID;
            SPUserToken sysToken = SPContext.Current.Site.SystemAccount.UserToken;
 
            using (SPSite groupSite = new SPSite(groupSiteID, sysToken))
            {
                using (SPWeb groupWeb = groupSite.OpenWeb(groupWebID))
                {
 
                    SPGroup group = groupWeb.Groups["My Group"];
                    foreach (SPUser user in group.Users)
                    {
                        AllUsers.Items.Add(user.Email);
                    }
 
                }
            }

Saturday, 22 October 2011

Copying File from one Doc Library to Another - Problem Solved

I forgot to update about this. I solved that problem that had me removing several hairs at the follicle.

In order to copy the file from one place to the other, I had to create a using block for the source site and then the target site. Thus (note that this was in a separate class file from the event handler so I did not have access to the properties object and had to pass the IDs in as parameters):

public static void CopyFile (Guid listID, int itemID, string sourceUrl, string targetUrl, Guid targetListID)
{
     try
     {     
         using (SPSite sourcesite = new SPSite(sourceUrl))
         {
             using (SPWeb sourceWeb = sourceSite.OpenWeb())
             {
                  SPList list = web.Lists[listID];
                  SPListItem item = list.Items[itemID];
                  SPFile file = item.File;
                  //Here was where my error started
                  //I instantiated the file out of scope
                  byte[] binFile = file.OpenBinary();
                  
                  //OPEN TARGET SITE AND WEB HERE
                  using (SPSite targetSite = new SPSite(targetUrl))
                  {
                       using (SPWeb targetWeb = targetSite.OpenWeb())
                       {


                           //get the target list
                           //create SPFolder object
                           //this is like a SPList object
                           //but concerned only with the copying of files
                           folder.Files.Add(binFile);
                       }
                  }

     
             }
         }
     }
}


My error appeared to be where I declared the binary array. When I declared it within scope of the target site everything appeared to work perfectly, even though I was just streaming the file on the other site like before. I have no idea why a binary stream should lose scope, it's only an array, but I could not make it work for a non-admin user.


Please note that I haven't put in the target file copying code in detail as I am working from memory here - but it needs to be done using the SPFolder object. The SPFolder objects points to the document library just like the SPList object, but only deals with the files. Because the SPList object only handles stuff on lists. It doesn't do files. Jobsworth of an object!

Saturday, 15 October 2011

Extending and Overriding my own Wits

Well I am making some progress on that non-event from hell detailed in my last post. First I commented out everything in my event handler and put in some innocuous line like:

properties.ListItem("Title") = "Changed by the event handler";
properties.ListItem.Update();


And that worked. So my fears that the event handling code was not invoked at all when logging in as a non-admin, nothing special user were unfounded.


So, I commented back in the error handling code. Nothing happened. OK, so the error handler doesn't work. At least that explains why I wasn't getting any feedback. Strange given that the test user had access to the folders but not crucial but will worry about it later.


So what did I do then? Moved the comment /* indicator down a few painstaking lines each time, compiled, GACed, IISResetted and ran. Used the Title field as my error handler! Bit by bit by bit. The code had no problem calling the web service or using the impersonator token. What it did not want to do was copy the binarily streamed file (is that valid syntax? Probably not, but if the method of streaming a file is binary, then surely it is binarily streamed, no? Anyway.) It streamed it fine, even modified as Mr High-Up Impersonated User just as I asked it to with the SPUserToken. But it won't copy it.


I suspect I will have to put a Special Snowflake sodding privilege block around that operation all by itself or else it will sulk forever. So, will I succeed. Tune in...to be continued in our next. If you haven't died of boredom first...

Thursday, 13 October 2011

At My Wit's End

I cannot get an event handler to fire at all for a non-admin user.

I have error tracking enabled  and on. It writes to a file. I have enabled permissions on the file folder. I have instructed it to throw an error and write back. When I log in as myself, it does all these things. I am a member of the owner group of the site.

The event handler copies the document library entry, including the document, to another document library on a different site, in a different site collection. It does various other things as well, but that's later on. When I log in as myself, all this works fine. When I log in as the test user, nothing happens. When I instrument the code, nothing happens. I have tried elevated privilege blocks in the code, paying attention to the declaration of the site instances within the block as required, but given that the event handling mechanism steadfastly refuses to even CALL the code for that user, I'm inclined to believe I could put "rhubarb rhubarb rhubarb" in there and it wouldn't make any difference. There should be no reason why I cannot manipulate the properties object.

I made the test user King of Everything. Full control on the source document library, full control on the site - I even made the blasted thing a site collection administrator! (this on the test machine, of course) Test user had more privileges than I did. Plus I removed my login from the site collection admin list.

Didn't make a lick of difference. And then when an actual user tried to log in and nothing happened, I knew this was going to be trouble. I have to confess to being utterly stumped as to why it doesn't call the code AT ALL. I would understand if it gave an error due to privilege - I even managed to get past one of those in one of the other issues I had with the EnsureUser method - but it's not even bothering to invoke the component. Works fine when I log in as myself, or log in as super user.

Any ideas? Losing the will to live over here! :)

Susan

Tuesday, 11 October 2011

RunWithElevatedPrivileges - another encounter and something you should know

I have been previously complaining about SPSecurity.RunWithElevatedPrivileges as being a load of tosh. I might have been a tad harsh as I employed it just yesterday and got it working - almost.

I needed to do two things - copy over a file and update fields. The file copy bit worked well - I had an impersonation block for that - but the bit where a non-admin user updates the fields was, alas, a bit of a dud. Until I put the field update section into a RunWithElevatedPrivilege delegate block and all looked fine.

But in addition to the native data types I was using, I also had four user fields I was obtaining from a web service off somewhere else. In order to update these, I had to get the username and call the EnsureUser method on my elevated privileges SPWeb object. This was still failing, even within the privileged user wrapper. It either said I couldn't find the user or that I wasn't allowed to get it. This even though I had, as Google's wisdom advised, wrapped the EnsureUser method call with AllowUnsafeUpdates = true on either side.

Then I commented out the web.AllowUnsafeUpdates = true line and its corresponding AllowUnsafeUpdates=false on the other side. Ran it again. Worked perfectly. I had been trying this for days!

So, you heard it here first - when using the delegate, try not setting the AllowUnsafeUpdates property. And definitely don't set it on the Site object or the whole thing will break completely. SharePoint seems perfectly capable of deciding for itself, in this case, whether the update is safe or not.

Saturday, 24 September 2011

SPSecurity.RunWithElevatedPrivileges Doesn't Work: The Pleasures and Sorrows of the Non-Admin User

I blogged the last time about deploying event handlers using features and components. So your event handler is sitting there, ready to fire. You update, add, or delete or whatever it is you want to do. Nothing happens. You have a look at the feature to check all is well. No typos? No copy-and-paste issues with the component name? Got the right list template ID? Instrumented your error code and recording nothing?

Then you look at the top right corner of your site and see the tell-tale message "Logged In As Serf Minion". You log out and log back in as "God of All Admins" and hey presto, everything works fine. Only problem being that you don't want every user in the damn system having admin privileges on this site or list or document library because - well you just don't. That way madness lies.

So what do you do?

Well I had this problem just a week or so ago. Since I am a novice, I did a bit of googling and came across the function SPSecurity.RunWithElevatedPrivileges. You pass in a delegate, which is a fancy word for an entire wodge of code, and all that code runs as if you're logged in as an admin. Hurrah, thought I, my problem is solved. And gentle reader, I took care to read the warnings. It is bad practice to instantiate your SPSite and SPWeb objects outside the RunWithElevatedPrivileges block. Why? Well, what is the point of creating the admin code block when you already have your site object instantiated as Serf Minion when firing the event handler? Bit of a waste of time that.

So what you're supposed to do is get your site Guid from your existing properties object and then create your site within the delegate block, treating the whole thing like a bubble. Thusly:


Guid siteID = properties.SiteID;
Guid webID = properties.ListItem.Web.ID;


SPSecurity.RunWithElevatedPrivileges(delegate() {
//create site
          using (SPSite site = new SPSite(siteID))
          {
              using (SPWeb web = site.OpenWeb(webID))
                   {
                         //insert godly admin code here with no reference to properties object
                   }
          });

So I tried that, fair readers, or something very similar. Guess what? My code, which had been failing for non-admin users, now failed for everybody. I tried everything in the book to make it work. I could not figure out what the hell I was doing wrong! Then a thought suddenly struck me: maybe this is just a load of crap. So I googled "Run With Elevated Privileges doesn't work" and came straight back with this link from a Mr Ishai Sagi and all I can say it, I wish to God I'd found it sooner. I googled further to find the code somebody had written to create an Impersonation class (Lesson no. 1 - NEVER code something before checking someone else has done it on the internet.) Replaced the settings with my own server settings, ran the thing and HEY PRESTO IT WORKED.

So lesson learned: always test as non-admin and keep in mind non-admin privileges when writing your event handler. And the hell with RunWithElevatedPrivileges where event handlers are concerned. Sorry Mr Microsoft guys, I just couldn't make it work ::sniff::