0

In a web service function I recieve an array of User

public class User
{
   public string Name;
   public string Url;
}

The url is a url of some page in the site collection. I wish to open the web of said page and perform operations on it. What I have now is

users.ForEach(user => 
{
   using (SPSite site = new SPSite(user.Url)
   {
      using (SPWeb web = site.OpenWeb())
      {
         Some code goes here
      }
   }
}

Now this code is very heavy and inefficient, since for every user I open a new site and web. I do this because the url can be one of many different sites under the collection, so opening the site with the full url will give me the last site in the url hierarchy and then I'll just open its web.

Anyone has any better idea how to make it better. This code can run for up to a minute with only 20 users (which is nothing, there might be cases with thousands), not taking into account the possibility of an unknown url which will result in an exception (that will be thrown after a 404 timeout)

1 Answer 1

0

First - I don't think you need to keep re-creating the SPSite object. An SPSite object represents a site collection, not a (web)site. You can call site.OpenWeb() method with the server-relative or the site-relative URL of the web, which is easy enough to determine by stripping the URL of the site collection or web application.

Beyond that, the easiest thing you could do is to reorganize your data so that you only have to open each web once. To do this, I think you could parse URL and remove everything after the second-to-last slash:

http://example.com/sites/sitecollection/subweb/web2/Pages/Page.aspx

would then become:

http://example.com/sites/sitecollection/subweb/web2/

Then you could create a mapping of Site URL to the list of User objects that reference it, and set up nested loops to loop through that mapping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.