Add Field with XML

SharePoint Short #21

A quick short today 🙂

Instead of adding new fields to a content type or list creating the object (SPFieldText, etc.) and adding it, simply pass the XML definition for whatever field you are looking to create into the AddFieldAsXml method of the Fields collection.

public void AddFieldToList(SPList list, string xmlDefinition)
    string fieldName = list.Fields.AddFieldAsXml(xmlDefinition);
    SPField newField = list.Fields.GetField(fieldName);
    // Do whatever you need to with the new field
    // and then update it.

The xmlDefinition is simply a copy of the Field tag, for example from a content type definition.

Run With Elevated Privilges

SharePoint Short #20

Instead of explicitly wrapping code in a RunWithElevatedPrivileges block, it’s better to first check if the user has sufficient privileges and only elevate when they don’t.

Instead of:

SPSecurity.RunWithElevatedPrivileges(() =>
        // elevated code...

Do this:

public void RunWithElevatedPrivileges(SPWeb web, SPSecurity.CodeToRunElevated elevatedCode)
    if (web.CurrentUser.IsSiteAdmin)
public void TestMethod()
    RunWithElevatedPrivileges(SPContext.Current.Web, ()=>
            // elevated code...

This way the code will only be encapsulated in the elevated block when the user does not have adequate permissions and you’ll help to increase the performance of your code by avoiding executing unnecessary code.

You could further extend this by only opening the SPSite\SPWeb object when elevating the code.


SharePoint Short #19

When implementing your own Custom_AddDocLibMenuItems, which allows you to add custom menu items to the ECB of SharePoint items, remember to check for other implementations of this method before your own version.

For example:

function YourImplementationOf_AddDocLibMenuItems(m, ctx, url) {
    if (typeof Custom_AddDocLibMenuItems != 'undefined') {
        var CurrentCustom_AddDocLibMenuItems = Custom_AddDocLibMenuItems;
    Custom_AddDocLibMenuItems = function (m, ctx, url) {
        // Custom code to add ECB menu items....
        if (CurrentCustom_AddDocLibMenuItems === undefined) {
            return false;
        return CurrentCustom_AddDocLibMenuItems(m, ctx, url);

By checking if Custom_AddDocLibMenuItems is not Undefined and referencing the method at the start of your YourImplementationOf_AddDocLibMenuItems method, you are able to ensure any other implementation of this method is called once you are finished with it.

To have your YourImplementationOf_AddDocLibMenuItems method initiated when a page loads, add the following:

$(document).ready(function () {

Here we use jQuery’s ready function, to add the custom method YourImplementationOf_AddDocLibMenuItems to a SharePoint array that is processed when the DOM is loaded. What this means is that the method will be executed when the page loads and subsequently the custom overload of Custom_AddDocLibMenuItems is called whenever the ECB is opened.

Loopback Check and 401.1 Error

SharePoint Short #18

If you’re developing a web service for SharePoint, or trying to access one of the SharePoint web services, through server code and get a 401.1 Unauthorized exception, it’s worth checking if the status of the loopback check, especially if you’re using a host name for the site.

Since Windows 2003 (SP1) a loopback security check was added. The purpose of this check is to prevent access to the web application if there is an attempt to access it from the same server hosting the site, using a fully qualified domain name or host name.

If you’re getting this exception on a dev\test environment, the simplest solution is to disable the loopback check. Do this by opening the registry editor and navigate to the following key:


From there, right click the LSA folder and add a new DWORD value called DisableLoopbackCheck. Set the value to 1 and then reboot the server. Do this for all Web Front Ends in the farm.

If, on the other hand, this is happening on a production environment, do not disable the loopback check as this will remove a security check that may compromise your environment. Instead, add the host names that should bypass this check by adding another key to the registry:


Right click the MSV1_0 folder and add a new Multi-String value called BackConnectionHostNames. Set the value to the host name you want to exclude. If there are more than one, add them on separate lines and do not include the protocol, just the host name. Reboot the server and apply this to all Web Front Ends in the farm.

For the last configuration, you could define a group policy to apply this across multiple servers, but I’ll leave that for another day!

Create Zip File

SharePoint Short #17

Not so much a SharePoint post, but can be used in a SharePoint project, so counts for me 🙂

Using the WindowsBase assembly provides access to the System.IO.Packaging namespace and the PackagePart class.

Using this class to create an in memory zip file containing one or more files is pretty straight forward:

public byte[] GetZipData()
    byte[] data;
    using (MemoryStream stream = new MemoryStream())
        using (Package package = ZipPackage.Open(stream, FileMode.Create, FileAccess.ReadWrite))
            // Wrap the rest of the using block in a for loop to iterate over files you want to
            // include in the package, this example only adds a single file.
            // Create the file to include in the zip
            Uri uri = PackUriHelper.CreatePartUri(new Uri("FileToIncludeInZip.txt", UriKind.Relative));
            PackagePart packagePart = package.CreatePart(uri, MediaTypeNames.Application.Octet, CompressionOption.Normal);
            using (Stream packagePartStream = packagePart.GetStream())
                // Get content for file as byte array.
                byte[] packagePartData = Encoding.UTF8.GetBytes("content to write to FileToIncludeInZip.txt file");
                // Commit to package
                packagePartStream.Write(packagePartData, 0, packagePartData.Length);
        // Write stream content to data byte array
        data = new byte[stream.Length];
        stream.Position = 0;
        stream.Read(data, 0, Convert.ToInt32(stream.Length));
    return data;
// Code in you aspx page, WebPart, control, etc. :
byte[] data = GetZipData();
Page.Response.Buffer = true;
Page.Response.AddHeader("Content-Length", data.Length.ToString());
Page.Response.ContentType = "application/zip";
Page.Response.AppendHeader("Content-Disposition", "attachment;");

Get every new post delivered to your Inbox

Join other followers: