Take the 2-minute tour ×
SharePoint Stack Exchange is a question and answer site for SharePoint enthusiasts. It's 100% free, no registration required.

i would like to know, whether I should be disposing the SpWeb object or I have closed it and trying to use it?

using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

using Microsoft.SharePoint.WebPartPages;
using System.Text;
using System.Collections;
using System.Collections.Generic;

namespace CrossSite.CrossSiteListViewWebPart
{

             [ToolboxItemAttribute(false)]
             public class CrossSiteListViewWebPart : System.Web.UI.WebControls.WebParts.WebPart
                {

    #region protected child control variable definitions
    protected ListViewByQuery viewByQuery = null;
    protected EncodedLiteral encodedLiteral = null;
    //  public string ValueSendByProviderProperty { get; set; }
    String JSID = String.Empty;
    #endregion

    #region webpart properties
    /// <summary>  
    /// ///    
    /// /// </summary>  
    private string viewNameField = string.Empty;
    [Personalizable(), WebPartStorage(Storage.Shared), WebBrowsable(),
   WebDisplayName("View Name"), WebDescription("View Name")]
    public string ViewName
    {
        get
        {
            return this.viewNameField;
        }
        set
        {
            this.viewNameField = value;
        }
    }
    private string siteUrlField = string.Empty;
    [Personalizable(), WebPartStorage(Storage.Shared), WebBrowsable(),
    WebDisplayName("Site Url"), WebDescription("Site Url")]
    public string SiteUrl
    {
        get
        {
            return this.siteUrlField;
        }
        set
        {
            this.siteUrlField = value;
        }
    }
    /// <summary>   
    /// ///   
    /// /// </summary>  
    private string sourceListField = string.Empty;
    [Personalizable(), WebPartStorage(Storage.Shared), WebBrowsable(),
    WebDisplayName("Source List"), WebDescription("Source list to query")]
    public string SourceList
    {
        get
        {
            return this.sourceListField;
        }
        set
        {
            this.sourceListField = value;
        }
    }
    private Boolean disableFilterField = false;
    [Personalizable(), WebPartStorage(Storage.Shared), WebBrowsable(),
    WebDisplayName("Disable Filter"), WebDescription("Disable List Filtering")]
    public Boolean DisableFilter
    {
        get
        {
            return disableFilterField;
        }
        set
        {
            disableFilterField = value;
        }
    }
    private Boolean disableSortField = false;
    [Personalizable(), WebPartStorage(Storage.Shared), WebBrowsable(),
    WebDisplayName("Disable Sort"), WebDescription("Disable list sorting")]
    public Boolean DisableSort
    {
        get
        {
            return disableSortField;
        }
        set
        {
            this.disableSortField = value;
        }
    }
    #endregion

    public CrossSiteListViewWebPart()
    {

        _filterProviders = new List<Microsoft.SharePoint.WebPartPages.IFilterValues>();

    }
    protected override void CreateChildControls()
    {

        base.CreateChildControls();
        SPSite site = null;
        SPWeb web = null;
        Boolean disposeSPSite = false;

        try
        {
            if (this.SourceList != string.Empty && this.SourceList != string.Empty)
            {
                viewByQuery = new ListViewByQuery();
                if (this.SiteUrl != null && this.SiteUrl != string.Empty)
                {
                    site = new SPSite(this.SiteUrl);
                    disposeSPSite = true;
                }
                else
                {
                    site = SPContext.Current.Site;
                }
                web = site.OpenWeb();
                SPList sourceList = web.Lists[this.SourceList];
                viewByQuery.List = sourceList;
                SPQuery query = null;
                if (CheckIfViewExists(viewByQuery.List))
                {

                    query = new SPQuery(viewByQuery.List.Views[this.ViewName]);
                }
                else
                {

                    query = new SPQuery(viewByQuery.List.DefaultView);
                }
                String str1 = ValueSendByProviderProperty;

                foreach (Microsoft.SharePoint.WebPartPages.IFilterValues filter in FilterProviders)
                {

                    if (filter.ParameterValues != null)
                    {

                        foreach (string item in filter.ParameterValues)
                        {

                            str1 += item;

                        }

                    }

                }

              query.Query = query.Query + " <Where><Contains><FieldRef Name='J_ID' /><Value Type='Text'>" + str1 + "</Value></Contains></Where>";



                query.ViewFields = "<FieldRef Name='LinkFilename'/><FieldRef Name='LinkTitle'/>";


                string queryText = String.Empty;


                string originalQuery = query.Query;
                string neqQuery = String.Empty;

                neqQuery = originalQuery + "<Where>" + queryText + "</Where>";
                viewByQuery.Query = query;
                viewByQuery.DisableFilter = this.DisableFilter;
                viewByQuery.DisableSort = this.DisableSort;

                this.Controls.Add(viewByQuery);

                HyperLink linkAddNew = new HyperLink();
                linkAddNew.Text = "Add New";

                string navigateUrl = string.Format("http://mySite/ab/_layouts/FormServer.aspx?XsnLocation=http://mysite/ab/Details%20Form/Forms/template.xsn&SaveLocation=http://mysite/ab/Details%20Form&ClientInstalled=true&Source=http%3A%2F%2mysite%2Fab%2FDetails%20Form%2FForms%2FBy%20Site.aspx&DefaultItemOpen=0");

                linkAddNew.NavigateUrl = navigateUrl;
                this.Controls.Add(linkAddNew);


            }
            else
            {
                encodedLiteral = new EncodedLiteral();
                encodedLiteral.Text = "This webpart is not configured.";
                this.Controls.Add(encodedLiteral);
            }
        }
        finally
        {
            if (disposeSPSite)
            {
                ((IDisposable)site).Dispose();
                ((IDisposable)web).Dispose();
            }
        }
    }

