Saturday, February 21, 2009

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

It's one of the common errors that we get when we developp with sharepoint object model.

To resolve this error you can check :

1. Application Pool Identity


When you use sharepoint object model from WEB SERVICE , you have to check that the identity of it application pool has the required rights to call the MOSS methods. In particular, the right to open site(SPite site = new SPsite).

2. Disposing of yours Sharepoint Objects

Check that you have correctly disposed yours Sharepoint Objects.
(see
Best Practices: Using Disposable Windows SharePoint Services Objects )

Specifically, if you writed code like this:
using (SPSite site = new SPSite(SPContext.Current.Site))
{
using (SPWeb web = site.OpenWeb(site.OpenWeb()))
{
string ItemID = web.Lists["myListName"].Items[0]["myItemID"].ToString();
}
}


It's preferable to modify this code by:
try
{
SPWeb webContext = null;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(webContext.Site.ID))
{
using (SPWeb web = site.OpenWeb(webContext.ID))
{
string ItemID = web.Lists["myListName"].Items[0]["myItemID"].ToString();
}
}
});
}
catch (Exception ex)
{
}
finally
{
if (webContext != null)
webContext.Dispose();
}

No comments:

Post a Comment