Home > 70-573, Development, SP 2010 > Manage SPSite and SPWeb programmatically by using Visual Studio 2010

Manage SPSite and SPWeb programmatically by using Visual Studio 2010

This one seems pretty easy…but there are some caveats. I think whats most important here is the use of the many properties and methods. You can view each class by going to these links: SPSite & SPWeb.

Here is the Skill Measured: This objective may include but is not limited to: creating sub webs, referencing SPFiles, manipulating property bag, when to call Update, referencing SPContext, SPSite, SPWeb, SPSite.OpenWeb, SPWeb.Webs, feature activiation and deactivation

Note from MS: This objective does not include: trivial cases such as setting title and other loose properties of the objects

Lets start off by looking at each class. Lets start with SPSite, as you will instansiate this prior to instansiating SPWeb (if instansiating).


This is the way, in the object model, that we get information about collections of sites in SharePoint. Since our farm (from a content perspective) is built into many, many site collections, this is the appropriate method for manipulating and building context around a site collection.

You can instantiate an SPSite object by using many of its constructors. Here are some examples:

Using absolute URL signature:

SPSite site = new SPSite("absoluteUrl");

Using an SPContext object:

string siteUrl = SPContext.Current.Site.Url;
using(SPSite site = new SPSite(siteUrl))

In my opinion, the most important part of using an SPSite object is disposing of it properly. In summary, disposing of this object will call garbage collection and free resources up in memory. This also prevents memory leaks…which is a very real possibility with using SPSite objects with other objects. Below is an example of how to dispose of your SPSite object:

Guid guid = SPContext.Current.Site.ID;
Using(SPSite site = new SPSite(guid))
	My code

There are A LOT of members in SPSite. I’m not exactly sure it’s a great use of your time to know all of the members in SPSite. Here is a small table of some of the SPSite members I think are important. **I think you should definetly check out the remaining SPSite Members…I’m just not going to list them all…http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spsite_members.aspx**


CheckForPermissions Checks the permissions for a given set of rights and throws an Unauthorized Access exception if the permission check fails.
Delete Overloaded. Deletes the site collection from the server.
Exists Returns a Boolean value that indicates whether the specified site collection exists.
OpenWeb Overloaded. Returns the specified Web site from the site collection.
Rename Changes the URL of a host-header-named site collection to a new URL.


All Webs Gets the collection of all Web sites that are contained within the site collection, including the top-level site and its subsites.
Features Gets the collection of SPFeature objects that are associated with the site collection.
ID Gets the GUID that identifies the site collection.
Owner Gets or sets the owner of the site collection
PortalName Gets or sets the name of a portal
PortalURL Gets or sets the url of a portal
ReadOnly Gets or sets a Boolean value that specifies whether the site collection is read-only, locked, and unavailable for write access.
RootWeb Gets the root Web site of the site collection.
Solutions Gets the collection of user solutions (sandbox solutions) that have been activated for the site collection
Url Gets the full URL to the root web site of the site collection, including host name, port number, and path.
WebApplication Gets the SharePoint Foundation Web application to which the site collection belongs to


From SPSite, we can then traverse into SPWeb. This class represents each web in a site collection (I’d say site…but not to be confused with SPSite). This class lets us change properties of webs and build out more context (so we can use SPList and so on).

Like SPSite, you instantiate SPWeb objects but use an SPSite object to build it out…like so:

Using SPSite.RootWeb (returns the top web of a site collection)

SPWeb web = SPSite.AllWebs["webName"];

Like SPSite, properly dispose of SPWeb objects with a using(){} statement. Like so…

using(SPWeb web = SPSite.RootWeb)

SPWeb has many members just like SPSite…but important to this exam is that it gives access to the Property Bag. Each SPWeb object has a couple of methods that allow you to get/set properties. Additionally, you can enumerate through each property in the Property Bag. Think of the Property Bag as a hash table for keys/values of settings in a SPWeb. An example of such a property is the default permissions groups for a web. The Property Bag stores which group is used as the Visitors, Members, and Owners group. Another one I’ve used in the past is to set the search center scopes.

Whenever you update a setting on a SPWeb object, you must call the SPWeb.Update() method to commit the changes.

Use the SPContext.Current.Web (or SPContext.Current.Site.RootWeb) to manipulate the current web settings. Don’t forget to call the Update() method to commit your changes.


