Expand Minimize

SPC110262: Close PublishingWeb created by PublishingWeb.GetVariation

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

CheckId SPC110262
TypeName ClosePublishingWebCreatedByPublishingWebGetVariation
Severity CriticalWarning
Type Assembly

The Microsoft.SharePoint.Publishing.PublishingWeb.GetVariation method returns a PublishingWeb object that must be closed. See sample from MSDN:
Bad 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 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.  
}

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

To suppress this violation in managed code add the following attribute to the method which contains the instruction (available since SPCAF version v5.2). Learn more about SuppressMessage here.

// Important: Ensure to have #define CODE_ANALYSIS at the beginning of your .cs file
[SuppressMessage("SPCAF.Rules.MemoryDisposalGroup", "SPC110262:ClosePublishingWebCreatedByPublishingWebGetVariation", Justification = "Provide reason for suppression here")]
Disclaimer: The views and opinions expressed in this documentation and in SPCAF do not necessarily reflect the opinions and recommendations of Microsoft or any member of Microsoft. SPCAF and RENCORE are registered trademarks of Rencore. All other trademarks, service marks, collective marks, copyrights, registered names, and marks used or cited by this documentation are the property of their respective owners.