Expand Minimize

Dispose SPWeb created by SPLimitedWebPartManager

The SPLimitedWebPartManager class contains a reference to an internal SPWeb object that must be disposed.

CheckId SPC110205
TypeName DisposeSPWebCreatedBySPLimitedWebPartManager
Severity Warning
Type Assembly

Dispose any SPWeb object which has been created by SPLimitedWebPartManager. See sample from MSDN:
Bad Practice

void SPLimitedWebPartManagerLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      SPFile page = web.GetFile("Source_Folder_Name/Source_Page");
      SPLimitedWebPartManager webPartManager =
        page.GetLimitedWebPartManager(PersonalizationScope.Shared);
        // SPWeb object webPartManager.Web leaked.
    } // SPWeb object web.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Good Practice
void SPLimitedWebPartManagerLeak()
{
  using (SPSite siteCollection = new SPSite("http://moss"))
  {
    using (SPWeb web = siteCollection.OpenWeb())
    {
      SPFile page = web.GetFile("Source_Folder_Name/Source_Page");
      SPLimitedWebPartManager webPartManager =
        page.GetLimitedWebPartManager(PersonalizationScope.Shared);
        webPartManaber.Web.Dispose();
    } // SPWeb object web.Dispose() automatically called.
  }  // SPSite object siteCollection.Dispose() automatically called.  
}

Rule relates to SPDisposeCheckId 'SPDisposeCheckID_160'. To ignore this rule add the attribute '[SPDisposeCheckIgnore(SPDisposeCheckID.SPDisposeCheckID_160, "Caller will dispose")]' to your method. Due to some limitations in current analysis the rule only checks for calls to the Web property of SPLimitedWebPartManager. Currently the rule cannot check if also Dispose is called on the property. This can lead to misleading warnings.

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", "SPC110205:DisposeSPWebCreatedBySPLimitedWebPartManager", 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.