CustomizeCSS Customizes the specified style sheet for the site. Use this method to apply an overriding style sheet for SharePoint branding.
Delete Deletes the Web site
DeleteProperty Deletes a property from the property bag
EnsureUser Checks whether the specified login name belongs to a valid user of the Web site, and if the login name does not already exist, adds it to the Web site.
GetFile Overloaded. Returns the file object with the specified GUID or the file object that is located at the specified URL.
GetList Returns the list that is associated with the specified server-relative URL.
GetProperty Gets a property from the property bag
SetProperty Sets a property in the property bag to a value
Update Updates the database with changes that are made to the Web site.


Alerts Gets the collection of alerts for the site or subsite
All properties Gets a hash table that contains metadata for the Web site.
CurrentUser Gets the current user of the site.
Features Gets the collection of Features that are currently activated in the Web site.
Lists Gets the collection of all lists that are contained in the Web site.
MasterUrl Gets or sets the URL of the master page that is used for the Web site. Use this property to set a custom master.page url in SharePoint Branding
Title Gets or sets the title for the Web site.
Webs Gets a Web site collection object that represents all Web sites immediately beneath the Web site, excluding children of those Web sites.

To programatically create a new subweb, create your context (I.E. which web you would like to create the web under. Then call the following code:

SPWeb newWeb = web.Webs.Add("overloads here");


You can programatically add/remove Features from the feature list by calling SPWeb.Features.Add() or SPWeb.Features.Remove().

Feel free to post comments below on what you think of this write-up. Thanks!

-Matt Huber

Categories: 70-573, Development, SP 2010
  1. January 5, 2011 at 3:04 pm


    Good post. One comment though. I’ve heard that it is not a good idea to place site.Rootweb inside of a “using” statement since that could potentially lead to errors in your code execution. It is similar to disposing of the SPContext.Current.Web object. If your code tries to reference it again during execution it will not exist and throw an exception. I believe the article I read suggested to create a new instance via Site.OpenWeb(“/”) instead.

    • January 5, 2011 at 9:41 pm

      Oh good idea. Thanks for the tip!

      I remember reading somewhere about best practices when properly disposing of SPSite & SPWeb. I think it might have been a whitepaper on the SharePoint Developer Center. I’ll see if I can dig that up and add it as a foot note =)

  2. annie
    March 3, 2011 at 3:39 pm

    I believe this is the URL that referenced it.


    • March 3, 2011 at 10:35 pm

      Thank you Annie! Thats exactly the post I referenced. Great stuff there…

      I should add that SPDisposeCheck.exe (the addon you can get at http://archive.msdn.microsoft.com/SPDisposeCheck) will automatically make sure you dispose of these objects properly. On a side note..I always thought that SPDisposeCheck came OOTB with something…it does not and must be installed as a VS2010 addon.

  3. Peter Bojanczyk
    November 19, 2012 at 4:04 pm

    Hi Matt,
    I know this is a pretty old article but I wanted to point out one important thing. You should NEVER dispose SPContext.Current.Site or SPContext.Current.Web. The proper pattern is to initialize your own SPSite or SPWeb and work with it inside a “using” code-block.

    • November 19, 2012 at 4:13 pm

      Thanks Peter… I agree with ya… not sure how that got in there. Thanks for the catch… I’ll update my samples!

  4. July 26, 2013 at 10:08 pm

    The starting of the cake toppers was done with the wedding cakes, but with
    time and huge popularity, it became a part of decoration in many other
    occasions where cake is used. On the backside of the coin displays all 12 Chinese zodiac symbols.
    Making hand shaped flowers like mums, roses, carnations, calla lilies, rosebuds and daisy will be taught as

  5. August 2, 2013 at 8:25 pm

    Break your 3 normal main meals into 5 smaller portion sizes – morning, snack, lunch, snack,
    dinner. Authorities inside the area will need to have an intensive understanding of laboratory and labeling techniques, infection security precautions, appropriate
    blood attract approaches to the elderly and for infants and
    even more. Many people don’t have the time to weight themselves every day, but checking the scale on a regular basis can definitely help when you’re working to lose weight and keep it off.

  6. August 5, 2013 at 7:51 am

    You don’t have to hit the gym for two and three hours each day to lose weight, but it does help to squeeze in 30 minutes of physical activity each day. Avocados- Although not my favorite, are high in fats, the good ones. Many people don’t have the time
    to weight themselves every day, but checking the scale on a regular basis can definitely help
    when you’re working to lose weight and keep it off.

  7. August 6, 2013 at 8:54 pm

    Believing that you are actually starving, it releases chemicals that actually make
    it harder to lose weight in an effort to conserve energy.
    Anyone who dares to make a closer inspection will find the underlying difference.

    Expect to lose all that extra flabbiness as you melt off all
    your unwanted fat.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: