none
Web part Properties lost when saving page

    Question

  • Hello. I'm fairly new to sharepoint, so this may be quite a simple problem, but i'm not able to solve it.

    I have a customized content query web part, that uses an Enhanced settings toolpart.

    This webpart has worked fine. It had a problem of not showing the "Comments" property of the pages it lists, but i was able to solve it (the problem is referenced here: http://blog.mastykarz.nl/inconvenient-content-query-web-part-slots/). Whenever an user with permissions to edit the web part acesses the page that the content query, it changes the data Mappings property with the correct Comments attribute Id.

    Now, after this, i noticed that i couldn't save the web part properties. Or to explain it in a different way:

    - I enter the edit mode of the web part (the page is checked out), and edit one of the properties (for example, the order of the list). I press the OK button and the properties are applied (the order is changed).

    - I then press the "Save & Close" for the page, and the default properties are once again applied.

    When i debug the web part, the property values are all null/empty (so they are given the default values). This happens in both the custom and default properties.

    Can anyone explain to me what may be causing this? 

    Monday, February 27, 2012 4:47 PM

Answers

  • Hi, Jean, and thanks again.

    That didn't work, but i solved the problem.

    It wasn't that the properties were not saving, but that they were being reseted, meaning in the code above the default values were being forcefully placed in the properties, instead of only being assigned if the property had a null value.

    I didn't think this was it because it only happened when i saved the page, when i confirmed the changes in the web part edit toolpart, it would work fine. Quite strange...

    Anyway, thanks again for the help.

    Wednesday, February 29, 2012 4:12 PM

All replies

  • Hi,

    Try to add in your WebPart class:

     protected override void CreateChildControls()
            {
                // add user control
                VisualWebPart1UserControl control = Page.LoadControl(_ascxPath) as VisualWebPart1UserControl;
                if (control != null)
                {
                    control.WebPart = this;
                    Controls.Add(control);
                    try
                    {
                        this.SaveProperties = true;
                    }
                    catch
                    {
                    }
                }
            }

    Regards,

    Monday, February 27, 2012 7:49 PM
  • Hi, Jean Vionnet, and thanks for the reply.

    Can you please explain the logic of that code?

    I don't use any UserControl, so there's no "_ascxPath" or any variable like that. 

    I do have a progress, though i have no idea how it happened, since i wasn't changing anything in this web part: The custom toolPart properties are now working correctly. However, the default properties (like order, filters, etc) of the web part are still losing their values when i save the page

    Regards

    Tuesday, February 28, 2012 4:35 PM
  • Hi,

    Sorry I understood that you developed a custom Visual WebPart (with the content query WebPart).

    But how is your WebPart developed?

    Regards,

    Tuesday, February 28, 2012 4:40 PM
  • Hi, Jean.

    Unfortunately, i don't know how it was developed, since i'm only doing bug fixing on it and didn't follow it's process.

    However, i'll paste the code here:

    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Globalization;
    using System.Text;
    using System.Web.UI.WebControls.WebParts;
    
    using Microsoft.SharePoint;
    using Microsoft.SharePoint.Publishing;
    using Microsoft.SharePoint.Publishing.WebControls;
    using Microsoft.SharePoint.WebPartPages;
    
    using Intranet.Administration.Constants;
    using Intranet.Presentation.WebParts.Support;
    using Intranet.Diagnostics;
    
    namespace Intranet.Presentation.WebParts
    {
    
        public class ContentQueryWebPart : ContentByQueryWebPart, IPager
        {
            #region Private Variables
            private int _numPages;
            private string _filterFieldName = "PublishingStartDate";
            private bool _listDocuments = false;
    
            private const string fieldIsVisible = "{f1ffa878-d513-4587-a1a4-930cf55d5ffb}"; //ID do campo IsVisible
            private const string fieldPubStartDate = "{51d39414-03dc-4bd0-b777-d3e20cb350f7}"; //ID do campo Publishing Start Date
    
            private enum OpcoesPesquisa
            {
                Valor,
                Data
            }
            #endregion
    
            #region Web Part Connections
            [ConnectionProvider("Paging data", "PagingData", AllowsMultipleConnections = true)]
            public IPager GetPager()
            {
                return this as IPager;
            }
            #endregion
    
            #region Web Part Properties
    
            [WebBrowsable(true), Personalizable(PersonalizationScope.Shared), WebDescription("Filtrar Nome")]
            public string FilterFieldName
            {
                get
                {
                    return _filterFieldName;
                }
                set
                {
                    _filterFieldName = value;
                }
            }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public bool ListDocuments
            {
                get
                {
                    return _listDocuments;
                }
                set
                {
                    _listDocuments = value;
                }
            }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public bool FilterByDate { get; set; }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public int ItemsPerPage { get; set; }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public string PagingQueryStringVariable { get; set; }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public bool UseCaching { get; set; }
            [WebBrowsable(false), Personalizable(PersonalizationScope.Shared)]
            public double CacheTime { get; set; }
    
            #endregion
    
            #region Web Part Methods
    
            public override Microsoft.SharePoint.WebPartPages.ToolPart[] GetToolParts()
            {
                List<ToolPart> customToolPart = new List<ToolPart>(base.GetToolParts());
                customToolPart.Add(new ContentQueryWebPartToolPart());
                
                return customToolPart.ToArray();
            }
    
            protected override void CreateChildControls()
            {
                this.ProcessDataDelegate = new ProcessData(ProcessItems);
                base.CreateChildControls();
            }
    
            protected DataTable ProcessItems(DataTable dt)
            {
                if (ItemsPerPage > 0)
                {
                    int currentPage = 1;
                    _numPages = (int)Math.Ceiling((double)dt.Rows.Count / ItemsPerPage);
    
                    DataTable dataTable = null;
    
                    if (!String.IsNullOrEmpty(PagingQueryStringVariable) &&
                        !String.IsNullOrEmpty(Page.Request.QueryString[PagingQueryStringVariable]) &&
                        Int32.TryParse(Page.Request.QueryString[PagingQueryStringVariable], out currentPage) &&
                        (currentPage < 1 || currentPage > _numPages))
                        currentPage = 1;
    
                    if (UseCaching)
                        dataTable = PartCacheRead(Storage.Shared, "Page" + currentPage.ToString()) as DataTable;
    
                    if (dataTable == null)
                    {
                        int startItemNumber = (currentPage - 1) * ItemsPerPage;
                        int endItemNumber = startItemNumber + (ItemsPerPage - 1);
    
                        dt.Columns.Add("Number", typeof(int));
                        for (int i = 0; i < dt.Rows.Count; i++)
                            dt.Rows[i]["Number"] = i;
    
                        dt.DefaultView.RowFilter = String.Format(CultureInfo.CurrentCulture, "Number >= {0} AND Number <= {1}", startItemNumber, endItemNumber);
    
                        dataTable = dt.DefaultView.ToTable();
    
                        if (UseCaching)
                            PartCacheWrite(Storage.Shared, "Page" + currentPage.ToString(), dataTable, TimeSpan.FromSeconds(CacheTime));
                    }
    
                    dt = dataTable;
                }
    
                return dt;
            }
    
            protected override void OnLoad(EventArgs e)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    OpcoesPesquisa TipoPesquisa;
                    Guid filterFieldID;
    
                    string siteToFilter = string.Empty;
                    SPWeb thisWeb = SPContext.Current.Web;
    
                    //Fix the description field, that fetched the Wrong "Comments" column.
                    //for more information, visit http://blog.mastykarz.nl/inconvenient-content-query-web-part-slots/ and http://aarebrot.net/blog/2010/06/frodes-awesome-list-of-sharepoint-column-field-ids-for-sharepoint-2010/
    
                    if (SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.UpdatePersonalWebParts))
                    {
                        if ((!(this.DataMappings.Contains("Description:|"))) && (this.DataMappings.Contains("Description:")))
                        {
                            string[] parameters = this.DataMappings.Split('|');
                            String fullString = string.Empty;
                            foreach (string property in parameters)
                            {
                                if (!String.IsNullOrEmpty(fullString))
                                {
    
                                    fullString += "|";
                                    if (property.Contains("Description:"))
                                        fullString += "Description:{9da97a8a-1da5-4a77-98d3-4bc10456e700},_Comments,Note;";
                                    else
                                        fullString += property;
                                }
                                else
                                {
                                    if (property.Contains("Description:"))
                                        fullString = "Description:{9da97a8a-1da5-4a77-98d3-4bc10456e700},_Comments,Note;";
                                    else
                                        fullString = property;
                                }
                            }
                            this.DataMappings = fullString;
                            //this.SaveProperties = true;
                        }
                    }
                    
                    if (String.IsNullOrEmpty(this.ItemStyle))
                        this.ItemStyle = "Listagem";
    
                    //using (SPWeb contextWeb = SPContext.Current.Web)
                    //{
                    string webGuid = thisWeb.ServerRelativeUrl;
                    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                    {
                        //  using (SPWeb thisWeb = site.OpenWeb(webGuid))
                        // {
    
                        //SPSite site = SPContext.Current.Site;
                        //SPWeb thisWeb = SPContext.Current.Web;
    
                        //Define número máximo de items a obter.
                        //Limitamos a 10 de 90.
                        if (this.ItemsPerPage == 0)
                        {
                            this.ItemsPerPage = 10;
                        }
                        if (this.ItemLimit == 0)
                        {
                            this.ItemLimit = 100;
                        }
    
    
                        filterFieldID = Microsoft.SharePoint.SPContext.Current.Item.Fields.GetFieldByInternalName(FilterFieldName).Id;
    
                        if (Page.Request.QueryString["Site"] != null && !string.IsNullOrEmpty(Page.Request.QueryString["Site"]))
                        {
                            siteToFilter = Page.Request.QueryString["Site"];
                            try
                            {
                                if (siteToFilter == "Todos")
                                    siteToFilter = SPContext.Current.Web.Url;
                                else
                                    siteToFilter = Encoding.Unicode.GetString(Convert.FromBase64String(siteToFilter));
                            }
                            catch (Exception innerException)
                            {
                                PortalLog logger = new PortalLog();
                                logger.LogToTraceView(PortalLog.LogSeverity.CriticalError, innerException);
                            }
                            siteToFilter = siteToFilter.Replace(SPContext.Current.Site.Url, "");
                        }
                        else //if (string.IsNullOrEmpty(this.WebUrl))
                        {
                            /*
                            siteToFilter = Page.Request.Url.LocalPath;
    
                            string list = Utils.ContextUtils.GetPageListAddr();
                            //if(ListDocuments)
                            //    list = Constants._DOCUMENTS_FOLDER_NAME; //Utils.ContextUtils.GetDocumentListName();
    
                            list = string.Concat("/", list ,"/");
    
                            siteToFilter = siteToFilter.Substring(0, siteToFilter.IndexOf(list));
    
                            */
    
                            siteToFilter = SPContext.Current.Web.Url;
    
                            //if (thisWeb.Webs.Count > 0)
                            //{
                            //int titleTest;
    
                            //using (SPWeb _web = thisWeb.Webs[0])
                            //{
                            //bool numericTitle = int.TryParse(_web.Title, out titleTest);
                            //if (!numericTitle || (numericTitle && titleTest < 2000) || (numericTitle && titleTest > 2030))
                            //{
                            //siteToFilter = _web.Url;
                            //}
                            /*else //No caso da estrutura de sites estar organizada por ano/mes - limitar a pesquisa somente ao mês actual
                            {
                            */
                            if (FilterByDate)
                            {
                                int yearActual = DateTime.Now.Year;
                                int monthActual = DateTime.Now.Month;
                                string monthActualStr = Utils.GlobalUtils.ConvertMonthToString(monthActual);
    
                                siteToFilter = thisWeb.Url + "/" + yearActual + "/" + monthActualStr;
                                siteToFilter = siteToFilter.Replace(site.Url, "");
                                if (siteToFilter.StartsWith("/"))
                                    siteToFilter = siteToFilter.Substring(1);
    
                                using (SPWeb _webFinal = site.OpenWeb(siteToFilter))
                                {
                                    //if (!_webFinal.Exists && monthActual == 3)
                                    //{
                                    //    siteToFilter = _web.Url + "/" + yearActual + "/Marco";
                                    //    _webFinal = site.OpenWeb(siteToFilter);
                                    //}
    
                                    if (!_webFinal.Exists)
                                        siteToFilter = thisWeb.Url;
                                }
                            }
                            //  }
                            //}
                        }
    
                        // No caso de ter sido seleccionado um site que contenha a lista "Documentos"
                        //Obtém dados dessa lista
    
                        siteToFilter = siteToFilter.Replace(SPContext.Current.Site.Url, "");
    
                        using (SPSite siteDocs = new SPSite(thisWeb.Site.Url))
                        {
                            using (SPWeb _web = siteDocs.OpenWeb(siteToFilter))
                            {
                                try
                                {
                                    SPList Doc = _web.Lists[Constants._DOCUMENTS_FOLDER_NAME];
                                    this.ServerTemplate = "101";
                                    this.GroupStyle = "DefaultHeader";
                                    this.ShowUntargetedItems = false;
                                    this.ListDocuments = true;
    
                                    filterFieldID = Microsoft.SharePoint.SPContext.Current.Item.Fields.GetFieldByInternalName("PublishingStartDate").Id;
    
                                }
                                catch (Exception) { }
                            }
                        }
    
                        this.WebUrl = siteToFilter;
    
                        //Restitui valores de filtros por omissão
                        this.FilterField1 = string.Empty;
                        this.FilterValue1 = string.Empty;
    
                        this.FilterField2 = string.Empty;
                        this.FilterValue2 = string.Empty;
    
                        this.FilterField3 = string.Empty;
                        this.FilterValue3 = string.Empty;
    
                        //this.SortBy = string.Empty;
    
                        //Caso o campo IsVisible esteja activo mostra somente elementos com este campo com valores = 1
                        try
                        {
                            if (!ListDocuments)
                            {
                                this.FilterField1 = fieldIsVisible; //Filtra pelo campo IsVisible
                                this.FilterValue1 = "1";
    
                                this.SortBy = fieldPubStartDate; //Faz o ordenamento pelo campo de StartPublishingDate
                                this.SortByDirection = SortDirection.Desc;
                                this.SortByFieldType = "DateTime";
    
                                /*
                                if (Microsoft.SharePoint.SPContext.Current.Item.Fields.GetFieldByInternalName("IsVisible") != null && string.IsNullOrEmpty(this.FilterValue1))
                                {
                                    filterFieldID = Microsoft.SharePoint.SPContext.Current.Item.Fields.GetFieldByInternalName("IsVisible").Id;
    
                                    this.FilterField1 = filterFieldID.ToString();
                                    this.FilterValue1 = "1";
                                }
                                */
                            }
    
                            if (string.IsNullOrEmpty(CommonViewFields))
                            {
                                this.CommonViewFields = "PublishingStartDate, PublishingScheduleStartDateFieldType;_Source,Note";
                            }
                        }
                        catch (Exception innerException)
                        {
                            PortalLog logger = new PortalLog();
                            logger.LogToTraceView(PortalLog.LogSeverity.CriticalError, innerException);
                        }
    
                        //Valida tipo de pesquisa e correcto preenchimento de valores, sendo que 
                        //existem dois tipos de pesquisa (por valor ou por data).
                        if (!string.IsNullOrEmpty(this.Page.Request.QueryString["Field"]))
                        {
                            TipoPesquisa = OpcoesPesquisa.Valor;
                            if (string.IsNullOrEmpty(this.Page.Request.QueryString["Value"]))
                                return;
                        }
                        else if (!string.IsNullOrEmpty(this.Page.Request.QueryString["Year"]) || !string.IsNullOrEmpty(this.Page.Request.QueryString["Month"]))
                        {
                            TipoPesquisa = OpcoesPesquisa.Data;
                        }
                        else if (FilterByDate)
                        {
                            TipoPesquisa = OpcoesPesquisa.Data;
                        }
                        else return;
    
                        // set the chaining of filter values to OR'd
                        this.Filter1ChainingOperator = FilterChainingOperator.And;
                        this.Filter2ChainingOperator = FilterChainingOperator.And;
    
                        //Processa pesquisa por valor
                        if (TipoPesquisa.Equals(OpcoesPesquisa.Valor))
                        {
                            // get the filtering field by name
                            string filterFieldName = this.Page.Request.QueryString["Field"].ToString();
                            // since the field name isn't suffucient for the CQWP, get the field's GUID
    
                            try
                            {
                                filterFieldID = Microsoft.SharePoint.SPContext.Current.Item.Fields.GetFieldByInternalName(filterFieldName).Id;
                                // get the filtering field value
                                string filterFieldValue = this.Page.Request.QueryString["Value"].ToString();
    
                                // set the filtering info
                                this.FilterField2 = filterFieldID.ToString();
    
                                if (filterFieldValue.ToLower().Equals("now"))
                                {
                                    this.FilterType2 = "DateTime";
                                    this.FilterValue2 = DateTime.Now.ToString("u");
                                }
                                else
                                {
                                    this.FilterValue2 = filterFieldValue;
                                }
    
                                //Atribui um operador
                                string filterFieldOper = string.Empty;
                                if (!string.IsNullOrEmpty(this.Page.Request.QueryString["Operator"]))
                                    filterFieldOper = this.Page.Request.QueryString["Operator"];
    
                                switch (filterFieldOper.ToLower())
                                {
                                    case "beginswith":
                                        this.FilterOperator2 = FilterFieldQueryOperator.BeginsWith;
                                        break;
                                    case "contains":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Contains;
                                        break;
                                    case "geq":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Geq;
                                        break;
                                    case "gt":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Gt;
                                        break;
                                    case "leq":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Leq;
                                        break;
                                    case "lt":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Lt;
                                        break;
                                    case "neq":
                                        this.FilterOperator2 = FilterFieldQueryOperator.Neq;
                                        break;
                                    default:
                                        this.FilterOperator2 = FilterFieldQueryOperator.Eq;
                                        break;
                                }
                            }
                            catch (Exception innerException)
                            {
                                PortalLog logger = new PortalLog();
                                logger.LogToTraceView(PortalLog.LogSeverity.CriticalError, innerException);
                            }
                        }
    
                        //Processa pesquisa por data
                        if (TipoPesquisa.Equals(OpcoesPesquisa.Data))
                        {
                            try
                            {
                                // get the filtering field value
    
                                string year = String.Empty;
                                string month = String.Empty;
    
                                if (!String.IsNullOrEmpty(this.Page.Request.QueryString["Year"]))
                                {
                                    year = this.Page.Request.QueryString["Year"].ToString();
                                }
                                if (!String.IsNullOrEmpty(this.Page.Request.QueryString["Month"]))
                                {
                                    month = this.Page.Request.QueryString["Month"].ToString();
                                }
    
                                if (String.IsNullOrEmpty(month)) //if (!String.IsNullOrEmpty(year) && String.IsNullOrEmpty(month))
                                {
                                    month = DateTime.Now.Month.ToString();
                                }
                                if (String.IsNullOrEmpty(year)) //if (!String.IsNullOrEmpty(month) && String.IsNullOrEmpty(year))
                                {
                                    year = DateTime.Now.Year.ToString();
                                }
    
                                if (!month.Equals("Todos") || !year.Equals("Todos")) //ML Só filtra se a opção não for todos/todos
                                {
                                    //ML DateTime fieldValueInicio = new DateTime(int.Parse(year), int.Parse(month), 1); //Mes a pesquisar
                                    //ML DateTime fieldValueFim = fieldValueInicio.AddMonths(1); //Mes a pesquisar + 1
    
                                    DateTime fieldValueInicio = new DateTime();
                                    DateTime fieldValueFim = new DateTime();
    
                                    if (!month.Equals("Todos"))
                                    {
                                        fieldValueInicio = new DateTime(int.Parse(year), int.Parse(month), 1); //Mes a pesquisar
                                        fieldValueFim = fieldValueInicio.AddMonths(1); //Mes a pesquisar + 1
                                    }
                                    else
                                    {
                                        fieldValueInicio = new DateTime(int.Parse(year), 1, 1);
                                        fieldValueFim = fieldValueInicio.AddMonths(12);
                                    }
    
                                    // set the filtering info
                                    if (ListDocuments)
                                    {
                                        this.FilterField1 = filterFieldID.ToString();
                                        this.FilterValue1 = fieldValueInicio.ToString("u");
                                        this.FilterOperator1 = FilterFieldQueryOperator.Geq;
                                        this.FilterType1 = "DateTime";
    
                                        this.FilterField2 = filterFieldID.ToString();
                                        this.FilterValue2 = fieldValueFim.ToString("u");//("yyyy-dd-MM");
                                        this.FilterOperator2 = FilterFieldQueryOperator.Lt;
                                        this.FilterType2 = "DateTime";
                                    }
                                    else
                                    {
                                        this.FilterField2 = filterFieldID.ToString();
                                        this.FilterValue2 = fieldValueInicio.ToString("u");
                                        this.FilterOperator2 = FilterFieldQueryOperator.Geq;
                                        this.FilterType2 = "DateTime";
    
                                        this.FilterField3 = filterFieldID.ToString();
                                        this.FilterValue3 = fieldValueFim.ToString("u");//("yyyy-dd-MM");
                                        this.FilterOperator3 = FilterFieldQueryOperator.Lt;
                                        this.FilterType3 = "DateTime";
                                    }
                                }
    
                            }
                            catch (Exception innerException)
                            {
                                PortalLog logger = new PortalLog();
                                logger.LogToTraceView(PortalLog.LogSeverity.CriticalError, innerException);
                            }
                        }
                    }
                    //}
                });
            }
            #endregion
    
            #region IPager Members
    
            public int PageCount
            {
                get { return _numPages; }
            }
    
            public string QueryStringPageVariable
            {
                get { return PagingQueryStringVariable; }
            }
    
            #endregion
        }
    }

    That is my entire file ContentQueryWebPart.cs file.


    • Edited by senpai2 Tuesday, February 28, 2012 5:21 PM
    Tuesday, February 28, 2012 5:20 PM
  • Okay,

    So try to add:

     try
                    {
                        this.SaveProperties = true;
                    }

    at the end of: CreateChildControls.

    Regards,


    Tuesday, February 28, 2012 6:32 PM
  • Hi, Jean, and thanks again.

    That didn't work, but i solved the problem.

    It wasn't that the properties were not saving, but that they were being reseted, meaning in the code above the default values were being forcefully placed in the properties, instead of only being assigned if the property had a null value.

    I didn't think this was it because it only happened when i saved the page, when i confirmed the changes in the web part edit toolpart, it would work fine. Quite strange...

    Anyway, thanks again for the help.

    Wednesday, February 29, 2012 4:12 PM
  • Okay, nice for you :)

    Regards,

    Wednesday, February 29, 2012 4:55 PM