+1-888-365-2779
Try Now
More in this section

Forums / Developing with Sitefinity / Unexpected .net error when overriding CreateChildControls method

Unexpected .net error when overriding CreateChildControls method

3 posts, 0 answered
  1. David van Geel
    David van Geel avatar
    59 posts
    Registered:
    19 Aug 2009
    12 Oct 2011
    Link to this post
    I have created a custom cases module with a standard public view user control. For a new customer I am trying to create a new user control based on the stanadrad public view user control in which I overrride the CreateChildControls and

    CreateDataSource methods. The reason for this is that I am trying to display all the cases attributed to some tags.

    This is the cs of the new user control.

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel;
    using Telerik.Cms.Web.UI;
    using Telerik.Cms.Engine.ContentViewFiltering;
    using Telerik.Cms.Engine;
    using System.Collections;
    using System.Web.UI.WebControls;
     
    /// <summary>
    /// Summary description for FilteredCasesControlBase
    /// </summary>
    [Telerik.Framework.Web.Design.ControlDesigner("FilteredCasesDesigner, App_Code")]
    public class FilteredCasesControlBase : Estate.SitefinityModules.Cases.WebControls.CasesPublicView
    {
        public override string ItemListTemplatePath
        {
            get
            {
                return "~/Estate/UserControls/Cases/FilteredCasesList.ascx";
            }
            set
            {
                base.ItemListTemplatePath = value;
            }
        }
     
        public override string SingleItemTemplatePath
        {
            get
            {
                return "~/Estate/UserControls/Cases/FilteredCasesItem.ascx";
            }
            set
            {
                base.SingleItemTemplatePath = value;
            }
        }
     
        private string filterTags;
        [Category("Filters")]
        [Description("Gets or sets the tags to filter this control by when in list view. Enter tags, separated by commas.")]
        [DisplayName("Tags")]
        public string FilterTags
        {
            get { return this.filterTags; }
            set { this.filterTags = value; }
        }
     
        private void Pager_SelectedPageChanged(object sender, EventArgs e)
        {
            this.CurrentPage = ((Pager)sender).SelectedPage;
            this.ChildControlsCreated = false;
        }
     
        protected override void CreateChildControls()
        {
            if (!string.IsNullOrEmpty(this.FilterTags) && this.AllowPaging)
            {
                if (!string.IsNullOrEmpty(HttpContext.Current.Request.QueryString[PageKey]))
                {
                    this.CurrentPage = Convert.ToInt32(HttpContext.Current.Request.QueryString[PageKey]);
                }
     
                Pager pager = base.ListContainer.GetControl<Pager>("pager1", true);
                if (pager != null)
                {
                    IList dataSource = RetrieveItems();
                    int numberOfPages = dataSource.Count / this.ItemsPerPage;
     
                    if (dataSource.Count % this.ItemsPerPage > 0)
                    {
                        numberOfPages++;
                    }
     
                    pager.SelectedPageChanged += new EventHandler<EventArgs>(Pager_SelectedPageChanged);
                    pager.PageCount = numberOfPages;
                    pager.SelectedPage = this.CurrentPage;
     
                    this.CustomDataSource = dataSource;
                }
     
                base.CreateChildControls();
            }
            else
            {
                base.CreateChildControls();
            }
        }
     
        protected override IList CreateDataSource()
        {
            if (!string.IsNullOrEmpty(this.FilterTags))
            {
                return RetrieveItems();
            }
            else
            {
                return base.CreateDataSource();
            }
        }
     
        private IList RetrieveItems()
        {
            ContentManager manager = new ContentManager("Cases");
            List<IContent> cases = new List<IContent>();
            IList allCases = null;
            if (!string.IsNullOrEmpty(this.FilterExpression))
            {
                ContentFilterBuilder itemFilters = new ContentFilterBuilder(this);
     
                foreach (IContentFilterStatement itemFilter in itemFilters.ParseInternal(true))
                {
                    itemFilters.AddFilter(itemFilter);
                }
     
                allCases = manager.GetContent(0, 99, this.SortExpression, itemFilters.ParseMetaFieldsFilter());
            }
            else
            {
                allCases = manager.GetContent(this.SortExpression);
            }
     
            if (allCases.Count > 0)
            {
                foreach (IContent caseItem in allCases)
                {
                    List<ITag> tags = manager.GetTags(caseItem.ID).OfType<ITag>().ToList();
                    if (tags != null && tags.Any(i => ("," + this.FilterTags + ",").Contains("," + i.ID.ToString())))
                    {
                        cases.Add(caseItem);
                    }
                }
            }
            return cases.ToArray();
        }
    }

    The user control displays the correct cases but I am having a problem with the pager. When I activate it for the user control I get the following .net error.

    Server Error in '/' Application.
    --------------------------------------------------------------------------------
     
    Object reference not set to an instance of an object.
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
     
    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
     
    Source Error:
     
     
    Line 83:             }
    Line 84:
    Line 85:             base.CreateChildControls();
    Line 86:         }
    Line 87:         else
      
     
    Source File: d:\Werkmappen\Projecten\www.tbvwonen.nl.dev\Website\App_Code\Cases\FilteredCasesControlBase.cs    Line: 85
     
    Stack Trace:
     
     
    [NullReferenceException: Object reference not set to an instance of an object.]
       System.Web.UI.WebControls.PagedDataSource.GetEnumerator() +129
       System.Web.UI.WebControls.Repeater.CreateControlHierarchy(Boolean useDataSource) +332
       System.Web.UI.WebControls.Repeater.OnDataBinding(EventArgs e) +51
       System.Web.UI.WebControls.Repeater.DataBind() +75
       Telerik.Cms.Engine.WebControls.ContentView.CreateChildControls() +4853
       FilteredCasesControlBase.CreateChildControls() in d:\Werkmappen\Projecten\www.tbvwonen.nl.dev\Website\App_Code\Cases\FilteredCasesControlBase.cs:85
       System.Web.UI.Control.EnsureChildControls() +87
       System.Web.UI.WebControls.CompositeControl.get_Controls() +15
       Output.FindContainerRecursive(Control root, String id) in D:\Werkmappen\Intern\Estate.SitefinityModules\Standard\SitefinityFunctions\Output.cs:312
       Estate.SitefinityModules.Cases.WebControls.CasesPublicView.OnLoad(EventArgs e) in D:\Werkmappen\Intern\Estate.SitefinityModules\Standard\SitefinityModuleCases\WebControls\CasesPublicView.cs:374
       System.Web.UI.Control.LoadRecursive() +50
       System.Web.UI.Control.AddedControl(Control control, Int32 index) +265
       System.Web.UI.ControlCollection.Add(Control child) +80
       Telerik.Cms.Web.PreviewPage.CreateChildControls() +1335
       System.Web.UI.Control.EnsureChildControls() +87
       System.Web.UI.Control.PreRenderRecursiveInternal() +44
       System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +842
     
      
     
     
    --------------------------------------------------------------------------------
    Version Information: Microsoft .NET Framework Version:2.0.50727.5448; ASP.NET Version:2.0.50727.5420

    Does someone have an idea why that error occurs?

    David

  2. Radoslav Georgiev
    Radoslav Georgiev avatar
    3370 posts
    Registered:
    01 Feb 2016
    17 Oct 2011
    Link to this post
    Hello David Van Geel,

    Can you please let us know from what class the CasesPublicView is derived? If you are inheriting from the built in content view controls, then there is already a pager there which will be populated? It seems that there is something wrong with the data source of the pager. Also the pager needs to be assigned a datasource. Please review how we are setting it up bellow:
    protected virtual void CreateContentList()
    {
        ICollection data;
     
        if (ListContainer.CssFileLink1 != null)
            ListContainer.CssFileLink1.AssemblyInfo = this.AssemblyInfo;
     
        int itemsCount = 0;
         
        if (AllowPaging && (ListContainer.Pager1 != null || ListContainer.Pager2 != null))
        {
            if (RenderPagerAsLink)
            {
                LoadCurrentPageFromUrlIfPossible();
            }
     
            if (isCustomDataSource)
            {
                PagedDataSource pgdDataSource = new PagedDataSource();
                pgdDataSource.DataSource = dataSource;
                pgdDataSource.AllowPaging = true;
                pgdDataSource.PageSize = ItemsPerPage;
                pgdDataSource.CurrentPageIndex = CurrentPage;
                data = pgdDataSource;
            }
            else
            {
                dataSource = CreateDataSource();
                itemsCount = SelectContentCount();
                data = dataSource;
            }
     
            double d = itemsCount / (double)ItemsPerPage;
            int pageCount = (int)Math.Ceiling(d);
            if (ListContainer.Pager1 != null)
            {
                ListContainer.Pager1.RenderPageLinkAsUrl = RenderPagerAsLink;
                // now paging is done through url
                ListContainer.Pager1.SelectedPageChanged += new EventHandler<EventArgs>(Pager_SelectedPageChanged);
                ListContainer.Pager1.PageCount = pageCount;
                ListContainer.Pager1.SelectedPage = CurrentPage;
            }
            if (ListContainer.Pager2 != null)
            {
                ListContainer.Pager2.RenderPageLinkAsUrl = RenderPagerAsLink;
                // now paging is doen through url
                ListContainer.Pager2.SelectedPageChanged += new EventHandler<EventArgs>(Pager_SelectedPageChanged);
                ListContainer.Pager2.PageCount = pageCount;
                ListContainer.Pager2.SelectedPage = CurrentPage;
            }
        }
        else // No paging allowed
        {
            dataSource = CreateDataSource();
            data = dataSource;
        }
     
        // Set the URL to go back to all posts
        if (ListContainer.BackLink != null && CmsContext.CurrentUrl != null)
        {
            ListContainer.BackLink.Visible = tempFilterOn;
             
            if(tempFilterOn)
            {
                string backUrl = CmsContext.CurrentUrl.Path;
                if (!String.IsNullOrEmpty(backUrl))
                {
                    IUrlService svc = UrlServices.GetLanguageService();
     
                    if (svc != null)
                        backUrl = svc.ResolveLanguageUrl(backUrl);
                }
                ListContainer.BackLink.NavigateUrl = backUrl;
            }
        }
     
        Repeater repeater = ListContainer.RepeaterControl;
        repeater.DataSource = data;
        repeater.ItemDataBound += new RepeaterItemEventHandler(repeater_ItemDataBound);
    }

    This is done in CreateContent list method. So instead of overriding CreateChild controls you can override CreateCotnentList

    All the best,
    Radoslav Georgiev
    the Telerik team
    Do you want to have your say in the Sitefinity development roadmap? Do you want to know when a feature you requested is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
  3. David van Geel
    David van Geel avatar
    59 posts
    Registered:
    19 Aug 2009
    18 Oct 2011
    Link to this post
    Hi Radoslav,

    The CasesPublicView user control derived from the ContentView user control.
    public class CasesPublicView : ContentView

    Note that this is a 3.7 SP3 system. Not sure if that matters.

    I tried to apply your example but the associated code is not executed. Not only is it impossible to step through it the end result displays all cases in the module. So NO filtering is done.

    Are you sure that this is the correct apprach? Most of the examples I see in the fora mention overriding the CreateChildControls method instead. I had to add a number of other methods to my code to get your approach to not report errors.

    This is what I ended up with.
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.ComponentModel;
    using Telerik.Cms.Web.UI;
    using Telerik.Cms.Engine.ContentViewFiltering;
    using Telerik.Cms.Engine;
    using System.Collections;
    using System.Web.UI.WebControls;
    using Telerik.Web;
    using Telerik;
    using Telerik.Cms.Engine.WebControls;
    using System.Web.UI;
     
    /// <summary>
    /// Summary description for FilteredCasesControlBase
    /// </summary>
    [Telerik.Framework.Web.Design.ControlDesigner("FilteredCasesDesigner, App_Code")]
    public class FilteredCasesControlBase : Estate.SitefinityModules.Cases.WebControls.CasesPublicView
    {
        public override string ItemListTemplatePath
        {
            get
            {
                return "~/Estate/UserControls/Cases/FilteredCasesList.ascx";
            }
            set
            {
                base.ItemListTemplatePath = value;
            }
        }
     
        public override string SingleItemTemplatePath
        {
            get
            {
                return "~/Estate/UserControls/Cases/FilteredCasesItem.ascx";
            }
            set
            {
                base.SingleItemTemplatePath = value;
            }
        }
     
        private string filterTags;
        [Category("Filters")]
        [Description("Gets or sets the tags to filter this control by when in list view. Enter tags, separated by commas.")]
        [DisplayName("Tags")]
        public string FilterTags
        {
            get { return this.filterTags; }
            set { this.filterTags = value; }
        }
     
        private IList dataSource;
        private bool tempFilterOn;
     
        protected override void CreateContentList(DisplayModes displayMode, Guid itemId)
        {
            this.CreateContentList();
        }
     
        protected virtual void CreateContentList()
        {
            ICollection data;
     
            if (ListContainer.CssFileLink1 != null)
                ListContainer.CssFileLink1.AssemblyInfo = this.AssemblyInfo;
     
            int itemsCount = 0;
     
            if (AllowPaging && (ListContainer.Pager1 != null || ListContainer.Pager2 != null))
            {
                if (RenderPagerAsLink)
                {
                    LoadCurrentPageFromUrlIfPossible();
                }
     
                if (isCustomDataSource)
                {
                    PagedDataSource pgdDataSource = new PagedDataSource();
                    pgdDataSource.DataSource = dataSource;
                    pgdDataSource.AllowPaging = true;
                    pgdDataSource.PageSize = ItemsPerPage;
                    pgdDataSource.CurrentPageIndex = CurrentPage;
                    data = pgdDataSource;
                }
                else
                {
                    dataSource = RetrieveItems(out itemsCount);
                    data = dataSource;
                }
     
                double d = itemsCount / (double)ItemsPerPage;
                int pageCount = (int)Math.Ceiling(d);
                if (ListContainer.Pager1 != null)
                {
                    ListContainer.Pager1.RenderPageLinkAsUrl = RenderPagerAsLink;
                    // now paging is done through url
                    ListContainer.Pager1.SelectedPageChanged += new EventHandler<EventArgs>(Pager_SelectedPageChanged);
                    ListContainer.Pager1.PageCount = pageCount;
                    ListContainer.Pager1.SelectedPage = CurrentPage;
                }
                if (ListContainer.Pager2 != null)
                {
                    ListContainer.Pager2.RenderPageLinkAsUrl = RenderPagerAsLink;
                    // now paging is doen through url
                    ListContainer.Pager2.SelectedPageChanged += new EventHandler<EventArgs>(Pager_SelectedPageChanged);
                    ListContainer.Pager2.PageCount = pageCount;
                    ListContainer.Pager2.SelectedPage = CurrentPage;
                }
            }
            else // No paging allowed
            {
                dataSource = RetrieveItems(out itemsCount);
                data = dataSource;
            }
     
            // Set the URL to go back to all posts
            if (ListContainer.BackLink != null && CmsContext.CurrentUrl != null)
            {
                ListContainer.BackLink.Visible = tempFilterOn;
     
                if (tempFilterOn)
                {
                    string backUrl = CmsContext.CurrentUrl.Path;
                    if (!String.IsNullOrEmpty(backUrl))
                    {
                        IUrlService svc = UrlServices.GetLanguageService();
     
                        if (svc != null)
                            backUrl = svc.ResolveLanguageUrl(backUrl);
                    }
                    ListContainer.BackLink.NavigateUrl = backUrl;
                }
            }
     
            Repeater repeater = ListContainer.RepeaterControl;
            repeater.DataSource = data;
            repeater.ItemDataBound += new RepeaterItemEventHandler(repeater_ItemDataBound);
        }
     
        private IList RetrieveItems(out int noOfCasesFound)
        {
            noOfCasesFound = 0;
            ContentManager manager = new ContentManager("Cases");
            List<IContent> cases = new List<IContent>();
            IList allCases = null;
            if (!string.IsNullOrEmpty(this.FilterExpression))
            {
                ContentFilterBuilder itemFilters = new ContentFilterBuilder(this);
     
                foreach (IContentFilterStatement itemFilter in itemFilters.ParseInternal(true))
                {
                    itemFilters.AddFilter(itemFilter);
                }
     
                allCases = manager.GetContent(0, 999, this.SortExpression, itemFilters.ParseMetaFieldsFilter());
            }
            else
            {
                allCases = manager.GetContent(this.SortExpression);
            }
     
            if (allCases.Count > 0)
            {
                noOfCasesFound = allCases.Count;
                 
                foreach (IContent caseItem in allCases)
                {
                    List<ITag> tags = manager.GetTags(caseItem.ID).OfType<ITag>().ToList();
                    if (tags != null && tags.Any(i => ("," + this.FilterTags + ",").Contains("," + i.ID.ToString())))
                    {
                        cases.Add(caseItem);
                    }
                }
     
                cases = cases.Skip(this.GetContentStartIndex()).Take(this.GetPageSize()).ToList<IContent>();
            }
     
            return cases.ToArray();
        }
     
        private void repeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.AlternatingItem || e.Item.ItemType == ListItemType.Item)
            {
                IContent dataItem1 = (IContent)e.Item.DataItem;
                CommentsList providerNameImpl = this.FindCommentsListControl(e.Item) as CommentsList;
                if (providerNameImpl != null)
                {
                    if (!this.AllowComments)
                    {
                        providerNameImpl.Visible = false;
                        providerNameImpl.Enabled = false;
                    }
                    else
                    {
                        providerNameImpl.ProviderName = this.ProviderNameImpl;
                        providerNameImpl.ParentID = dataItem1.ID;
                        providerNameImpl.Moderation = this.AllowCommentsModeration;
                        providerNameImpl.ValidationGroup = string.Concat("val", Guid.NewGuid());
                    }
                }
                this.SetItemContent(e.Item, dataItem1);
                this.SetItemMetadata(e.Item, dataItem1);
                this.ApplyModeSettings(this.MasterSettings, e.Item);
                return;
            }
            if (e.Item.ItemType == ListItemType.Footer)
            {
                IContent content = (IContent)e.Item.DataItem;
                this.SetItemFooterContent(e.Item, content);
                return;
            }
            if (e.Item.ItemType == ListItemType.Header)
            {
                IContent dataItem2 = (IContent)e.Item.DataItem;
                this.SetItemHeaderContent(e.Item, dataItem2);
            }
        }
     
        private void LoadCurrentPageFromUrlIfPossible()
        {
            int num = this.LoadFromPageUrl();
            if (num > 0)
            {
                base.CurrentPage = num;
            }
        }
     
        private Control FindCommentsListControl(Control container)
        {
            Control control1 = null;
            foreach (Control control2 in container.Controls)
            {
                if (control2 is CommentsList)
                {
                    control1 = control2;
                    break;
                }
                control1 = this.FindCommentsListControl(control2);
            }
            return control1;
        }
     
        private void Pager_SelectedPageChanged(object sender, EventArgs e)
        {
            this.CurrentPage = ((Pager)sender).SelectedPage;
            this.ChildControlsCreated = false;
        }
    }

Register for webinar
3 posts, 0 answered