April 2010


I was writing code using SPWeb under the impression that “using” statement takes care of disposing objects.
My Function was something like the one shown below:

public void LoadFunction()
{
using (SPWeb ospWeb = SPContext.Current.Web)
{
….Logic
}
}

However,I kept getting the error “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”
I realized, we should dispose off the SPSite object and not the SPWeb object directly.

So,I modified the code as shown below:

public void LoadFunction()
{
using(SPSite spSite=new SPSite(SPContext.Current.Web.Url))
{
using (SPWeb spWeb = spSite.OpenWeb())
{
….Logic
}
}
}

This solved the problem of “Trying to use an SPWeb object that has been closed or disposed and is no longer valid.”

We sometimes need to add lists,document/image libraries to a site automatically, or in other words when a feature is activated.To do that,we need a Feature Receiver class and on Feature Activated,we need to write the code for asdding list/doc library/picture library

using (SPSite siteCollection = new SPSite(“Absolute_url”))
{
using (SPWeb mySite = siteCollection.OpenWeb())
{
SPListCollection _Lists = mySite.Lists;
try
{
if (_Lists[strListName] != null)
Message += ” List Already Exists”;

}
catch(Exception ex)
{
Guid listGuid = _Lists.Add(“MapPicLibrary”, “Map Picture Library”, SPListTemplateType.PictureLibrary);
}
}
}