locked
Operation is not valid due to the current state of the object at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPContro

    Question

  • I have this  problem. When I run this piece of code all I get is


    1. I get this error at SPWebApplication webApp = webAppBld.Create();

    2. {"Operation is not valid due to the current state of the object."}

    3. Stack gets here "   at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context)



    SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPFarm objSpfarm = SPWebService.AdministrationService.Farm;
                    SPWebApplicationBuilder webAppBld = null;

                    webAppBld = new SPWebApplicationBuilder(objSpfarm);
                    webAppBld.Port = 33665;
                    webAppBld.Id = System.Guid.NewGuid();

                    webAppBld.AllowAnonymousAccess = false;
                    webAppBld.UseNTLMExclusively = true;
                    webAppBld.UseSecureSocketsLayer = false;

                    webAppBld.ApplicationPoolId = "SharePointAppPoolId-33665";
                    webAppBld.ApplicationPoolUsername = @"testsvr02\testadmin";

                    // build the password as a secure string
                    SecureString appPoolPwd = new SecureString();
                    appPoolPwd.AppendChar('1');
                    appPoolPwd.AppendChar('2');
                    appPoolPwd.AppendChar('3');
                    appPoolPwd.AppendChar('W');
                    appPoolPwd.AppendChar('e');
                    appPoolPwd.AppendChar('l');
                    appPoolPwd.AppendChar('c');
                    appPoolPwd.AppendChar('o');
                    appPoolPwd.AppendChar('m');
                    appPoolPwd.AppendChar('e');
                    // more of the same to build-up the password
                    appPoolPwd.MakeReadOnly();

                    webAppBld.ApplicationPoolPassword = appPoolPwd;

                    webAppBld.CreateNewDatabase = true;
                    webAppBld.DatabaseServer = @"TESTSVR02\OfficeServers";
                    webAppBld.DatabaseName = "TestSite";
                    webAppBld.DatabaseUsername = @"testsvr02\testadmin";
                    webAppBld.DatabasePassword = "123Welcome";

                    webAppBld.DefaultZoneUri = new Uri("http://TESTSVR02:33665/");
                    webAppBld.RootDirectory = new DirectoryInfo(@"C:\Inetpub\wwwroot\wss\VirtualDirectories\33665");
                    SPWebApplication webApp = webAppBld.Create();
                                                  
                });

    Any ideas ?
    Monday, June 02, 2008 5:13 AM

Answers

  • Hi all,

    I had a similar problem with some code to update a list item, executing within a web service method.

    I used HttpContext.Current = null and the problem got solved.

    Thank you


    Panos *
    • Edited by Mike Walsh FIN Wednesday, April 27, 2011 4:14 PM additional question removed prior to marking as (one) answer and locking thread (as long enough)
    • Marked as answer by Mike Walsh FIN Wednesday, April 27, 2011 4:14 PM
    Tuesday, March 22, 2011 2:06 PM

