The request uses too many resources

Introduction

While developing a CSOM app for SharePoint Online I encountered an error:

“The request uses too many resources”

My problem

I got this error while removing some webparts from a wikipage through CSOM code. It was working fine on development but didn’t work on the production system. Here is my code.

        public static void DeleteAllWebparts(this ClientContext ctx, File wikiPage)
        {
            LimitedWebPartManager lwpm = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ctx.Load(lwpm.WebParts);
            ctx.ExecuteQuery();

            if (lwpm.WebParts.Count >= 0)
            {
                for (int i = lwpm.WebParts.Count - 1; i >= 0; i--)
                {
                    lwpm.WebParts[i].DeleteWebPart();
                }
                ctx.ExecuteQuery();
            }
        }

Solution

You only have a limited amount of resources when executing a client-side statement. It’s good to group your information in one call. But, as it turns out, it’s also possible to make your request too large. In other words a client-side request can contain too much information.

Instead of deleting all the webparts at once. I deleted the webparts one by one. I moved the ‘ctx.ExecuteQuery();’ to the inside of the for-loop instead of after the loop.
This results ofcourse in more requests to the services but it limits the amount of data that is send at once.

        public static void DeleteAllWebparts(this ClientContext ctx, File wikiPage)
        {
            LimitedWebPartManager lwpm = wikiPage.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ctx.Load(lwpm.WebParts, wps => wps.Include(wp => wp.WebPart.Title));
            ctx.ExecuteQuery();

            if (lwpm.WebParts.Count > 0)
            {
                for (int i = lwpm.WebParts.Count - 1; i >= 0; i--)
                {
                    lwpm.WebParts[i].DeleteWebPart();
                    ctx.ExecuteQuery();
                }
            }
        }

After this fix my code worked.

More info:
http://msdn.microsoft.com/en-us/library/office/jj163082.aspx#pj15_WhatTheCSOM_RequestLimits

Share Your Thoughts