If you’re doing any sort of custom development within the MOSS framework, there might come a time when you’ll need to execute your code with elevated permissions. Meaning, instead of your code running under the context of the current user, you’ll want to run it using an account with a higher level of access.

Within MOSS, there is a method that will do the trick. The RunWithElevatedPrivileges method will run under the context of the Application Pool Identity account.

As an example: The code below was taken from an application page I developed recently. When running this code using my credentials, it executed without trouble. Once logged in as a user with Contribute access, I was running into an Access Denied SharePoint error.

1
2
3
4
5
void DoSubmit(object sender, EventArgs e)
{
    SPSite site = SPControl.GetContextSite(Context);
    SPWebCollection webs = site.AllWebs;
}

My next step was to attempt to run the DoSubmit method using elevated privileges as follows.

1
2
3
4
5
6
7
8
9
10
void DoSubmit(object sender, EventArgs e)
{
    SPSecurity.RunWithElevatedPrivileges(GetExpiredPages);
}
 
void GetExpiredPages()
{
    SPSite site = SPControl.GetContextSite(Context);
    SPWebCollection webs = site.AllWebs;
}

The above code was still producing an Access Denied error. It took me a moment to realize what I was doing wrong. The trick was that I needed to create a NEW SPSite object INSIDE the function that I am trying to run using elevated privileges. If I don’t recreate the SPSite object, I’ll essentially still be executing my code under the context of the current user.

1
2
3
4
5
void GetExpiredPages()
{
    SPSite site = new SPSite(SPControl.GetContextSite(Context).ID);
    SPWebCollection webs = site.AllWebs;
}
Tagged with:  

In this example, I will focus specifically on a scenario where I had to write code that would overwrite the CustomQuickAccess.xml file located within the masterpage gallery.

Typically, up until this point, I had been dealing with simply uploading new files to a SharePoint library when a feature was activated. Simple enough, however, what happens if you’re trying to overwrite a file that already exists? I’ve attached the file to this post here for reference, but let’s go over the basics for doing something of this sort.

  1. The first step was to create a new feature and overwrite the FeatureActivated method. I’ll assume you’re familiar with this already, but if not, feel free to drop me a note and I’ll assist where I can.
  2. The code inside of the FeatureActivated method is pretty straightforward. Create a web object, declare a variable to store the file system path where the feature was activated so that we can grab the file we want to overwrite with and finally, call another method to do the file overwriting, with elevated privileges.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    
    override void FeatureActivated(SPFeatureReceiverProperties properties)
     
    {
     
    WriteMessageToEventLog(“Feature Activated”);
     
    try
     
    {
     
    web = (SPWeb)properties.Feature.Parent;
     
    // set the directory path on the file system where the feature was activated
     
    directoryPath = properties.Definition.RootDirectory;
     
    // run with elevated permissions so we can overwrite the file
     
    SPSecurity.RunWithElevatedPrivileges(OverwriteFile);
     
    }
     
    catch (Exception ex)
     
    {
     
    WriteMessageToEventLog(ex.ToString());
     
    }
     
    }
  3. Now let’s look at the OverwriteFile method. What we’re doing here is reading the contents of the file into a byte array and uploading that file into the Editing Menu folder, specifiying that we want to overwrite the file.
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    
    public void OverwriteFile()
     
    {
     
    // create a new site object so that elevation works properly
     
    SPSite site = new SPSite(web.Site.ID);
     
    // copy to location
     
    string url = null;
     
    // get the url to the local file
     
    string[] localFile = System.IO.Directory.GetFiles(directoryPath, ”*.xml”, System.IO.SearchOption.TopDirectoryOnly);
     
    // define a fstream object so we can read the contents of the file into a byte array
     
    FileStream fstream = File.OpenRead(localFile[0]);
     
    byte[] contents = new byte[fstream.Length];
     
    fstream.Read(contents, 0, (int)fstream.Length);
     
    fstream.Close();
     
    // get a handle to the master page gallery
     
    SPList masterPageGallery = site.OpenWeb().Lists[“Master Page Gallery”];
     
    // get a handle to the folder we want to upload the file to
     
    SPFolder editingMenuFolder = masterPageGallery.RootFolder.SubFolders[“Editing Menu”];
     
    SPFile customQuickAccessFile = editingMenuFolder.Files[“CustomQuickAccess.xml”];
     
    // build the destination copy url
     
    url = site.Url + ”/” + editingMenuFolder.Url + > ”/”;
     
    // check out the file, replace it with the modified one, and check it back in, publish and approve
     
    customQuickAccessFile.CheckOut();
     
    customQuickAccessFile.CopyTo(url + “CustomQuickAccess_Original.xml”, true);
     
    WriteMessageToEventLog(editingMenuFolder.ServerRelativeUrl);
     
    WriteMessageToEventLog(editingMenuFolder.Url);
     
    // check in new file
     
    customQuickAccessFile = editingMenuFolder.Files.Add(url + “CustomQuickAccess.xml”, contents, true);
     
    customQuickAccessFile.CheckIn(“File over-written by activiating the Published Page View Feature”);
     
    customQuickAccessFile.Publish(“File published by activating the Published Page View Feature”);
     
    customQuickAccessFile.Approve(“Approved by Published Page View Feature”);
     
    site.Close();
     
    }
Tagged with:  

If you’re working with custom workflows, and you’ve run into a scenario where you have the login name of the user in the form of domain\juser but would like to see a more user friendly display name like Joe User then here’s how you do it:

What I usually do is create an SPUser object and then use the Name property to get at the display name of the user. Once I’ve got an SPUser object created, I have access to several different properties and methods. You can view the full list on msdn. The SiteUsers property will take in a string containing the login name of the user

SPUser user = workflowProperties.web.SiteUsers[string loginName];
string fullName = user.Name;
Tagged with: