Using remote SPSite and SPWeb objects

I was pleased enough that I inherited a terribly written SharePoint project.
Apparently, the original developer was a big fan of reusable code (30% of the code is reused in 20 projects without using any libraries - guess how?).

I would often find that his code calls some Common.OpenWeb method to retrieve the SPWeb object to work with SharePoint stuff. Most implementations of this feature look exactly the same:

 public SPWeb OpenWeb() { String strSiteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString(); SPSite site = null; SPWeb web = null; try { using (site = new SPSite(strSiteUrl)) { using (web = site.OpenWeb()) { return web; } } } catch (Exception ex) { LogEvent("Error occured in OpenWeb : " + ex.Message, EventLogEntryType.Error); } return web; } 

And now I'm really worried. How does it work in production? This method always returns the located object, right?

How unstable is this?

UPDATE:

This method is used as follows:

 oWeb = objCommon.OpenWeb(); SPList list = oWeb.Lists["List name"]; SPListItem itemToAdd = list.Items.Add(); itemToAdd["Some field"] = "Some value"; oWeb.AllowUnsafeUpdates = true; itemToAdd.Update(); oWeb.AllowUnsafeUpdates = false; 

I missed swallowing try-catch for short.
This code inserts the value into the list! This is a write operation, I'm sure the Request property is used for this. Then how can this work?

+4
source share
1 answer

First, the short answer: this method really returns the located object. An object should not be used after its removal, since it is no longer in a reliable state, and any further operation performed on this object should (theoretically) throw an ObjectDisposedException .

Now, after a short spurt, the SharePoint objects do not seem to follow this rule. Not only does SPWeb never throw an ObjectDisposedException after removing it, but it actually checks this case in the Request property and restores the actual SPRequest from its internal state if it was deleted.

It seems that at least SPWeb was designed to be fully functional even in a remote state. Why i do not know. Perhaps this is for hosting client code, like the one you are working on. Maybe this is some kind of complicated optimization that I cannot understand.

However, I suggest you not rely on this behavior because it may change in the future (although, given Microsoft’s policy regarding backward compatibility with error for errors, it cannot).

And of course, you will still test a new instance of SPRequest , which can be quite expensive. Never, never, use a located object, even if SharePoint allows you to deal with it.

+12
source

Source: https://habr.com/ru/post/1339725/


All Articles