All replies

  • Try taking out:

                    webAppBld.DatabaseUsername = @"testsvr02\testadmin";
                    webAppBld.DatabasePassword = "123Welcome";

     

    Those properties are for SQL Authentication and that account name looks like a Windows account to me.

     

     

    Tuesday, June 03, 2008 6:17 PM
  • Thanks Michael  for the suggestion. I did try it after removing but I still get the same error.

    Regards
    Ashish
    Wednesday, June 04, 2008 4:02 AM
  • I am getting the same error, but my code is very different than yours. Are you running this code in a .NET app that is running in a virtual directory under the main MOSS site? I am, and I am thinking that something in the RunWithElevatedPriviledges doesn't like something or we are both missing something.

     

    Here is my code if it helps anyone else. I don't know that our 2 issues are the same, but it looks like they might be. Mine craps out on web.siteusers.add

     

     

    Code Snippet

    try

    {

    SPSite site = new SPSite(http://mysite);

    SPWeb web = site.RootWeb;

    SPSecurity.RunWithElevatedPrivileges(delegate()

    {

    using (site)

    {

    using (web)

    {

    Boolean allowUnsafeUpdate = web.AllowUnsafeUpdates;

    try

    {

    web.AllowUnsafeUpdates = true;

    APHLCreateNewFormsAccount(txtEmail.Text.Trim(), txtPass.Text.Trim());

    String notes = "New user created to replace: " + usr;

    web.SiteUsers.Add("User:" + txtEmail.Text.Trim(), txtEmail.Text.Trim(), txtFName.Text.Trim() + " " + txtLName.Text.Trim(), notes);

    SPUser currentUser = web.AllUsers[usr];

    SPUser newUser = web.AllUsers["User:" + txtEmail.Text.Trim()];

    foreach (SPGroup group in currentUser.Groups)

    {

    group.Users.Add(newUser.LoginName, newUser.Email, newUser.Name, newUser.Notes);

    }

    foreach (SPAlert alert in currentUser.Alerts)

    {

    newUser.Alerts.Add(alert.List, alert.EventType, alert.AlertFrequency);

    }

    }

    finally

    {

    web.AllowUnsafeUpdates = allowUnsafeUpdate;

    }

    }

    }

    });

    }

    catch (Exception ex)

    {

    Context.Response.Write(ex.Message + ex.StackTrace);

    }

     

     

    Wednesday, June 04, 2008 8:52 PM
  • Hi Joe,

     

    I think you have a different problem.


    Daniel Larson answered this one on this thread:

    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=3354242&SiteID=1

     

     

    Wednesday, June 04, 2008 8:56 PM
  • Michael,

     

    Thanks for the response. I read Daniels post, but I'm unsure how it relates to my problem. I'm sure it has to do with my usage of SPSite and SPWeb, but I'm unsure on how to fix it. In his post he's creating a new web first, then adding users to it. I want to just add users to a current web, so I'm not sure what I need to change in my code. Can you help any further?

     

    Thanks.

    Wednesday, June 04, 2008 9:18 PM
  • What part of your code fails?

    The only thing I see out of the oridinary is:

    Right after your call to web.SiteUsers.Add you should call web.Update();

     

    Wednesday, June 04, 2008 9:41 PM
  • I'm not sure exactly which function call is causing the error. It's either the RunWithElevatedPrivileges or the web.SiteUsers.Add

     

    When using the RunWithElevatedPrivileges does there have to be a valid logged in user? That's the only other idea I had. Or do I need to use the RunWithElevatedPrivileges in a different way?

     

    Here's the full stack trace and updated code. Thanks!

     

    Code Snippet

    try

    {

    SPSite site = new SPSite("http://forms.dev.aphlweb.org");

    SPWeb web = site.RootWeb;

    SPSecurity.RunWithElevatedPrivileges(delegate()

    {

    Boolean allowUnsafeUpdate = web.AllowUnsafeUpdates;

    try

    {

    web.AllowUnsafeUpdates = true;

    APHLCreateNewFormsAccount(txtEmail.Text.Trim(), txtPass.Text.Trim());

    String notes = "New user created to replace: " + usr;

    web.SiteUsers.Add("APHLUser:" + txtEmail.Text.Trim(), txtEmail.Text.Trim(), txtFName.Text.Trim() + " " + txtLName.Text.Trim(), notes);

    web.Update();

    SPUser currentUser = web.AllUsers[usr];

    SPUser newUser = web.AllUsers["APHLUser:" + txtEmail.Text.Trim()];

    foreach (SPGroup group in currentUser.Groups)

    {

    group.Users.Add(newUser.LoginName, newUser.Email, newUser.Name, newUser.Notes);

    }

    foreach (SPAlert alert in currentUser.Alerts)

    {

    newUser.Alerts.Add(alert.List, alert.EventType, alert.AlertFrequency);

    }

    }

    finally

    {

    web.AllowUnsafeUpdates = allowUnsafeUpdate;

    }

    });

    }

    catch (Exception ex)

    {

    Context.Response.Write(ex.Message + ex.StackTrace);

    }

     

     

    Operation is not valid due to the current state of the object. at Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) at Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context) at Microsoft.SharePoint.Utilities.SPUtility.RedirectToAccessDeniedPage(HttpContext context) at Microsoft.SharePoint.Utilities.SPUtility.HandleAccessDenied(Exception ex) at Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException ex) at Microsoft.SharePoint.Library.SPRequest.UpdateMembers(String bstrUrl, Guid& pguidScopeId, Int32 lGroupID, Int32 lGroupOwnerId, Object& pvarArrayAdd, Object& pvarArrayAddIds, Object& pvarArrayLoginsRemove, Object& pvarArrayIdsRemove, Boolean bSendEmail) at Microsoft.SharePoint.SPUserCollection.UpdateMembers(Object objUpdateInfo, Object objRemoveLogins, Object objRemoveIds, Boolean fSendEmail) at Microsoft.SharePoint.SPUserCollection.AddCollection(SPUserInfo[] addUsersInfo) at Microsoft.SharePoint.SPUserCollection.Add(String loginName, String email, String name, String notes) at SSOLoginCreateAccount.<>c__DisplayClass3.b__0() in c:\Data\Websites\forms_dev_aphl_org\_layouts\Login\SSOLoginCreateAccount.aspx.cs:line 930 at Microsoft.SharePoint.SPSecurity.CodeToRunElevatedWrapper(Object state) at Microsoft.SharePoint.SPSecurity.<>c__DisplayClass4.b__2() at Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRunElevated secureCode) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(WaitCallback secureCode, Object param) at Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) at SSOLoginCreateAccount.ChangeAPHLEmail() in c:\Data\Websites\forms_dev_aphl_org\_layouts\Login\SSOLoginCreateAccount.aspx.cs:line 921
    Wednesday, June 04, 2008 9:56 PM
  • Try chaning your code around like below so you have an elevated SPSite and SPWeb.

    SPSite site = SPContext.Current.Site;
    SPWeb web = SPContext.Current.Web;
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    SPSite elevatedPrivilegesSiteCollection = new SPSite(site.ID);
    SPWeb elevatedPrivilegesWeb = elevatedPrivilegesSiteCollection.OpenWeb(web.ID);

    Wednesday, June 04, 2008 10:13 PM
  • Michael,

     

    Thanks for all your help. It is much appreciated. I got everything worked out. The problem was an order of operation. I read here: http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsecurity.runwithelevatedprivileges.aspx

    That the SPSite and SPWeb declaration must be inside the delegate function because SPSite objects created outside do not have Full Control even when referenced inside the delegate. So I moved that inside the delegate and everything worked.

     

    Thanks again.

    Thursday, June 05, 2008 12:54 AM
  • Hmm anybody got some suggestion for my problem ? I have got everything inside Elevated priv. ?
    Thursday, June 05, 2008 4:28 AM
  • Try removing :
    SPSecurity.RunWithElevatedPrivileges(delegate(){});

    Run without evelated privileges.
          
    Tuesday, December 16, 2008 11:30 AM
  • In my case,

    the problem was that RunWithElevatedPriviliges seems not to change the context to the new user.
    By setting the context to null, it all worked:

     	SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    HttpContext.Current = null;
                    using (SPSite site = new SPSite(targetWeb))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            SPList targetlist = web.Lists[targetList];
                            foreach (ItemType item in import.item)
                            {
       			...
                            }
                        }
                    }
                });
    Thursday, January 21, 2010 4:11 PM
  • In my case I was getting the following error and it got resolved by iisreset.

    Server Error in '/' Application.

     


     

    Operation is not valid due to the current state of the object.

    Description:

    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.]
    
     Microsoft.SharePoint.WebControls.SPControl.SPWebEnsureSPControl(HttpContext context) +170
    
     Microsoft.SharePoint.WebControls.SPControl.GetContextWeb(HttpContext context) +31
    
     Microsoft.SharePoint.ApplicationRuntime.SPRequestModule.PostResolveRequestCacheHandler(Object oSender, EventArgs ea) +385
    
     System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +68
    
     System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +75

     

    Moderator Note: NEVER propose your own posts as answers. The Propose as Answer function is so that people can propose the good answers of other people. It is NOT for self-proposing.


    • Proposed as answer by Vijay Ji Monday, April 25, 2011 9:08 PM
    • Unproposed as answer by Mike Walsh FIN Wednesday, April 27, 2011 4:12 PM
    • Edited by Mike Walsh FIN Wednesday, April 27, 2011 4:13 PM Moderator note added about not proposing own answers
    Tuesday, July 20, 2010 1:46 PM
  • Stefan,

    Many thanks!  I've written to lists all over the place using the SP.Security delegate with context changes in the correct order with never an issue - until I tried it from within an HTTPModule.  I got "Operation is not valid' and was at wits end.  For whatever reason, and I'm content to just let it be, setting the HttpContext.Current to null within the delegate was the trick.

    Friday, October 08, 2010 8:12 PM
  • Im getting same message sharepoint operation is not valid due to current state of the object but mine is a new install (2 weeks) of windows 2008 sbs and was working fine until I started using the SBS 2008 Best Practices Analyzer and began to download updates and install them as it suggested.

    It may have something to do with one of the suggestions was to change the authentication on the server

    Here is my error:

    System.InvalidOperationException: Operation is not valid due to the current state of the object.
       at Microsoft.SharePoint.Administration.SPContentDatabase.ValidateDatabaseSchemaCompatibility()
       at Microsoft.SharePoint.SPSite.PreinitializeServer(SPRequest request)
       at Microsoft.SharePoint.SPWeb.InitializeSPRequest()
       at Microsoft.SharePoint.SPWeb.EnsureSPRequest()
       at Microsoft.SharePoint.SPWeb.get_Request()
       at Microsoft.SharePoint.SPWeb.InitWeb()
       at Microsoft.SharePoint.SPWeb.get_WebTemplate()
       at Microsoft.SharePoint.SPEvaluatorModeProvisioning.TryGetIsSiteProvisioned(String template, String relativePath, Nullable`1 port, SPSite& provisionedSite, SPWeb& provisionedWeb, Uri& provisionedUri)
       at Microsoft.SharePoint.PostSetupConfiguration.WelcomeForm.ShowNextFormForServerRoleSingleServer()
       at Microsoft.SharePoint.PostSetupConfiguration.WelcomeForm.PsconfigBaseFormNextButtonClickedEventHandler(Object sender, EventArgs e)
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

     

    Monday, November 01, 2010 2:50 AM
  • Hi friends,

    I got the same problem and i used

    HttpContext.Current=null,

    as Scott mentioned, it did work for me....

     

    Regards

    Wilson


    Wilson Varghese
    Tuesday, November 02, 2010 1:41 PM
  • I had a similar problem as described in the setup for the test environment of my final diploma exam in media computer science. I was look for a solution to this for like 3 days, that really saved me.

    Thank you very much!

    Wednesday, November 03, 2010 11:57 PM
  • Hi all,

    I had a similar problem with some code to update a list item, executing within a web service method.

    I used HttpContext.Current = null and the problem got solved.

    Thank you


    Panos *
    • Edited by Mike Walsh FIN Wednesday, April 27, 2011 4:14 PM additional question removed prior to marking as (one) answer and locking thread (as long enough)
    • Marked as answer by Mike Walsh FIN Wednesday, April 27, 2011 4:14 PM
    Tuesday, March 22, 2011 2:06 PM
  • you can try this "go to the Task Manager and look for all the instances of the process vssphost4.exe and kill them."  then deploy your solution again.....

     

    its works for me. hope it help.

    sandy


    sandy
    Wednesday, April 13, 2011 1:09 AM
  • I can atest to the same thing. I have a webservice that wasn't working without HttpContext.Current = null
    Wednesday, April 27, 2011 2:36 PM