SPC110263: Close PublishingWeb created by PublishingWebCollection.Add

PublishingWebCollection.Add() method requires you to call Close on the returned PublishingWeb object.

TypeName: ClosePublishingWebCreatedByPublishingWebCollectionAdd
CheckId: SPC110263
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

PublishingWebCollection.Add() method requires you to call Close() on the returned PublishingWeb object. See sample from MSDN:

Bad Coding Practice

void PublishingWebAddLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      // Passing in SPWeb object that you own, no dispose needed on outerPubWeb.
      PublishingWeb rootPublishingWeb = PublishingWeb.GetPublishingWeb(web);
      PublishingWebCollection publishingWebs = rootPublishingWeb.GetPublishingWebs();
      
      // Create the new PublishingWeb using the example values provided.
      PublishingWeb newWeb = publishingWebs.Add("http://moss/site", 1033, "STS#0"); // PublishingWeb will leak  
      } // SPWeb object web.Dispose() automatically called.
    } // SPSite object siteCollection.Dispose() automatically called.
}

Good Coding Practice
void PublishingWebAddNoLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      PublishingWeb newWeb = null;
      
      // Passing in SPWeb object that you own, no dispose needed on outerPubWeb.
      PublishingWeb rootPublishingWeb = PublishingWeb.GetPublishingWeb(web);
      PublishingWebCollection publishingWebs = rootPublishingWeb.GetPublishingWebs();
      
      try
      {
        newWeb = publishingWebs.Add("http://moss/site", 1033, "STS#0"); // PublishingWeb will leak  
      }
      finally
      {
        // Always close the SPWeb when done to release memory.
        if (null != newWeb)
        {
          newWeb.Close();
        }
      }  
    } // SPWeb object web.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Remarks

Rule relates to SPDisposeCheckId 'SPDisposeCheckID_310'. To ignore this rule add the attribute '[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_310, "Caller will dispose")]' to your method.

Links

comments powered by Disqus