    protected override void RenderContents(HtmlTextWriter writer)
    {

        EnsureChildControls();
        RenderChildren(writer);
    }

    #region helper methods
    private Boolean CheckIfViewExists(SPList list)
    {
        Boolean ret = false;

        foreach (SPView view in list.Views)
        {
            if (view.Title.ToLower() == this.ViewName.ToLower())
            {
                ret = true;
            }
        }
        return ret;
    }
    #endregion




    private List<Microsoft.SharePoint.WebPartPages.IFilterValues> _filterProviders;

    private List<Microsoft.SharePoint.WebPartPages.IFilterValues> FilterProviders
    {

        get { return _filterProviders; }

    }

    [ConnectionConsumer("filter", "UniqueIDForConsumer", AllowsMultipleConnections = true)]

    public void SetFilter(Microsoft.SharePoint.WebPartPages.IFilterValues filterValues)
    {

        if (filterValues != null)
        {

            List<Microsoft.SharePoint.WebPartPages.ConsumerParameter> parameters = new List<Microsoft.SharePoint.WebPartPages.ConsumerParameter>();

            parameters.Add(new Microsoft.SharePoint.WebPartPages.ConsumerParameter("C_ID", Microsoft.SharePoint.WebPartPages.ConsumerParameterCapabilities.SupportsSingleValue | Microsoft.SharePoint.WebPartPages.ConsumerParameterCapabilities.SupportsAllValue | Microsoft.SharePoint.WebPartPages.ConsumerParameterCapabilities.SupportsEmptyValue));

            filterValues.SetConsumerParameters(new System.Collections.ObjectModel.ReadOnlyCollection<Microsoft.SharePoint.WebPartPages.ConsumerParameter>(parameters));

            this.FilterProviders.Add(filterValues);

        }

    }

    public string ValueSendByProviderProperty { get; set; }


    public string GetUniqueID
    {
        get
        {


            return string.Empty;

        }
    }



}
}
share|improve this question
add comment

2 Answers

In short you as the other answer says, you will need to dispose of those objects as you created them.

However, to help keep the code a bit cleaner, easier to maintain and also so you dont have to create SPWeb lots of times, why not move the SPWeb and SPSite objects out of the function and make them as private members of the class. You can then create the object once and dispose of it when your web part is cleaned up within the Dispose() function.

This is an approach I also take when I want to use SPSite or SPWeb objects within a custom class. Implement the IDisposable interface. With the Dispose() function implemented you can then choose when the objects are disposed of.

Fortunately the WebPart class already implements the IDisposable() function so you can override that with your own implementation.

Finally, I use a similar pattern to one that you have used and create a boolean variable which says whether the dispose function needs to dispose of the object or not.

Anyway here is a quick example, hope it helps:-

public class MyWebPart : System.Web.UI.WebControls.WebParts.WebPart, IDisposable
{

private SPSite _site=null;
private SPWeb _web=null;
private bool _needDisposal=false;

public MyWebPart()
{

}

public void Initialise()
{
if(!String.IsNullOrEmpty(_siteUrl))
{
_site=new SPSite(_siteUrl);
_web=site.OpenWeb()
_needDisposal=true;
}
}
}

/// do stuff


public void Dispose() 
{

if(_needDisposal)
{
  if(_web!=null)
  {
    _web.Dispose();
    _hasBeenDisposed=true;
  }

  if(_site!=null)
  {
    _site.Dispose();
    _hasBeenDisposed=true;
  }
}

}


}
share|improve this answer
add comment

In your case you need to dispose the SPWeb object in both cases as you are using OpenWeb because OpenWeb() returns a SPWeb object which needs to be disposed.
You may be already aware of this but just wanted to put it, here you can replace this statement if (this.SiteUrl != null && this.SiteUrl != string.Empty) with if (!string.IsNullOrEmpty(this.SiteUrl))

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.