Thursday, January 27, 2011

Programatically create Power Pivot Gallery

Have you ever tried creating Power Pivot Gallery?

It isn't straight forward.You cannot just use the 
web. ListTemplates["ReportGalleryLibrary"]. I found that the ListTemplates had the required template but it wasn't accepting the Internal name of ReportGalleryLibrary.

The error I was getting was "Value does not fall within the expected range."

Here is the code to Create a Pivot Gallery on a given Web. 

public void CreatePowerPivotGallery(SPWeb web, string galleryName, string description)
        {
            web.AllowUnsafeUpdates = true;

            SPListTemplate template = null;
            foreach (SPListTemplate temp in web.ListTemplates)
            {
                if (temp.InternalName == "ReportGalleryLibrary")
                {
                    template = temp;
                    break;
                }
            }

            if (template == null)
            {
                throw new Exception();
            }

            web.Lists.Add(galleryName, description, template);

            web.Update();
            web.AllowUnsafeUpdates = false;
        }


Usage:
SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite site = new SPSite(@"http://mymachine:30000/"))
                {
                    using (SPWeb web = site.OpenWeb())
                    {
                        CreatePowerPivotGallery(web, "SomeNewGallery", "Power Pivot Gallery");
                    }
                }
            });


Note: Ensure that the Site Collection has the "PowerPivot Feature Integration for Site Collections" feature enabled.

1 comment:

  1. You don't have to loop through the ListTemplates to compare the internal name. ListTemplates collection is indexed based off of the "Name" of the list template.

    Therefore you can just do the following:

    SPListTemplate template = web.ListTemplates["PowerPivot Gallery"];

    ReplyDelete