Watch out for dispose issue in the snippets for Visual Web Parts
The code snippet below has an issue that you need to watch out...
The dispose guidelines have NOT changed in SP2010, so you have to be careful:
Update: These issues have been fixed thanks to Paul Andrew.
The dispose guidelines have NOT changed in SP2010, so you have to be careful:
protected void Page_Load(object sender, EventArgs e)
{
SPWeb thisWeb = null;
try
{
TreeNode node;
thisWeb = SPContext.Current.Web;
//Add the Web's title as the display text for the tree node, and add the URL as the NavigateUri
node = new TreeNode(thisWeb.Title, null, null, thisWeb.Url, "_self");
//The Visual Web Part has a treeview control called siteStructure
siteStructure.Nodes.Add(node);
//Get a reference to the current node, so child nodes can be added in the correct position
TreeNode parentNode = node;
//Iterate through the Lists collection of the Web
foreach (SPList list in thisWeb.Lists)
{
if (!list.Hidden)
{
node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
parentNode.ChildNodes.Add(node);
}
}
foreach (SPWeb childWeb in thisWeb.Webs)
{
//Call our own helper function for adding each child Web to the tree
addWebs(childWeb, parentNode);
// have to dispose those
// you should use a try finally block to trap exceptions,
// but at least do:
childWeb.Dispose();
}
siteStructure.CollapseAll();
}
finally
{
// you should not dispose the web that you got from the context
// note that this finally block is obsolete now
//thisWeb.Dispose();
}
Update: These issues have been fixed thanks to Paul Andrew.
0 Comments:
Post a Comment
<< Home