Tuesday, 24 June 2014

SharePoint 2010: Why does my RunWithElevatedPrivileges not pick up the context of the Application Pool user?

It is important to remember that RunWithElevatedPrivileges requires its own SPWeb. If you reuse a existing SPWeb, you won't run elevated, but with the initial context.

For Example, the following function is intended to perform some actions on the sub sites for the given site. The access requires elevated permissions:

This function will not work:

private void DoStuff (SPWeb web)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
foreach (SPWeb w in web.Webs)
// Still running under logged in user credential
}
});
}

but this will:

private void DoStuffProperly(SPWeb web)
{
SPSecurity.RunWithElevatedPrivileges(() =>
{
using (SPSite site = new SPSite(web.Url))
{
using (SPWeb w = site.OpenWeb())
{
// Running under the application pool credential
}
}
});
}

Thursday, 19 June 2014

SharePoint 2010: Why is my name displaying as DOMAIN\LOGIN instead of Displayname?

My development environment was displaying my name as 'DOMAIN\LOGIN' instead of 'DisplayName'. I found the solution in this post - a simple one-line PowerShell command:

Get-SPUser -Web http://myweb.com | Set-SPUser -SyncFromAD

Monday, 9 June 2014

SharePoint 2010: How do I load a picture and meta data to an asset library?

I recently had to load some seed data for a SharePoint site that required the population of some images into an asset library. After a lot of playing and experimenting, I eventually settled on the pattern of

1. Add the files to an image folder in the Style Library
2. Reading in the source file into a byte array
3. then loading the array into a new file in the target location.

Its a little convoluted, but it was the only solution that met my requirement.

I then populated a dictionary with a name/value pair that mapped to the columns in my content type.

Here are the methods I used:

     public void UploadFile(SPWeb webParam, string fileUrl, SPList list, Dictionary<string, string> parameters)
        {
            try
            {
             
                using (SPSite site = new SPSite(webParam.Url))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        //SPList list = web.Lists.TryGetList(listName);

                        string urlOfFile = string.Format("{0}/{1}", list.RootFolder.ServerRelativeUrl, Path.GetFileName(fileUrl));
                        string title = Path.GetFileName(fileUrl).Substring(0, Path.GetFileName(fileUrl).IndexOf("."));

                        using (Stream file = (new WebClient() { Credentials = CredentialCache.DefaultCredentials }).OpenRead(fileUrl))
                        {
                            byte[] b = ReadFully(file);

                            using (MemoryStream DocumentStream = new MemoryStream())
                            {
                                using (StreamWriter writer = new StreamWriter(DocumentStream))
                                {
                                    writer.Write(b);
                                    writer.Flush();
                                    SPFile file2 = list.RootFolder.Files.Add(Path.GetFileName(fileUrl), DocumentStream, true);
                                    file2.Update();
                                    list.Update();
                                }
                            }
                        }

                        SPListItem uploadedFile = web.GetListItem(urlOfFile);
                        if (uploadedFile != null)
                        {
                            // for the hyperlink
                            SPFieldUrlValue urlValue = new SPFieldUrlValue();
                            urlValue.Description = title;
                            urlValue.Url = fileUrl;
                            uploadedFile["AlternateThumbnailUrl"] = urlValue;

                            foreach (var i in parameters)
                            {
                                uploadedFile[i.Key] = i.Value;
                            }

                            uploadedFile.Update();
                        }
                        else throw new Exception("Something bad happened!");
                    }
                }

            }
            catch (Exception ex)
            {
                // handle exception here
            }
        }

        public static byte[] ReadFully(Stream input)
        {
            byte[] buffer = new byte[16 * 1024];
            using (MemoryStream ms = new MemoryStream())
            {
                int read;
                while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
                {
                    ms.Write(buffer, 0, read);
                }
                return ms.ToArray();
            }
        }

And here is the invocation:

string sourceFile = "http://SiteCollection/Site/Style%20Library/myimage.png";

Dictionary<string, string> parameters = new Dictionary<string,string>();
parameters.Add("Title", "My Test Title");
parameters.Add("MyCustomColumn", "Foo");

UploadFile(web, sourceFile, web.Lists["MyList"], parameters);