Roger Lamb's SharePoint Developer Blog

  • SharePoint Conference 2009 Developer Hands On Labs (HOLs)

    Whether or not you were one of the lucky ones to attend the sold out SPC ‘09 conference in Las Vegas last week you should download and review the 10 developer Hands On Labs (HOL’s) in anticipation to the public beta of SharePoint Server 2010 due out in November 2009.

    You can download the 10 Developer HOL’s from here (C# and VB.NET).

    HOL01 - Developing a Visual Web Part in Visual Studio 2010
    This hands-on lab introduces the Visual Studio 2010 SharePoint development environment. It shows how to build a Visual Web Part using LINQ to SharePoint, and how to connect one Web Part to another Web Part on the page.

    HOL02 - Developing a List Definition and Event Receiver in Visual Studio 2010
    This hands-on lab walks you through building a list definition for SharePoint 2010 in Visual Studio 2010. It also shows how to build an event receiver for the list in Visual Studio 2010 and deploy it to SharePoint. After the list and event receiver are deployed, you can use the developer dashboard to evaluate the performance of the event receiver.

    HOL03 - Developing Advanced Web Parts for SharePoint 2010 with Visual Studio 2010
    This hands-on lab shows how to build a Web Part using several SharePoint-specific controls in Visual Studio 2010. Investigate advanced built-in Web Parts, including the Data View Web Part.

    HOL04 - Developing with LINQ to SharePoint in Visual Studio 2010
    This hands-on lab explores a variety of LINQ queries on SharePoint 2010, going into more depth than the introductory hands-on lab. It also walks you through an exercise of creating a custom content type in Visual Studio 2010.

    HOL05 - Developing for SharePoint 2010 with the Client OM and REST in Visual Studio 2010
    This hands-on lab introduces the Client object model for use in calling SharePoint 2010 APIs from a client machine. It also shows the use of ADO.NET Data Services to call REST services in SharePoint 2010.

    HOL06 - Developing a BCS External Content Type with Visual Studio 2010
    This hands-on lab walks you through building an external content type for Business Connectivity Services using Visual Studio 2010. It also builds a form for Microsoft Outlook and shows the data being edited offline in Outlook.

    HOL07 - Developing a SharePoint 2010 Workflow with Initiation Form in Visual Studio 2010
    This hands-on lab walks you through building a workflow in Visual Studio 2010 for SharePoint 2010. You add an initiation form to the workflow and use an external data exchange activity in the workflow.

    HOL08 - Developing SharePoint 2010 User Interface with Silverlight in Visual Studio 2010
    This hands-on lab walks you through building Microsoft Silverlight applications for use in SharePoint 2010. You will access SharePoint 2010 data in Silverlight using the Client object model.

    HOL09 - Developing SharePoint 2010 Sandboxed Solutions in Visual Studio 2010
    This hands-on lab walks you through building a Sandboxed Solution Web Part for SharePoint 2010. It will also add code to the Web Part that overloads the limits placed by the sandboxed solution, and you will review how the solution is shut down.

    HOL10 - Developing SharePoint 2010 User Interface Ribbon and Dialog Customizations
    This hands-on lab walks you through adding a custom action to the SharePoint 2010 ribbon, and creating a Web Part that uses the Dialog Framework.

  • Updated Patterns & Practices Developing SharePoint Applications Guidance

    Congrats to Chris Keyser and all the authors/contributors for shipping the updated Version 2 of the SharePoint Developers Guidance.. must have free resource if you are doing development with SharePoint.

    Guidance for building collaborative applications that extend your LOB systems

    The guidance provides value for experienced developers just starting in SharePoint development as well as experienced SharePoint developers looking to expand their skills.

    If you are new to SharePoint development, the first step is to study the Training Management application, which is based on Windows SharePoint Services. The documentation and the application can help developers understand the fundamentals of SharePoint development, and compliments other training resources and publications.

    For those that already are experienced in developing SharePoint applications, or who have gone through the Training Management application, the Partner Portal application and SharePoint Guidance library demonstrate these advanced areas. You can explore the guidance and Partner Portal reference implementation based upon your areas of interest. The general guidance refers into areas of the reference implementation that illustrate the covered concepts.

    This guide enhances product documentation by applying the information to a realistic business situation illustrated in the reference implementations. In many cases, the guidance refers to the product documentation. You can use the guidance to gain initial understanding. You can then use the product documentation for deeper understanding.

    Quick Links:

    http://www.microsoft.com/spg
    http://www.codeplex.com/spg
    Download here

    What’s included:

    Component

    Description

    SharePoint Guidance Library

    A set of reusable components that helps developers manage configuration, build repositories for SharePoint lists, log traces and events, and use service location.

    Guide

    The documentation includes a variety of topics, such as how to use design and application patterns, how to integrate LOB systems with SharePoint applications, building scalable applications, upgrading SharePoint applications, and using SharePoint capabilities to create, and deploy content. It also includes the design decisions made for the Partner Portal and Training Management applications and explanations of their implementations.

    Contoso Partner Portal Reference Implementation

    This SharePoint application shows how Contoso created an extranet where it can interact with its partners. Among the items demonstrated are techniques for building manageable and scalable enterprise applications, and how to incorporate publishing and page composition features, flexible navigation, collaboration sites, and LOB integration. It includes more advanced techniques than the Training Management reference implementation and requires Microsoft Office SharePoint Server 2007 with Service Pack 1 or Service Pack 2.

    Contoso Training Management Reference Implementation

    This SharePoint application illustrates how the Contoso Human Resources department manages its training course offerings. It shows how to solve many basic SharePoint challenges that you might encounter when you develop your own applications. Windows SharePoint Services 3.0 is required.

    Channel 9 videos

    · Setting up the Contoso RI

    · Walkthrough of the Contoso Reference Implementation

    · How to use the configuration component?

    · How to use the logging components?

    · How to use the SharePoint Service Locator?

    Authors and Contributors

    The Developing SharePoint Applications guidance was produced by the following individuals:

    • Larry Brader, Francis Cheung, RoAnn Corbisier, Nelly Delgado, Chris Keyser, Erwin van der Valk, Blaine Wastell, Hanz Zhang (Microsoft Corporation)
    • Charles Cho, Mike Chorey (Avanade)
    • Kishore Kadiveti, Allvin Muthunayagam, VenkataAppaji Sirangi (Tata Consultancy Services)
    • Colin Campbell, Roberta Leibovitz (Modeled Computation LLC)
    • Robert L. Bogue (Thor Projects LLC)
    • Todd Baginski (Advaiya, Inc)
    • Andrew Connell (Critical Path Training)
    • John Daniels (Analysts International)
    • Tina Burden, Sharon Smith (TinaTech Inc)
    • Veronica Ruiz (CXR Design)
    • Richard Burte (ChannelCatalyst.com, Inc.)

    Many thanks to the following advisors who provided invaluable assistance:

    • Microsoft Contributors and Reviewers: Mike Ammerlaan, Paul Andrew, Luca Bandinelli, Eric Charran, Todd Haugen, Rob Howard, Roger Lamb, Steve Peschka, Jim Sturms, Simon Skaria, Aaron Weiker, Mike Wise
    • External Contributors and Reviewers: Reza Alirezaei, Darrin Bishop, Jackson Chackungal, Spencer Harbar, Faraz Khan, Matthew McDermott, Maurice Prather, Eric Shupps, Ethan Wilansky, Andrew Woodward

    Dd203468.practices(en-us,MSDN.10).png

  • SharePoint STSADM Silverlight application on TechNet

    Go check out the cool new TechNet interactive online Silverlight application which allows you to quickly browse and filter STSADM commands with links to the documentation.

    image

  • Announcing Developer Best Practices Resource Center for SharePoint Server 2007

    Find up-to-date guidance about how to write Microsoft Office SharePoint Server 2007 applications and customizations that perform well, avoid common pitfalls, and best use the features of the SharePoint object model.

    http://msdn.microsoft.com/en-us/office/dd638301.aspx

  • SharePoint Diagnostics Tool v1.0 (SPDiag) Released

    There is a new GUI utility published today to Microsoft.com/downloads for x32 and x64 environments which should help cut down the ping pong performance related troubleshooting discussions between IT staff, support, and developers regarding the SharePoint farm itself. Use the tool to collect data from performance counters, ULS log files, IIS log files, event logs, and WMI (Windows Management Instrumentation), and then display and analyze the data in snapshots and custom reports.  You can read more about the SPDiag tool in the SPDiag User Guide

    Description of the tool directly from the SPDiag User guide:

    The SharePoint Diagnostic tool (SPDiag) version 1.0, included with the latest release of the SharePoint Administration Toolkit, was created to simplify and standardize troubleshooting of SharePoint Products and Technologies, and to provide a unified view of collected data. SharePoint Products and Technologies administrators can use SPDiag to gather relevant information from a farm, display the results in a meaningful way, identify performance issues, and export the collected data and reports for analysis by Microsoft support personnel.

    The SharePoint Products and Technologies platform is highly complex and can be used for a wide variety of uses. Deploying, managing, and troubleshooting SharePoint Products and Technologies requires extensive knowledge spanning multiple technology areas, including security, networking, such Web technologies as ASPX, and SQL Server.

    Traditionally, SharePoint Server troubleshooting involves manually collecting a wide array of data from servers in the affected farm, and then manually analyzing the data to determine the source of the problem. This process can be complex and time-consuming, and data collection itself can place a significant load on the servers.

    SPDiag is designed to collect and review data from SharePoint Products and Technologies Web servers, application servers, and SQL servers, and store the collected data for each project in a SQL Server database for retrieval and analysis. SPDiag can collect performance data from IIS logs, ULS logs, and performance counters, and can also collect live data from the servers using Windows Management Instrumentation (WMI). Data can then be displayed in the Trends pane of the SPDiag interface and filtered to reveal trends, bottlenecks, and other performance issues that would otherwise require significant manual data processing to uncover. You can also view the individual components and the logical structure of the farm in the Snapshot pane.

    SPDiag operates in the context of a project, which is the container used to store collected data for a specific farm. Each project has its own database, and you can create many projects for a single farm, subject only to database server resource limitations. Projects can be saved and reopened again at a later time, and new data can be added to a project between SPDiag sessions. You cannot move data between projects, and you cannot collect data from more than one farm in a single project. Because all SPDiag project data is stored in a SQL Server database, you can back up a project database or move it to another database server.

    SPDiag can be used in online or offline modes. In online mode, SPDiag is installed on a Web server belonging to the farm you want to troubleshoot. This allows SPDiag to connect to the farm and collect data. In offline mode, SPDiag is installed on a computer that is not a part of a farm. It can only be used to review existing SPDiag projects, and cannot collect data.

    You can export collected data and reports as data files, which can then be sent to Microsoft support technicians for analysis. This can help to facilitate remote troubleshooting by ensuring that the required data is captured on-site, and by consolidating the data in a standardized format.

  • Automate SharePoint Dispose() code reviews with SPDisposeCheck

    Today the Microsoft SharePoint Product Team announced the SPDisposeCheck utility here and also at Paul Andrew’s blog here. You can download the free SPDisposeCheck utility in the MSDN Code Gallery http://code.msdn.microsoft.com/SPDisposeCheck .

    The SPDisposeCheck utility will assist you dig through your custom SharePoint MSIL assemblies (DLL’s and EXE’s) looking for areas in your code that may require “closer examination” and might lead to Dispose() related memory leaks.  It’s important to note that this tool is not a replacement for developers to learn and understand the ins and outs of the SharePoint Dispose() guidance and how it is implemented in their custom code.  A manual code review is still required to cast out ‘false positives’ that the tool may produce in the output report.  During internal field tests we received feedback that the tool can help identify areas in the code that may have been overlooked even by the most experienced SharePoint developers. As a final step in development we encourage you to frequently review your ULS logs for Dispose() related leaks that have occurred while the code is executing.  Note SharePoint’s instrumentation writes to the ULS logs when it finds SPSite and SPWeb objects that were not disposed as expected.

    The original MSDN article Best Practices: Using Disposable Windows SharePoint Services Objects was updated 1/30/09 and the Dispose() guidance is in sync with the content on this blog and the SPDisposeCheck tool.  If you have not done so in a while check out my original blog post “SharePoint 2007 and WSS 3.0 Dispose Patterns by Example” which has several updated Dispose() guidance and edge cases including RootWeb and ParentWeb changes.  You can find all the source code examples on this blog in the Visual Studio 2008 solution SPDisposeExamples packaged with the SPDisposeCheck utility installer.

    Understanding the latest Dispose() guidance from Microsoft, scanning with SPDisposeCheck frequently throughout the Software Development Life Cycle (SDLC), and examining the SharePoint ULS logs for evidence of Dispose() related leaks during runtime can help you reduce the probability of unnecessary memory pressure resulting in poor performing SharePoint applications.

  • SharePoint 2007 PublishingWeb.GetVariation() Method Leak

    PublishingWeb.GetVariation() method returns a PublishingWeb object which which needs to be explicitly Closed() as shown in the following code sample.  For a complete list of all the updated SharePoint Dispose() guidance please see SharePoint 2007 and WSS 3.0 Dispose Patterns by Example .

    void GetVariationLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in web so no Close() needed
                VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
                PublishingWeb variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // must be Closed()
                // ...
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    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 web 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 
    }
    

    Special thanks to Keith Dahlby, Stefan Goßner (Microsoft), and Robert Orleth (Microsoft).

  • SharePoint 2007 UserProfiles.PersonalSite Property Leak

    The following edge case applies to MOSS 2007 (and not WSS 3.0).  When using the following pattern the property Microsoft.Office.Server.UserProfiles.PersonalSite requires a Dispose() call before leaving scope if you use the property in your code.  Below is an example of a common usage of PersonalSite property.

    void PersonalSiteLeak()
    {
        // open a site collection
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
            UserProfile profile = profileManager.GetUserProfile("domain\\username");
            SPSite personalSite = profile.PersonalSite;    // will leak
        }
    }
    
    void PersonalSiteNoLeak()
    {
        // open a site collection
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
            UserProfile profile = profileManager.GetUserProfile("domain\\username");
            using (SPSite personalSite = profile.PersonalSite)
            {
                // ...
            }
        }
    }

    From a web context performance perspective it is more efficient to get your UserProfile object in the following example:

    UserProfile myProfile = ProfileLoader.GetProfileLoader().GetUserProfile();
    using (SPSite personalSite = myProfile.PersonalSite)
    {
         // ...
    }

    Note the use of ProfileLoader to get the shared UserProfile instance for my own profile.  There is no need to open a fresh SPSite in the case where you’re browsing a page.  Additionally, if your web part is designed to be placed on a My Site, there is even a shared PersonalSite instance that will be disposed for you and does not require you to call Dispose() with this technique:

    IPersonalPage currentMySitePage = this.Page as IPersonalPage;
    if (currentMySitePage != null && !currentMySitePage.IsProfileError)
    {
         SPSite personalSite = currentMySitePage.PersonalSite; // will not leak
         // ...
    }
    

    Thanks to Microsoft’s Anant Dimiri and Bryant Fong for their contributions!

  • try / finally using() SharePoint Dispose()

    Chances are that by now if you have been developing on the Microsoft SharePoint Office Server (MOSS) 2007 and Windows SharePoint Services (WSS) 3.0 Object Model (OM) for any length of time you are aware of the importance of when to (and when not to) call Dispose() on your SharePoint Objects.  However, you may not be aware that if you do not always wrap your Dispose() method(s) within a finally { } block either implicitly by implementing the using() { } statement or by explicitly wrapping it in your code with try/finally then you you can’t guarantee that your intended objects Dispose() will ever be called during an exception. 

    SharePoint developers are required to be alert and stay on their toes when creating and releasing SPSite and SPWeb objects.  Intimately understand your applications code path(s) and object scope lifetime in order to optimize performance and good memory hygiene with the SharePoint platform is paramount.  Every .NET application (not just SharePoint) must play by the .NET Common Language Runtime (CLR) house rules to ensure that Dispose() gets called (when appropriate) in a timely fashion if you want to avoid very serious negative consequences exacerbated in heavily utilized production SharePoint environments.  You need to make certain and take extra measures to take that code snippet you found which for brevity excluded proper dispose methods and works fine on a developers Virtual PC environment later keeps the business stakeholders up late at night wondering why their customized SharePoint site is having production problems under load.

    Below I discuss some edge cases that you should be aware of when implementing using() and try/finally in your code to help mitigate the risk of memory leaks and help tighten up your production code.

    Understanding the using() statement

    Since you have your SharePoint OM homework you know that you can take advantage of the using() statement to increase the readability and help simplify the the amount of code you have to write to properly release the unmanaged memory held onto by the SharePoint managed code.  Behind the scenes .NET has the CLR automatically inject into your MSIL code a try/finally block (notice I did not say try/catch/finally) and the Dispose() method is getting called on your behalf. 

    public void UsingBestPractice()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                  //...
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }

    Coding with try/finally

    What might not be so commonly known when writing SharePoint code is that there are some cases where we should not implement using().  We do have the option of manually emulating what the CLR does behind the scenes automatically for us by implementing try/finally blocks which contain the respective Dispose() method(s) which ultimately allows our SharePoint IT Administrator(s) to get their much needed beauty sleep.  By the way, there is nothing wrong with adding a try/catch/finally as long as you make certain that you are properly handling the exceptions in the catch { } block and not just eating them without some sort of logging in place.  You do not want to see any empty catch { } blocks in your production code.  Also, note the best practice of conditionally testing for null prior to disposing as shown in the following code. 

    void TryFinallyBestPractice()
    {
        SPSite siteCollection = null;
        SPWeb web = null;

        try
        {
            siteCollection = new SPSite("http://moss");
            web = siteCollection.OpenWeb();
            Console.WriteLine(web.Title);
        }  // optionally catch { ... make sure you handle if you use catch }
        finally
        {
            if (web != null)
                web.Dispose();

            if (siteCollection != null)
                siteCollection.Dispose();
        }
    }

    Don’t use SPContext with using()

    The following example illustrates a common bad practice of wrapping a SPContext originated SPWeb object in a using() statement which as we now know will automatically inject a try/finally that will call web.Dispose() .  In cases where RootWeb equals the SPContext “web” as shown below this can cause production problems since SPContext objects are managed by SharePoint itself and should not be released by you (ever).

    // Bad.. Dispose() is automatically called on web which SPContext equality
    using( SPWeb web = SPControl.GetContextWeb(HttpContext.Current)) { ... }
    Combining OM Calls

    Use caution when combining SharePoint Object Model calls into the same line as these can be some of the most tricky leaks to find.  Dissecting the following example we see:

    • SPContext.Current.Web.Url is fine no dispose needed
    • SPSite is instantiated which needs to be Disposed but is lost since we are also calling OpenWeb() which is actually what using() will Dispose()
    void CombiningCallsLeak()
    {
        using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
        {
            // ... new SPSite will be leaked
        } // SPWeb object web.Dispose() automatically called
    }

    You would have to split the previous sample up into nested using() statements to avoid leaking memory:

    void CombiningCallsBestPractice()
    {
        using (SPSite siteCollection = new SPSite(SPContext.Current.Web.Url))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }
    
    foreach statement and try/finally

    Unfortunately foreach can’t implement using() so extra measures must be taken to make sure your code makes it to the intended Dispose by using the following try/finally pattern in your code.  Use extra caution with any code that is part of a iteration such as foreach because they have a way of turning a small problem in dev into a big problem in production especially when called with navigation or on SharePoint environments with lots of sites.

    public void TryFinallyBestPractice()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                foreach (SPWeb innerWeb in outerWeb.Webs)
                {
                    try //should be 1st statement after foreach
                    {
                        // ... something evil occurs here
                    }
                    finally
                    {
                        if(innerWeb != null)

                            innerWeb.Dispose();
                    }
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }

    SharePoint Memory Internals

    If you’ve made it this far without falling asleep you might be interested in learning more about the SharePoint internals of memory management and why it’s so important for you (the owner of the application code) to know when is the optimal time for performance reasons to hold and release your SharePoint objects.  As SharePoint Application developers you are familiar with the public SPSite and SPWeb objects but internally to get their work done the real managed object that holds onto the unmanaged heap is SPRequestInternalClass which is internal to a wrapper class SPRequest.

    Internally we use a RCW (runtime callable wrapper) which is essentially a finalizable object (there are subtle differences but they don’t really come into play here).    If that object is no longer rooted, the finalizer (teardown of the RCW) will release the native memory.   However, like normal finalizers the RCW teardown is performed by a single finalizer thread which generally can’t keep up with cleaning these objects if they’re being leaked many times per second.

    Not releasing the SharePoint objects in a timely fashion can lead to poor memory hygiene including excessive fragmentation, pinning, and OOM exceptions building very quickly.  Problematic code which fails to properly dispose objects in a timely fashion becomes exacerbated especially in x32bit environments with a large number of sites.  We encourage all Enterprise SharePoint farms to use x64bit versions of the OS and MOSS to take advantage of the additional addressable memory.

    Resources other than just memory are effected by not properly disposing memory.  For example, SQL Server establishes a 1:1 connection with each SPRequest object and it lives up to the release of the internal SPRequest object (which is used by your SPSite and SPWeb object).

    If you’d like to read more perspective on SharePoint internals and also discover ways to look for evidence of dispose related memory leaks in the ULS logs I’d encourage you to read Stefan Goßner’s excellent blog on Disposing SPWeb and SPSite objects .

    Special thanks to my colleagues at Microsoft Dave Aknai, Paul Andrew, Todd Carter, Shawn Cicoria, Stefan Goßner, Scott Harris, Vishwas Kulkarni, Zach Kramer, Randy Thomson, and Sean Thompson.

  • CTP of VSeWSS 1.3 Announced – Now installs on 64bit OS

    Paul Andrew just announced on the Microsoft SharePoint Team Blog that a new Community Technology Preview (CTP) version of the Visual Studio extensions for SharePoint 1.3 (VSeWSS 1.3) is now publically available on Microsoft Connect site.

    New Features in VSeWSS 1.3

    • The extensions now install on x64 bit OS. Visual Studio 2008 and SharePoint must be already installed.
    • Command Line Build option for TFS and MSBuild integration
    • Separate WSP Package and Retract commands. You can now build the WSP without deploying it
    • SPSolGen to Support Exporting from Content Management Publishing Sites
    • New Item Template for RootFiles Deployment
    • Automatically Remove conflicting existing features on development SharePoint server
    • WSP View New Feature Dialog Improvements: scope, receiver checkbox, element checkbox
    • WSP View can now be used to merge features and it blocks site features being merged into web features
    • Allow adding separate binary files such as Workflow assemblies
    • Some refactoring allowing for Web Part renaming and removing lines from feature.xml Item Removed
    • Allow selection of GAC or BIN deployment for Web Part Project not including CAS generation
    • Increase visibility of hidden features that VSeWSS creates
    • Add fast update deploy for DLL only or file only changes to solutions
    • Numerous Bug Fixes and improvements to error messages
  • SharePoint Automated Setup, Product Software Updates, and “Single-Click” Deployment

    MOSS 2007 and WSS 3.0 December 2008 Cumulative Update (CU)

    Blog Updated 12/17/08

    The Microsoft SharePoint Team Blog Announced the December Cumulative Update (CU) for Office SharePoint Server 2007 and Windows SharePoint Services 3.0.  From this point (December 2008) forward each Cumulative Update will consist of a package that contains every hotfix patch that we have shipped including the Infrastructure Update.  This should greatly simplify building MOSS servers and farms going forward.  In summary you can start with WSS 3.0 + SP1 and MOSS 2007 + SP1 plus the Dec CU for both WSS 3.0 and MOSS 2007!

    After applying the December CU the version should be 12.0.6335

    image

    MOSS 2007 and WSS 3.0 Product Software Updates

    As developers you want to ensure you are working with your I.T. departments for building, testing, and deploying your SharePoint software on the latest updated bits from Microsoft.  The best practice going forward is to use the Cumulative Update to build your MOSS 2007 and WSS 3.0 servers but if you want more details on the specific updates prior to the Dec CU check out the following links which will be maintained by the product group.

    Deploy software updates for Windows SharePoint Services 3.0
    http://technet.microsoft.com/en-us/library/cc288269.aspx

    Deploy software updates for Office SharePoint Server 2007
    http://technet.microsoft.com/en-us/library/cc263467.aspx

    MOSS 2007 Automated Setup White Paper

    Emmanuel Bergerat (Microsoft Consulting Services) published the following White Paper: “Using scripts to automate SharePoint Server 2007 installations” to industrialize MOSS 2007 environments setup in a single resource.  This will help SharePoint Developers with deployment and Administrators for repeatability and improve consistency.

    “Single-Click” Deployment Example – Adventure Works Demo Site Installation

    image

    The MOSS MVP’s have a free webcast series ongoing using a new soon to be published Adventure Works Web Application Demo Site.  Ryan Duguid (Microsoft PM SharePoint) and Steve Fox (Microsoft DPE) have been leading this effort and it is very impressive Silverlight 2.0 enabled SharePoint Web Application that hardly looks like a SharePoint WCM site!  One thing I’m most impressed with is what is called the “Single-Click” Web Application Deployment example which allows you to modify a config file with your MOSS Farm environment settings and it will do a complete uninterrupted installation of the entire Adventure Works Demo Site in about 20 minutes (based on your Virtual Environment efficiency)!  What’s very cool for developers and administrators is that you can examine how this is being done since it’s a combination of custom stsadm extensions with batch and config files.  It is very comprehensive setup process and closely resembles real world Internet farms including dual authentication (FBA and Windows Integrated), AD user setup, IIS host headers, SSP, Web application(s), SharePoint Solutions and Features.. everything!  Until the Adventure Works Demo Site is released soon you can begin ramping up by viewing the MOSS MVP’s free ongoing MS Events Webcast presentations (past sessions are recorded) here:

    Date (GMT -0500)
    Topic & Registration URL

    Tues, Dec 2, 2008 : 2p-3p
    Getting Started

    Thurs, Dec 4, 2008 : 2p-3p
    .COM Branding

    Tues, Dec 9, 2008 : 2p-3p
    Custom Fields, Web Parts & Lists

    Thurs, Dec 11, 2008 : 2p-3p
    Authentication

    Tues, Dec 16, 2008 : 2p-3p
    Web Interoperability

    Thurs, Dec 18, 2008 : 2-3p
    Search

    Tues, Jan 6, 2009 : 2-3p
    Content Deployment

    Thurs, Jan 8, 2009 : 2-3p
    Variations & Multilingual Sites

    Tues, Jan 13, 2009 : 2-3p
    Enabling Social Networking

    Thurs, Jan 15, 2009 : 2-3p
    Site Customization with Silverlight 2.0

    SharePoint Guidance (SPG) on Deploying and Upgrading SharePoint Applications

    The folks in the Patterns and Practices team have published many topics in the SharePoint Guidance (SPG) which is downloadable from here.  It includes a fictitious Contoso Pharmaceuticals Training Site which can be manually deployed from Visual Studio Solutions and there is some great guidance you can take offline in the chm help file which installs with the SPG guidance download.  In particular take a look at the Deploying and Upgrading SharePoint Applications .

    image

  • SPDisposeCheck SPSite and SPWeb Dispose() Best Practice Utility Announced

    Paul Andrew (Microsoft SharePoint Product Group) announced the SPDisposeCheck utility at the Tech·Ed EMEA Developers Conference today.  The SPDisposeCheck command line utility will be released soon (North American Winter) and will recursively scan any destination folder that you specify containing custom WSS 3.0 and Microsoft SharePoint Server 2007 .NET assemblies (scanning MSIL and not the source code itself) looking for SharePoint specific Dispose() best practices (or lack thereof) as listed in the guidance on MSDN Best Practices: Using Disposable Windows SharePoint Services Objects , Best Practices: Common Coding Issues When Using the SharePoint Object Model , and my blog SharePoint 2007 and WSS 3.0 Dispose Patterns by Example .  SPDisposeCheck utility is intended to help quickly scan through a large amount of custom SharePoint code in order to direct an experienced SharePoint developer to areas of concern with regards to proper usage of Dispose().

    Additional SPDisposeCheck information:

    • For developer workstations, not to be run on production
    • Built on FX Cop technology the tool opens assemblies and validates them against the Microsoft published guidance (however, not compatible with FX Cop)
    • Output will contain warnings messages for Dispose() method
    • May include “false positives” so expert analysis is required
    • Contact Microsoft support if you need assistance now

    Special thanks to Microsoft’s Sean Thompson (Microsoft PFE), Scott Harris, Paul Andrew, and Stefan Goßner.  In addition, I’d like to thank the folks in the field including the MOSS MVP’s and Microsoft Services and Support (MCS/Premier/PFE/CSS) for their feedback and testing.

  • Updated SPSite.RootWeb Dispose Guidance

    I have recently been working directly with the Microsoft Office SharePoint Server 2007 (MOSS 2007) Product Group as well as several Subject Matter Experts in the Microsoft Services field to help clarify some Dispose edge cases which have been causing confusion which have surfaced in the MOSS Developer community.  Taking a closer look at the RootWeb Dispose Best Practice listed in the MSDN white paper Best Practices: Using Disposable Windows SharePoint Services Objects there is an new exception to the SPSite.RootWeb Dispose guidance.

    Do not explicitly call Dispose() on the SPSite.RootWeb property.  The dispose cleanup will be handled automatically by the SharePoint and the .NET framework.  For existing SharePoint customizations removal of explicit RootWeb Dispose is recommended to avoid an edge case condition where the SPContext.Current.Web has equality to the SPSite.RootWeb.  Problems can occur when disposing RootWeb when obtained from any variation of SPContext (For Example: SPContext.Site.RootWeb, SPContext.Current.Site.RootWeb and GetContextSite(Context).RootWeb ).  Note the owning SPSite object must be properly Disposed (or not Disposed in the case of SPContext) as described here - SharePoint 2007 and WSS 3.0 Dispose Patterns by Example.

    In addition, SPSite properties LockIssue, Owner, and SecondaryContact internally used the RootWeb property.  Based on the updated guidance for RootWeb no explicit Dispose on any of these properties are required.  Again, note the same dependency on properly Disposing the owning SPSite object is in effect.

    public void RootWebBestPractice()
    {
        // Exception to "Best Practices: Using Disposable Windows SharePoint Services Objects" White paper
    
        // Example 1 - new SPSite
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            SPWeb rootWeb1 = siteCollection.RootWeb;
            // No explicit rootWeb1 dispose required
        }  // siteCollection automatically disposed by implementing using()
        // rootWeb1 will be Disposed by SPSite
    
        // Example 2 - SPContext and SPControl
        SPWeb rootWeb2 = SPContext.Current.Site.RootWeb;
        // Also would apply to SPControl.GetContextSite(Context);
        // No explicit rootWeb2 dispose required because it's obtained from SPContext.Current.Site
    }
  • SharePoint 2007 and WSS 3.0 Dispose Patterns by Example

    Last Updated: January 30, 2009

    [New] – The original MSDN article Best Practices: Using Disposable Windows SharePoint Services Objects was updated 1/30/2009 and the Dispose() guidance is now in sync with the content on this blog and the new SPDisposeCheck automated Dispose() code review tool.

    Overview

    Windows SharePoint Services (WSS 3.0) and Microsoft Office SharePoint Server (MOSS 2007) have some gotchas with serious implications that every SharePoint application developer needs to be intimately familiar with before deploying into production MOSS 2007 farms.  In particular, Microsoft.SharePoint.SPSite , Microsoft.SharePoint.SPWeb , and the often overlooked (MOSS 2007) Microsoft.SharePoint.Publishing objects need to be carefully examined and disposed of properly in order to avoid potential memory leaks. My original objective with this blog post was to consolidate several different reliable sources compiled by Microsoft's top Subject Matter Experts (SME’s) into a Uber-Dispose quick reference which could be used to increase developer awareness of the current Microsoft Guidance.  I’ve been working closely with the SharePoint Product Group as well as the top Microsoft Support and Services SME’s to help carve out the information you see here.  I plan to keep this blog post updated with the latest official guidance from Microsoft and while there are more verbose resources available elsewhere the primary objective is to provide lots of samples in a quick reference format.  Pre-requisites: The intended audience for this guidance is a seasoned .NET developer who currently is or will be developing custom SharePoint solutions with Visual Studio 2005/2008.

    Quick Reference - SharePoint Example Dispose() Patterns

    Why Dispose?

    SPSite and SPWeb classes both implement the IDisposable interface.  Microsoft .NET requires objects that implement the IDisposable interface to properly cleanup the unmanaged resources by explicitly calling the Dispose() method when you are finished using them.  Internally, SPSite and SPWeb both hold references to an "internal class Microsoft.SharePoint.Library.SPRequest" which holds on to unmanaged COM resources.  The consequence of not explicitly disposing unmanaged resources in a timely fashion can lead to not having enough memory for further allocations and quickly consumes memory. Under the hood, when reviewing dump files we see the that the managed objects used by SPSite and SPWeb are relatively small and it's the unmanaged resources that are most concerning and account for approximately 1MB to 2MB for each object instance!  Omitting to explicitly call Dispose() means the .NET (non-deterministic) garbage collector gets out of sync with the finalizer and the unmanaged memory does not get reclaimed in a timely manner possibly blocking future memory allocations. For further reading I recommend reviewing Stefan Goßner's blog Dealing with Memory Pressure problems in MOSS/WSS .

    The unmanaged memory leaks can grow very quickly especially when traversing through frequently called areas like site navigation code and item event receivers.  The lack of proper Dispose() hygiene can increase your risk of frequent IIS Application Domain recycles (see Steve Sheppard's blog Overlapped Recycling And SharePoint: Why SharePoint Requires It), Out Of Memory (OOM) exceptions, high memory consumption, and poor performing SharePoint production environments.

    To Dispose or not Dispose?! That is the question...

    To make matters more confusing for SharePoint developers there are times when SPSite and SPWeb objects should not be disposed and are cleaned up by SharePoint and ASP.NET after page processing is completed.  In addition, there are cases when developers indirectly call a property on a object that creates and holds an internal reference to a SPSite or SPWeb object (for example SPSite.ParentWeb property).  Understanding the origin and the scope the object was created is paramount when determining whether or not to explicitly call dispose.

    Dispose Patterns

    When writing customized SharePoint code you need to be aware of the scope and context of each SPSite, SPWeb objects lifetime.  When objects are created and destroyed in the same method or iteration scope (foreach or do/while loop) they are the easiest to clean handle.  Things become more complex to review when developers create objects in one method and dispose in another.  Areas to be aware of are assigning objects to class variables or static/global variables which may hold on to the object reference across method calls.  The content in this blog post is a combination of Product Group Guidance along with any edge cases that have been discovered in the field through support incidents.

    Try / finally using() Dispose()

    Make certain that the objects listed here which need to be properly Disposed by your application code is wrapped within a using(), try/finally, or try/catch/finally block.  Failure to do so can lead to unexpected memory leaks as there is no other way to guarantee that your Dispose will be reached in the event of an exception.  See my updated guidance here.

    Troubleshooting Dispose Related Leaks

    Recently the SPDisposeCheck utility was announced by Paul Andrew from the Microsoft SharePoint Product Group which was published 1/29/09 here.  This command line utility will help scan your custom MOSS and WSS 3.0 .NET assemblies (MSIL not your original source code) automatically scanning for the guidance listed on this blog post.  SPDisposeCheck will produce a summary report calling your attention to areas in your code you that you need to closely examine for possible Dispose() related leaks.  After you have completed your initial scan with SPDisposeCheck you should examine the SharePoint ULS logs to help further verify that no Dispose() edge cases will be introduced into your shared development, test, and production environments.  Stefan Goßner (Microsoft Support Escalation Engineer) has created guidance on using the ULS logs to Troubleshooting SPSite/SPWeb leaks in WSS v3 and MOSS 2007 .  See also Stefan’s Disposing SPWeb and SPSite objects for additional info.  For advanced troubleshooting you can ($) contact Microsoft Support or if you have a Premier Contract you can engage Microsoft Premier Support’s Developer Advisory Services (DAS) or Premier Field Engineering (PFE) resources for advanced troubleshooting, debugging, and proactive advisory services including custom code reviews.

    SharePoint Memory Internals

    400 Level – (Optional read) It’s very important for the developer of the application code to understand when is the optimal time for code optimization and performance reasons to hold on to and release the proper SharePoint objects in a timely fashion.  As SharePoint Application developers you should be familiar with the public SPSite and SPWeb objects but internally to get their work done the real managed object that holds onto the unmanaged heap is SPRequestInternalClass which is internal to a wrapper class SPRequest.

    Internally we use a RCW (runtime callable wrapper) which is essentially a finalizable object (there are subtle differences but they don’t really come into play here).    If that object is no longer rooted, the finalizer (teardown of the RCW) will release the native memory.   However, like normal finalizers the RCW teardown is performed by a single finalizer thread which generally can’t keep up with cleaning these objects if they’re being leaked many times per second.

    Not releasing the SharePoint objects in a timely fashion can lead to poor memory hygiene including excessive fragmentation, pinning, and OOM exceptions building very quickly.  Problematic code which fails to properly dispose objects in a timely fashion becomes exacerbated especially in x32bit environments with a large number of sites.  We encourage all Enterprise SharePoint farms to use x64bit versions of the OS and MOSS to take advantage of the additional addressable memory.

    Note resources other than just memory are effected by not properly disposing your object in a timely fashion.  For example, SQL Server establishes a 1:1 connection with each SPRequest object and it lives up to the release of the internal SPRequest object (which is used by your SPSite and SPWeb object).

    Microsoft.SharePoint.SPList

    • [Updated] - SPList.BreakRoleInheritance() method no longer requires list.ParentWeb.Dispose() to be executed after calling BreakRoleInheritance() due to the updated ParentWeb guidance (see ParentWeb) later in this blog post.

    Microsoft.SharePoint.SPSite

    • [Updated] - RootWeb property no longer requires Dispose() to be called on itself as previously indicated in the Whitepaper Best Practices: Using Disposable Windows SharePoint Services Objects .  See my blog post here for more detail.  In addition, properties LockIssue, Owner, and SecondaryContact internally used the RootWeb property.  Based on the updated Microsoft guidance for RootWeb there is no longer a requirement to explicitly Dispose on any of these properties.  Note that the owning SPSite object must be properly Disposed (or not Disposed in the case of SPContext) as described by the rules listed elsewhere in this blog.

    • new SPSite() operator - Instantiating SPSite objects with the new operator needs to be disposed.

    Note: With C# you can automatically have the Dispose() called for you when the object leaves the scope by wrapping the code with the using() { } statement.

    void CreatingSPSiteLeak()
    {
        SPSite siteCollection = new SPSite("http://moss");
        // siteCollection leaked
    }
    
    void CreatingSPSiteExplicitDisposeNoLeak()
    {
        SPSite siteCollection = null;
        try
        {
            siteCollection = new SPSite("http://moss");
        }
        finally
        {
            if (siteCollection != null)
                siteCollection.Dispose();
        }
    }
    
    CreatingSPSiteWithAutomaticDisposeNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
        } // SPSite object siteCollection.Dispose() automatically called
    }

    Avoid the following pattern which collapses SPSite and SPWeb calls.  The example returns the SPWeb site object wrapped by a using statement which gets disposed but there is no way to dispose the underlying SPSite object.

    void OpenWebLeak()
    {
        using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
        {
            // SPSite leaked !
        } // SPWeb object web.Dispose() automatically called
    }
    
    void OpenWebNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }
    
    • AllWebs[] Indexer returns SPWeb object that needs to be disposed to avoid aggregation of memory which can lead to memory pressure when running on a site collection with large number of sub sites.
    void AllWebsForEachLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                foreach (SPWeb innerWeb in siteCollection.AllWebs)
                {
                    // explicit dispose here to avoid OOM's with large # of webs
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void AllWebsForEachNoLeakOrMemoryOOM()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                foreach (SPWeb innerWeb in siteCollection.AllWebs)
                {
                    try
                    {
                        // ...
                    }
                    finally
                    {
                        if(innerWeb != null)
                            innerWeb.Dispose();
                    }
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void AllWebsIndexerLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            SPWeb web = siteCollection.AllWebs[0];
            // SPWeb web leaked
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void AllWebsIndexerNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.AllWebs[0])
            {
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    void AllWebsAddLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            SPWeb web = siteCollection.AllWebs.Add("site-relative URL");
            // SPWeb web Leaked
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void AllWebsAddNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.AllWebs.Add("site-relative URL"))
            {
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }

    Microsoft.SharePoint.SPWeb

    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 
    }
    
    void SPLimitedWebPartManagerNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                SPFile page = web.GetFile("Source_Folder_Name/Source_Page");
                using (SPLimitedWebPartManager webPartManager = page.GetLimitedWebPartManager(PersonalizationScope.Shared))
                {
                    try
                    {
                        // ...
                    }
                    finally
                    {
                        webPartManager.Web.Dispose();
                    }
                }
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
     
    void WebsLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                foreach (SPWeb innerWeb in outerWeb.Webs)
                {
                    // SPWeb innerWeb leak
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void WebsNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                foreach (SPWeb innerWeb in outerWeb.Webs)
                {
                    try //should be 1st statement after foreach
                    {
                        // ...
                    }
                    finally
                    {
                        if(innerWeb != null)
                            innerWeb.Dispose();
                    }
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    • [Updated] – SPWeb.Webs.Add() method returns a SPWeb object that needs to be disposed.
    void WebsAddLeak(string strWebUrl)
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                SPWeb addedWeb = web.Webs.Add(strWebUrl);   // will leak
    
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }
    
    void WebsAddNoLeak(string strWebUrl)
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                using (SPWeb addedWeb = web.Webs.Add(strWebUrl))
                {
                    //..
                }
    
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called
    }
    

    Microsoft.SharePoint.SPWebCollection

    void SPWebCollectionAddLeak(string strWebUrl)
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                SPWebCollection webCollection = siteCollection.AllWebs; // no AllWebs leak just getting reference
                SPWeb innerWeb = webCollection.Add(strWebUrl);  // must dispose of innerWeb
                // innerWeb Leak
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    void SPWebCollectionAddNoLeak(string strWebUrl)
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb outerWeb = siteCollection.OpenWeb())
            {
                SPWebCollection webCollection = siteCollection.AllWebs; // no AllWebs leak just getting reference
                using (SPWeb innerWeb = webCollection.Add(strWebUrl))
                {
                    //...
                }
            } // SPWeb object outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }

    Microsoft.SharePoint.WebControls.SPControl

    void SPControlBADPractice()
    {
        SPSite siteCollection = SPControl.GetContextSite(Context);
        siteCollection.Dispose();   // DO NOT DO THIS
        SPWeb web = SPControl.GetContextWeb(Context);
        web.Dispose();  // DO NOT DO THIS
    }
    
    void SPControlBestPractice()
    {
        SPSite siteCollection = SPControl.GetContextSite(Context);
        SPWeb web = SPControl.GetContextWeb(Context);
        // Do NOT call Dispose()
    }
    

    Microsoft.SharePoint.SPContext

    void SPContextBADPractice()
    {
        SPSite siteCollection = SPContext.Current.Site;
        siteCollection.Dispose(); // DO NOT DO THIS
        SPWeb web = SPContext.Current.Web;
        web.Dispose(); // DO NOT DO THIS
    }
    
    void SPContextBestPractice()
    {
        SPSite siteCollection = SPContext.Current.Site;
        SPWeb web = SPContext.Current.Web;
        // Do NOT call Dispose()
    }

    Microsoft.SharePoint.Publishing

    void PublishingWebCollectionLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                // passing in web you own, no dispose needed on outerPubWeb
                PublishingWeb outerPubWeb = PublishingWeb.GetPublishingWeb(web);
    
                PublishingWebCollection pubWebCollection = outerPubWeb.GetPublishingWebs();
                foreach (PublishingWeb innerPubWeb in pubWebCollection)
                {
                    // innerPubWeb leak
                }
                // PublishingWeb will leak for each innerPubWeb referenced
            } // SPWeb object web.Dispose() automatically called
        } // SPSite object siteCollection.Dispose() automatically called
    }
    
    void PublishingWebCollectionNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                // passing in web you own, no dispose needed on outerPubWeb
                PublishingWeb outerPubWeb = PublishingWeb.GetPublishingWeb(web);
                PublishingWebCollection pubWebCollection = outerPubWeb.GetPublishingWebs();
                foreach (PublishingWeb innerPubWeb in pubWebCollection)
                {
                    try
                    {
                        // ...
                    }
                    finally
                    {
                        if(innerPubWeb != null)
                            innerPubWeb.Close();
                    }
                }
                // outerPubWeb.Close(); not needed and if called will log warning in ULS log
            }  // SPWeb object web.Dispose() automatically called
        } // SPSite object siteCollection.Dispose() automatically called
    }
    
    void GetPublishingWebNoLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                // passing in web you own, no dispose needed on singlePubWeb
                PublishingWeb singlePubWeb = PublishingWeb.GetPublishingWeb(web);
            } // SPWeb object web.Dispose() automatically called
        } // SPSite object siteCollection.Dispose() automatically called
    }
    
    void GetVariationLeak()
    {
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            using (SPWeb web = siteCollection.OpenWeb())
            {
                PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(web);  // Passing in web so no Close() needed
                VariationLabel variationLabel = Variations.Current.UserAccessibleLabels[0];
                PublishingWeb variationPublishingWeb = publishingWeb.GetVariation(variationLabel);  // must be Closed()
                // ...
            } // SPWeb object web.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    
    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 web 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 outerWeb.Dispose() automatically called
        }  // SPSite object siteCollection.Dispose() automatically called 
    }
    

    Microsoft.Office.Server.UserProfiles

    UserProfiles.PersonalSite requires a Dispose() call before leaving scope if you use the property in your code.  For addition code optimization information please see my blog post here.

    void PersonalSiteLeak()
    {
        // open a site collection
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
            UserProfile profile = profileManager.GetUserProfile("domain\\username");
            SPSite personalSite = profile.PersonalSite;    // will leak
        }
    }
    
    void PersonalSiteNoLeak()
    {
        // open a site collection
        using (SPSite siteCollection = new SPSite("http://moss"))
        {
            UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(siteCollection));
            UserProfile profile = profileManager.GetUserProfile("domain\\username");
            using (SPSite personalSite = profile.PersonalSite)
            {
                // ...
            }
        }
    }

    Microsoft.SharePoint.Administration

    void SPSiteCollectionIndexerLeak()
    {
        using (SPSite siteCollectionOuter = new SPSite("http://moss"))
        {
            SPWebApplication webApp = siteCollectionOuter.WebApplication;
            SPSiteCollection siteCollections = webApp.Sites;
    
            SPSite siteCollectionInner = siteCollections[0];
            // SPSite siteCollectionInner leak 
        } // SPSite object siteCollectionOuter.Dispose() automatically called
    }
    
    void SPSiteCollectionIndexerNoLeak()
    {
        using (SPSite siteCollectionOuter = new SPSite("http://moss"))
        {
            SPSite siteCollectionInner = null;
            try
            {
                SPWebApplication webApp = siteCollectionOuter.WebApplication;
                SPSiteCollection siteCollections = webApp.Sites;
    
                siteCollectionInner = siteCollections[0];
            }
            finally
            {
                if (siteCollectionInner != null)
                    siteCollectionInner.Dispose();
            }
        } // SPSite object siteCollectionOuter.Dispose() automatically called
    }
    
    void SPSiteCollectionForEachLeak()
    {
        using (SPSite siteCollectionOuter = new SPSite("http://moss"))
        {
            SPWebApplication webApp = siteCollectionOuter.WebApplication;
            SPSiteCollection siteCollections = webApp.Sites;
    
            foreach (SPSite siteCollectionInner in siteCollections)
            {
                // SPSite siteCollectionInner leak
            }
        } // SPSite object siteCollectionOuter.Dispose() automatically called
    }
    
    void SPSiteCollectionForEachNoLeak()
    {
        using (SPSite siteCollectionOuter = new SPSite("http://moss"))
        {
            SPWebApplication webApp = siteCollectionOuter.WebApplication;
            SPSiteCollection siteCollections = webApp.Sites;
    
            foreach (SPSite siteCollectionInner in siteCollections)
            {
                try
                {
                    // ...
                }
                finally
                {
                    if(siteCollectionInner != null)
                        siteCollectionInner.Dispose();
                }
            }
        } // SPSite object siteCollectionOuter.Dispose() automatically called
    }
    • Add() returns a SPSite object which needs to be disposed.
    void SPSiteCollectionAddLeak()
    {
        SPWebApplication webApp = new SPSite("http://moss").WebApplication;
        SPSiteCollection siteCollections = webApp.Sites;
        SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\\User", "roger.lamb@litwareinc.com");
        // SPSite siteCollection leak
    }
    
    void SPSiteCollectionAddNoLeak()
    {
        SPWebApplication webApp = new SPSite("http://moss").WebApplication;
        SPSiteCollection siteCollections = webApp.Sites;
        using (SPSite siteCollection = siteCollections.Add("sites/myNewSiteCollection", "DOMAIN\\User", "roger.lamb@litwareinc.com"))
        {
        } // SPSite object siteCollection.Dispose() automatically called
    }

    Microsoft.SharePoint.Portal.SiteData.Area (Obsolete)

    • [Updated] - Area.Web property creates a SPWeb object that needs to be Disposed().  Although the Area class is obsolete in MOSS 2007 it is still of concern when migrating legacy code.
    public void AreaWebLeak()
    {
        // AreaManager and Area are obsolete in MOSS but this should still be noted
        Area area = AreaManager.GetArea(PortalContext.Current, new Guid("{GUID}"));
        SPWeb areaWeb = area.Web;   // this SPWeb object must be disposed
        string str = areaWeb.Title;
        // SPWeb areaWeb leak
    }
    
    public void AreaWebNoLeak()
    {
        // AreaManager and Area are obsolete in MOSS but this should still be noted
        Area area = AreaManager.GetArea(PortalContext.Current, new Guid("{GUID}"));
        using (SPWeb areaWeb = area.Web)
        {
            string str = areaWeb.Title;
        }
    }

    Cross Method Dispose Patterns

    • The following example demonstrates the common practice of holding onto the SPSite and SPWeb objects across methods in a class.  There are times where this design pattern is required however make sure you don't overlook the appropriate time to call dispose when you are finished with the cross method calls.  Below is an example of this pattern and shows and example of a leak of both SPSite and SPWeb when the class is torn down.
    public class CrossMethodLeak
    {
        private SPSite _siteCollection = null;
        private SPWeb _web = null;
    
        public void MethodA()
        {
            _siteCollection = new SPSite("http://moss");
            _web = _siteCollection.OpenWeb();
        }
    
        public void MethodB()
        {
            if (_web != null)
            {
                string title = _web.Title;
            }
        }
    
        public void MethodC()
        {
            if (_web != null)
            {
                string name = _web.Name;
            }
        }
    }
    

    Summary

    If you have extended MOSS 2007 or WSS 3.0 with custom code you should digest this post carefully to avoid expensive consequences commonly found in production environments.  For a more verbose explanation of many of the topics covered in this blog post I suggest you read Scott Harris's MSDN White Papers Best Practices: Using Disposable Windows SharePoint Services Objects and Best Practices: Common Coding Issues When Using the SharePoint Object Model .

    Special thanks to my Microsoft colleagues Scott Harris, Stefan Goßner, Steve Sheppard, Sean Thompson, Lisa Guthrie, Cliff Green, and Rick Caudle for reviewing and helping contribute to this blog post.


© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker