SPC110262: Close PublishingWeb created by PublishingWeb.GetVariation

The Microsoft.SharePoint.Publishing.PublishingWeb.GetVariation method returns a PublishingWeb object that must be closed.

TypeName: ClosePublishingWebCreatedByPublishingWebGetVariation
CheckId: SPC110262
Severity: CriticalWarning
Type: AssemblyFileReference
Resolution

The Microsoft.SharePoint.Publishing.PublishingWeb.GetVariation method returns a PublishingWeb object that must be closed. See sample from MSDN:

Bad Coding Practice

void GetVariationLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in SPWeb object, so no Close() needed
      VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
      PublishingWeb variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // Must be Closed().
      // ...
    } // SPWeb object outerWeb.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Good Coding Practice
void GetVariationNoLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      PublishingWeb variationPublishingWeb = null;
      try
      {
        PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in SPWeb object, so no Close() needed.
        VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
        variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // Must be Closed().
        // ...
      }
      finally
      {
        if(variationPublishingWeb != null)
          variationPublishingWeb.Close();
      }
    } // SPWeb object web.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Remarks

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

Links

comments powered by Disqus