Tuesday, February 10, 2015

Operation is not valid due to the current state of the object, Update web.config file using feature in SharePoint

Operation is not valid due to the current state of the object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.InvalidOperationException: Operation is not valid due to the current state of the object.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[InvalidOperationException: Operation is not valid due to the current state of the object.]
   System.Web.HttpValueCollection.ThrowIfMaxHttpCollectionKeysExceeded() +4197167
   System.Web.HttpValueCollection.FillFromEncodedBytes(Byte[] bytes, Encoding encoding) +60
   System.Web.HttpRequest.FillInFormCollection() +189

[HttpException (0x80004005): The URL-encoded form data is not valid.]
   System.Web.HttpRequest.FillInFormCollection() +11195688
   System.Web.HttpRequest.get_Form() +119
   Microsoft.SharePoint.SPGlobal.GetParametersFromHttpRequest(SPSite site, Boolean bAuthenticated) +422
   Microsoft.SharePoint.SPGlobal.CreateSPRequestAndSetIdentity(SPSite site, String name, Boolean bNotGlobalAdminCode, String strUrl, Boolean bNotAddToContext, Byte[] UserToken, String userName, Boolean bIgnoreTokenTimeout, Boolean bAsAnonymous) +28024985
   Microsoft.SharePoint.SPWeb.InitializeSPRequest() +223
   Microsoft.SharePoint.WebControls.SPControl.EnsureSPWebRequest(SPWeb web) +365
   Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) +520
   Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.GetContextWeb(HttpContext context) +27
   Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PostResolveRequestCacheHandler(Object oSender, EventArgs ea) +918
   System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +171
Open VS -> Create New Solution for SharePoint -> Select Features -> right click ‘Add New Feature’(make sure feature scope is 'WebApplication') -> select created new feature -> right click ‘Add Event receiver’
using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

namespace MyNewFeature.Features.UpdateWebConfig
{
    [Guid("20e0b198-3468-42cd-bf97-1d0bbef479eb")]
    public class MyNewFeatureEventReceiver : SPFeatureReceiver
    {
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPWebConfigModification mod = new SPWebConfigModification();
                mod.Path = "configuration/appSettings";
                mod.Name = "add [@key='aspnet:MaxHttpCollectionKeys'] [@value='10000']";
                mod.Owner = "MaxHttpCollectionKeys_Owner";
                mod.Sequence = 0;
                mod.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
                mod.Value = "<add key='aspnet:MaxHttpCollectionKeys' value='10000' />";
                webApplication.WebConfigModifications.Add(mod);
                webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                webApplication.Update();                //ConfigurationManager.AppSettings["aspnet:MaxHttpCollectionKeys"].ToString();
            });
        }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            SPWebApplication webApplication = properties.Feature.Parent as SPWebApplication;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                Collection<SPWebConfigModification> mods = webApplication.WebConfigModifications;
                int initialModificationsCount = mods.Count;
                for (int i = initialModificationsCount - 1; i >= 0; i--)
                {
                    if (mods[i].Owner == "MaxHttpCollectionKeys_Owner")
                    {
                        SPWebConfigModification modToRemove = mods[i];
                        mods.Remove(modToRemove);
                    }
                }
                if (initialModificationsCount > mods.Count)
                {
                    webApplication.Farm.Services.GetValue<SPWebService>().ApplyWebConfigModifications();
                    webApplication.Update();
                }
            });
        }
    }
}

Featured Post

Sent Email in C#

Sent Email in C# : //Option 1: using S ystem; using System.Net.Mail; using System.Security; using System.Text; using System.Threading.T...

Popular posts